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

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

// node_modules/zod/lib/index.mjs
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === errorMap ? void 0 : errorMap
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    var _a5, _b;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a5 = message !== null && message !== void 0 ? message : required_error) !== null && _a5 !== void 0 ? _a5 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let regex2 = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex2 = `${regex2}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex2 = `${regex2}(\\.\\d+)?`;
  }
  return regex2;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex2 = `${regex2}(${opts.join("|")})`;
  return new RegExp(`^${regex2}$`);
}
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base642));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if (!decoded.typ || !decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (_a5) {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val2, step) {
  const valDecCount = (val2.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val2.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
function mergeValues(a3, b3) {
  const aType = getParsedType(a3);
  const bType = getParsedType(b3);
  if (a3 === b3) {
    return { valid: true, data: a3 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b3);
    const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a3, ...b3 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a3[key], b3[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a3.length !== b3.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a3.length; index2++) {
      const itemA = a3[index2];
      const itemB = b3[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b3) {
    return { valid: true, data: a3 };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function custom(check, params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a5, _b;
      if (!check(data)) {
        const p3 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b = (_a5 = p3.fatal) !== null && _a5 !== void 0 ? _a5 : fatal) !== null && _b !== void 0 ? _b : true;
        const p22 = typeof p3 === "string" ? { message: p3 } : p3;
        ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER, z;
var init_lib = __esm({
  "node_modules/zod/lib/index.mjs"() {
    (function(util2) {
      util2.assertEqual = (val2) => val2;
      function assertIs(_arg) {
      }
      util2.assertIs = assertIs;
      function assertNever2(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever2;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number");
        const filtered = {};
        for (const k3 of validKeys) {
          filtered[k3] = obj[k3];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e3) {
          return obj[e3];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr2, checker) => {
        for (const item of arr2) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2;
      function joinValues(array, separator = " | ") {
        return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_2, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second2) => {
        return {
          ...first,
          ...second2
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data) => {
      const t3 = typeof data;
      switch (t3) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return ZodParsedType.array;
          }
          if (data === null) {
            return ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    };
    ZodIssueCode = util.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    quotelessJson = (obj) => {
      const json = JSON.stringify(obj, null, 2);
      return json.replace(/"([^"]+)":/g, "$1:");
    };
    ZodError = class extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error) => {
          for (const issue of error.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i3 = 0;
              while (i3 < issue.path.length) {
                const el = issue.path[i3];
                const terminal = i3 === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i3++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
            fieldErrors[sub.path[0]].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error = new ZodError(issues);
      return error;
    };
    errorMap = (issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodIssueCode.invalid_type:
          if (issue.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue.validation === "object") {
            if ("includes" in issue.validation) {
              message = `Invalid input: must include "${issue.validation.includes}"`;
              if (typeof issue.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
              }
            } else if ("startsWith" in issue.validation) {
              message = `Invalid input: must start with "${issue.validation.startsWith}"`;
            } else if ("endsWith" in issue.validation) {
              message = `Invalid input: must end with "${issue.validation.endsWith}"`;
            } else {
              util.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "bigint")
            message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util.assertNever(issue);
      }
      return { message };
    };
    overrideErrorMap = errorMap;
    makeIssue = (params) => {
      const { data, path, errorMaps, issueData } = params;
      const fullPath = [...path, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m3) => !!m3).slice().reverse();
      for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    ParseStatus = class {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s4 of results) {
          if (s4.status === "aborted")
            return INVALID;
          if (s4.status === "dirty")
            status.dirty();
          arrayValue.push(s4.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x2) => x2.status === "aborted";
    isDirty = (x2) => x2.status === "dirty";
    isValid = (x2) => x2.status === "valid";
    isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
    })(errorUtil || (errorUtil = {}));
    ParseInputLazyPath = class {
      constructor(parent, value, path, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (this._key instanceof Array) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error = new ZodError(ctx.common.issues);
            this._error = error;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        var _a5;
        const ctx = {
          common: {
            issues: [],
            async: (_a5 = params === null || params === void 0 ? void 0 : params.async) !== null && _a5 !== void 0 ? _a5 : false,
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        var _a5, _b;
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if ((_b = (_a5 = err === null || err === void 0 ? void 0 : err.message) === null || _a5 === void 0 ? void 0 : _a5.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
            async: true
          },
          path: (params === null || params === void 0 ? void 0 : params.path) || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = (val2) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val2);
          } else {
            return message;
          }
        };
        return this._refinement((val2, ctx) => {
          const result = check(val2);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val2)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check, refinementData) {
        return this._refinement((val2, ctx) => {
          if (!check(val2)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data) => this["~validate"](data)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch (_a5) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex2 = datetimeRegex(check);
            if (!regex2.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex2 = dateRegex;
            if (!regex2.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex2 = timeRegex(check);
            if (!regex2.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex2, validation, message) {
        return this.refinement((data) => regex2.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        var _a5, _b;
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          offset: (_a5 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a5 !== void 0 ? _a5 : false,
          local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex2, message) {
        return this._addCheck({
          kind: "regex",
          regex: regex2,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options === null || options === void 0 ? void 0 : options.position,
          ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxLength() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodString.create = (params) => {
      var _a5;
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind4, value, inclusive, message) {
        return new ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind: kind4,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max2 = null, min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          } else if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return Number.isFinite(min2) && Number.isFinite(max2);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch (_a5) {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind4, value, inclusive, message) {
        return new ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind: kind4,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodBigInt.create = (params) => {
      var _a5;
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2 != null ? new Date(min2) : null;
      }
      get maxDate() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2 != null ? new Date(max2) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i3) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i3));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i3) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i3));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema, params) => {
      return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        return this._cached = { shape, keys };
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip")
            ;
          else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              var _a5, _b, _c, _d;
              const defaultError = (_c = (_b = (_a5 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a5, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema) {
        return this.augment({ [key]: schema });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index2) {
        return new ZodObject({
          ...this._def,
          catchall: index2
        });
      }
      pick(mask) {
        const shape = {};
        util.objectKeys(mask).forEach((key) => {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        });
        return new ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        });
        return new ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        util.objectKeys(this.shape).forEach((key) => {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        });
        return new ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types, params) => {
      return new ZodUnion({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema = this._def.items[itemIndex] || this._def.rest;
          if (!schema)
            return null;
          return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x2) => !!x2);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second2, third) {
        if (second2 instanceof ZodType) {
          return new ZodRecord({
            keyType: first,
            valueType: second2,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second2)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i3) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i3)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size4, message) {
        return this.min(size4, message).max(size4, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [
              ctx.common.contextualErrorMap,
              ctx.schemaErrorMap,
              getErrorMap(),
              errorMap
            ].filter((x2) => !!x2),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error
            }
          });
        }
        function makeReturnsIssue(returns, error) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [
              ctx.common.contextualErrorMap,
              ctx.schemaErrorMap,
              getErrorMap(),
              errorMap
            ].filter((x2) => !!x2),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e3) => {
              error.addIssue(makeArgsIssue(args, e3));
              throw error;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e3) => {
              error.addIssue(makeReturnsIssue(result, e3));
              throw error;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class extends ZodType {
      constructor() {
        super(...arguments);
        _ZodEnum_cache.set(this, void 0);
      }
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val2 of this._def.values) {
          enumValues[val2] = val2;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    _ZodEnum_cache = /* @__PURE__ */ new WeakMap();
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      constructor() {
        super(...arguments);
        _ZodNativeEnum_cache.set(this, void 0);
      }
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
          __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
        }
        if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    _ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap();
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema, params) => {
      return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base))
              return base;
            const result = effect.transform(base.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
              if (!isValid(base))
                return base;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema, effect, params) => {
      return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
      return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a3, b3) {
        return new ZodPipeline({
          in: a3,
          out: b3,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce = {
      string: (arg) => ZodString.create({ ...arg, coerce: true }),
      number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
      boolean: (arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      }),
      bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
      date: (arg) => ZodDate.create({ ...arg, coerce: true })
    };
    NEVER = INVALID;
    z = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      defaultErrorMap: errorMap,
      setErrorMap,
      getErrorMap,
      makeIssue,
      EMPTY_PATH,
      addIssueToContext,
      ParseStatus,
      INVALID,
      DIRTY,
      OK,
      isAborted,
      isDirty,
      isValid,
      isAsync,
      get util() {
        return util;
      },
      get objectUtil() {
        return objectUtil;
      },
      ZodParsedType,
      getParsedType,
      ZodType,
      datetimeRegex,
      ZodString,
      ZodNumber,
      ZodBigInt,
      ZodBoolean,
      ZodDate,
      ZodSymbol,
      ZodUndefined,
      ZodNull,
      ZodAny,
      ZodUnknown,
      ZodNever,
      ZodVoid,
      ZodArray,
      ZodObject,
      ZodUnion,
      ZodDiscriminatedUnion,
      ZodIntersection,
      ZodTuple,
      ZodRecord,
      ZodMap,
      ZodSet,
      ZodFunction,
      ZodLazy,
      ZodLiteral,
      ZodEnum,
      ZodNativeEnum,
      ZodPromise,
      ZodEffects,
      ZodTransformer: ZodEffects,
      ZodOptional,
      ZodNullable,
      ZodDefault,
      ZodCatch,
      ZodNaN,
      BRAND,
      ZodBranded,
      ZodPipeline,
      ZodReadonly,
      custom,
      Schema: ZodType,
      ZodSchema: ZodType,
      late,
      get ZodFirstPartyTypeKind() {
        return ZodFirstPartyTypeKind;
      },
      coerce,
      any: anyType,
      array: arrayType,
      bigint: bigIntType,
      boolean: booleanType,
      date: dateType,
      discriminatedUnion: discriminatedUnionType,
      effect: effectsType,
      "enum": enumType,
      "function": functionType,
      "instanceof": instanceOfType,
      intersection: intersectionType,
      lazy: lazyType,
      literal: literalType,
      map: mapType,
      nan: nanType,
      nativeEnum: nativeEnumType,
      never: neverType,
      "null": nullType,
      nullable: nullableType,
      number: numberType,
      object: objectType,
      oboolean,
      onumber,
      optional: optionalType,
      ostring,
      pipeline: pipelineType,
      preprocess: preprocessType,
      promise: promiseType,
      record: recordType,
      set: setType,
      strictObject: strictObjectType,
      string: stringType,
      symbol: symbolType,
      transformer: effectsType,
      tuple: tupleType,
      "undefined": undefinedType,
      union: unionType,
      unknown: unknownType,
      "void": voidType,
      NEVER,
      ZodIssueCode,
      quotelessJson,
      ZodError
    });
  }
});

// node_modules/retry/lib/retry_operation.js
var require_retry_operation = __commonJS({
  "node_modules/retry/lib/retry_operation.js"(exports, module2) {
    function RetryOperation(timeouts, options) {
      if (typeof options === "boolean") {
        options = { forever: options };
      }
      this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
      this._timeouts = timeouts;
      this._options = options || {};
      this._maxRetryTime = options && options.maxRetryTime || Infinity;
      this._fn = null;
      this._errors = [];
      this._attempts = 1;
      this._operationTimeout = null;
      this._operationTimeoutCb = null;
      this._timeout = null;
      this._operationStart = null;
      this._timer = null;
      if (this._options.forever) {
        this._cachedTimeouts = this._timeouts.slice(0);
      }
    }
    module2.exports = RetryOperation;
    RetryOperation.prototype.reset = function() {
      this._attempts = 1;
      this._timeouts = this._originalTimeouts.slice(0);
    };
    RetryOperation.prototype.stop = function() {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (this._timer) {
        clearTimeout(this._timer);
      }
      this._timeouts = [];
      this._cachedTimeouts = null;
    };
    RetryOperation.prototype.retry = function(err) {
      if (this._timeout) {
        clearTimeout(this._timeout);
      }
      if (!err) {
        return false;
      }
      var currentTime = new Date().getTime();
      if (err && currentTime - this._operationStart >= this._maxRetryTime) {
        this._errors.push(err);
        this._errors.unshift(new Error("RetryOperation timeout occurred"));
        return false;
      }
      this._errors.push(err);
      var timeout = this._timeouts.shift();
      if (timeout === void 0) {
        if (this._cachedTimeouts) {
          this._errors.splice(0, this._errors.length - 1);
          timeout = this._cachedTimeouts.slice(-1);
        } else {
          return false;
        }
      }
      var self2 = this;
      this._timer = setTimeout(function() {
        self2._attempts++;
        if (self2._operationTimeoutCb) {
          self2._timeout = setTimeout(function() {
            self2._operationTimeoutCb(self2._attempts);
          }, self2._operationTimeout);
          if (self2._options.unref) {
            self2._timeout.unref();
          }
        }
        self2._fn(self2._attempts);
      }, timeout);
      if (this._options.unref) {
        this._timer.unref();
      }
      return true;
    };
    RetryOperation.prototype.attempt = function(fn, timeoutOps) {
      this._fn = fn;
      if (timeoutOps) {
        if (timeoutOps.timeout) {
          this._operationTimeout = timeoutOps.timeout;
        }
        if (timeoutOps.cb) {
          this._operationTimeoutCb = timeoutOps.cb;
        }
      }
      var self2 = this;
      if (this._operationTimeoutCb) {
        this._timeout = setTimeout(function() {
          self2._operationTimeoutCb();
        }, self2._operationTimeout);
      }
      this._operationStart = new Date().getTime();
      this._fn(this._attempts);
    };
    RetryOperation.prototype.try = function(fn) {
      console.log("Using RetryOperation.try() is deprecated");
      this.attempt(fn);
    };
    RetryOperation.prototype.start = function(fn) {
      console.log("Using RetryOperation.start() is deprecated");
      this.attempt(fn);
    };
    RetryOperation.prototype.start = RetryOperation.prototype.try;
    RetryOperation.prototype.errors = function() {
      return this._errors;
    };
    RetryOperation.prototype.attempts = function() {
      return this._attempts;
    };
    RetryOperation.prototype.mainError = function() {
      if (this._errors.length === 0) {
        return null;
      }
      var counts = {};
      var mainError = null;
      var mainErrorCount = 0;
      for (var i3 = 0; i3 < this._errors.length; i3++) {
        var error = this._errors[i3];
        var message = error.message;
        var count5 = (counts[message] || 0) + 1;
        counts[message] = count5;
        if (count5 >= mainErrorCount) {
          mainError = error;
          mainErrorCount = count5;
        }
      }
      return mainError;
    };
  }
});

// node_modules/retry/lib/retry.js
var require_retry = __commonJS({
  "node_modules/retry/lib/retry.js"(exports) {
    var RetryOperation = require_retry_operation();
    exports.operation = function(options) {
      var timeouts = exports.timeouts(options);
      return new RetryOperation(timeouts, {
        forever: options && (options.forever || options.retries === Infinity),
        unref: options && options.unref,
        maxRetryTime: options && options.maxRetryTime
      });
    };
    exports.timeouts = function(options) {
      if (options instanceof Array) {
        return [].concat(options);
      }
      var opts = {
        retries: 10,
        factor: 2,
        minTimeout: 1 * 1e3,
        maxTimeout: Infinity,
        randomize: false
      };
      for (var key in options) {
        opts[key] = options[key];
      }
      if (opts.minTimeout > opts.maxTimeout) {
        throw new Error("minTimeout is greater than maxTimeout");
      }
      var timeouts = [];
      for (var i3 = 0; i3 < opts.retries; i3++) {
        timeouts.push(this.createTimeout(i3, opts));
      }
      if (options && options.forever && !timeouts.length) {
        timeouts.push(this.createTimeout(i3, opts));
      }
      timeouts.sort(function(a3, b3) {
        return a3 - b3;
      });
      return timeouts;
    };
    exports.createTimeout = function(attempt, opts) {
      var random = opts.randomize ? Math.random() + 1 : 1;
      var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
      timeout = Math.min(timeout, opts.maxTimeout);
      return timeout;
    };
    exports.wrap = function(obj, options, methods2) {
      if (options instanceof Array) {
        methods2 = options;
        options = null;
      }
      if (!methods2) {
        methods2 = [];
        for (var key in obj) {
          if (typeof obj[key] === "function") {
            methods2.push(key);
          }
        }
      }
      for (var i3 = 0; i3 < methods2.length; i3++) {
        var method = methods2[i3];
        var original = obj[method];
        obj[method] = function retryWrapper2(original2) {
          var op = exports.operation(options);
          var args = Array.prototype.slice.call(arguments, 1);
          var callback = args.pop();
          args.push(function(err) {
            if (op.retry(err)) {
              return;
            }
            if (err) {
              arguments[0] = op.mainError();
            }
            callback.apply(this, arguments);
          });
          op.attempt(function() {
            original2.apply(obj, args);
          });
        }.bind(obj, original);
        obj[method].options = options;
      }
    };
  }
});

// node_modules/retry/index.js
var require_retry2 = __commonJS({
  "node_modules/retry/index.js"(exports, module2) {
    module2.exports = require_retry();
  }
});

// node_modules/p-retry/index.js
var require_p_retry = __commonJS({
  "node_modules/p-retry/index.js"(exports, module2) {
    "use strict";
    var retry = require_retry2();
    var networkErrorMsgs = [
      "Failed to fetch",
      // Chrome
      "NetworkError when attempting to fetch resource.",
      // Firefox
      "The Internet connection appears to be offline.",
      // Safari
      "Network request failed"
      // `cross-fetch`
    ];
    var AbortError = class extends Error {
      constructor(message) {
        super();
        if (message instanceof Error) {
          this.originalError = message;
          ({ message } = message);
        } else {
          this.originalError = new Error(message);
          this.originalError.stack = this.stack;
        }
        this.name = "AbortError";
        this.message = message;
      }
    };
    var decorateErrorWithCounts = (error, attemptNumber, options) => {
      const retriesLeft = options.retries - (attemptNumber - 1);
      error.attemptNumber = attemptNumber;
      error.retriesLeft = retriesLeft;
      return error;
    };
    var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
    var pRetry4 = (input, options) => new Promise((resolve, reject) => {
      options = {
        onFailedAttempt: () => {
        },
        retries: 10,
        ...options
      };
      const operation = retry.operation(options);
      operation.attempt(async (attemptNumber) => {
        try {
          resolve(await input(attemptNumber));
        } catch (error) {
          if (!(error instanceof Error)) {
            reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
            return;
          }
          if (error instanceof AbortError) {
            operation.stop();
            reject(error.originalError);
          } else if (error instanceof TypeError && !isNetworkError(error.message)) {
            operation.stop();
            reject(error);
          } else {
            decorateErrorWithCounts(error, attemptNumber, options);
            try {
              await options.onFailedAttempt(error);
            } catch (error2) {
              reject(error2);
              return;
            }
            if (!operation.retry(error)) {
              reject(operation.mainError());
            }
          }
        }
      });
    });
    module2.exports = pRetry4;
    module2.exports.default = pRetry4;
    module2.exports.AbortError = AbortError;
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/regex.js
var regex_default;
var init_regex = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/regex.js"() {
    regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/validate.js
function validate(uuid) {
  return typeof uuid === "string" && regex_default.test(uuid);
}
var validate_default;
var init_validate = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/validate.js"() {
    init_regex();
    validate_default = validate;
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/stringify.js
function unsafeStringify(arr2, offset5 = 0) {
  return (byteToHex[arr2[offset5 + 0]] + byteToHex[arr2[offset5 + 1]] + byteToHex[arr2[offset5 + 2]] + byteToHex[arr2[offset5 + 3]] + "-" + byteToHex[arr2[offset5 + 4]] + byteToHex[arr2[offset5 + 5]] + "-" + byteToHex[arr2[offset5 + 6]] + byteToHex[arr2[offset5 + 7]] + "-" + byteToHex[arr2[offset5 + 8]] + byteToHex[arr2[offset5 + 9]] + "-" + byteToHex[arr2[offset5 + 10]] + byteToHex[arr2[offset5 + 11]] + byteToHex[arr2[offset5 + 12]] + byteToHex[arr2[offset5 + 13]] + byteToHex[arr2[offset5 + 14]] + byteToHex[arr2[offset5 + 15]]).toLowerCase();
}
var byteToHex, i3;
var init_stringify = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/stringify.js"() {
    byteToHex = [];
    for (i3 = 0; i3 < 256; ++i3) {
      byteToHex.push((i3 + 256).toString(16).slice(1));
    }
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/rng.js
function rng() {
  if (!getRandomValues) {
    getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues(rnds8);
}
var getRandomValues, rnds8;
var init_rng = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/rng.js"() {
    rnds8 = new Uint8Array(16);
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/native.js
var randomUUID, native_default;
var init_native = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/native.js"() {
    randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
    native_default = {
      randomUUID
    };
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset5) {
  if (native_default.randomUUID && !buf && !options) {
    return native_default.randomUUID();
  }
  options = options || {};
  var rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset5 = offset5 || 0;
    for (var i3 = 0; i3 < 16; ++i3) {
      buf[offset5 + i3] = rnds[i3];
    }
    return buf;
  }
  return unsafeStringify(rnds);
}
var v4_default;
var init_v4 = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/v4.js"() {
    init_native();
    init_rng();
    init_stringify();
    v4_default = v4;
  }
});

// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/index.js
var init_esm_browser = __esm({
  "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/index.js"() {
    init_v4();
    init_validate();
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/regex.js
var regex_default2;
var init_regex2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/regex.js"() {
    regex_default2 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/validate.js
function validate2(uuid) {
  return typeof uuid === "string" && regex_default2.test(uuid);
}
var validate_default2;
var init_validate2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/validate.js"() {
    init_regex2();
    validate_default2 = validate2;
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js
function unsafeStringify2(arr2, offset5 = 0) {
  return (byteToHex2[arr2[offset5 + 0]] + byteToHex2[arr2[offset5 + 1]] + byteToHex2[arr2[offset5 + 2]] + byteToHex2[arr2[offset5 + 3]] + "-" + byteToHex2[arr2[offset5 + 4]] + byteToHex2[arr2[offset5 + 5]] + "-" + byteToHex2[arr2[offset5 + 6]] + byteToHex2[arr2[offset5 + 7]] + "-" + byteToHex2[arr2[offset5 + 8]] + byteToHex2[arr2[offset5 + 9]] + "-" + byteToHex2[arr2[offset5 + 10]] + byteToHex2[arr2[offset5 + 11]] + byteToHex2[arr2[offset5 + 12]] + byteToHex2[arr2[offset5 + 13]] + byteToHex2[arr2[offset5 + 14]] + byteToHex2[arr2[offset5 + 15]]).toLowerCase();
}
var byteToHex2, i3;
var init_stringify2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js"() {
    byteToHex2 = [];
    for (i3 = 0; i3 < 256; ++i3) {
      byteToHex2.push((i3 + 256).toString(16).slice(1));
    }
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/rng.js
function rng2() {
  if (!getRandomValues2) {
    getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues2) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues2(rnds82);
}
var getRandomValues2, rnds82;
var init_rng2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/rng.js"() {
    rnds82 = new Uint8Array(16);
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/native.js
var randomUUID2, native_default2;
var init_native2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/native.js"() {
    randomUUID2 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
    native_default2 = {
      randomUUID: randomUUID2
    };
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/v4.js
function v42(options, buf, offset5) {
  if (native_default2.randomUUID && !buf && !options) {
    return native_default2.randomUUID();
  }
  options = options || {};
  var rnds = options.random || (options.rng || rng2)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset5 = offset5 || 0;
    for (var i3 = 0; i3 < 16; ++i3) {
      buf[offset5 + i3] = rnds[i3];
    }
    return buf;
  }
  return unsafeStringify2(rnds);
}
var v4_default2;
var init_v42 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/v4.js"() {
    init_native2();
    init_rng2();
    init_stringify2();
    v4_default2 = v42;
  }
});

// node_modules/langsmith/node_modules/uuid/dist/esm-browser/index.js
var init_esm_browser2 = __esm({
  "node_modules/langsmith/node_modules/uuid/dist/esm-browser/index.js"() {
    init_v42();
    init_validate2();
  }
});

// node_modules/eventemitter3/index.js
var require_eventemitter3 = __commonJS({
  "node_modules/eventemitter3/index.js"(exports, module2) {
    "use strict";
    var has2 = Object.prototype.hasOwnProperty;
    var prefix = "~";
    function Events() {
    }
    if (Object.create) {
      Events.prototype = /* @__PURE__ */ Object.create(null);
      if (!new Events().__proto__)
        prefix = false;
    }
    function EE(fn, context, once) {
      this.fn = fn;
      this.context = context;
      this.once = once || false;
    }
    function addListener(emitter, event, fn, context, once) {
      if (typeof fn !== "function") {
        throw new TypeError("The listener must be a function");
      }
      var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
      if (!emitter._events[evt])
        emitter._events[evt] = listener, emitter._eventsCount++;
      else if (!emitter._events[evt].fn)
        emitter._events[evt].push(listener);
      else
        emitter._events[evt] = [emitter._events[evt], listener];
      return emitter;
    }
    function clearEvent(emitter, evt) {
      if (--emitter._eventsCount === 0)
        emitter._events = new Events();
      else
        delete emitter._events[evt];
    }
    function EventEmitter() {
      this._events = new Events();
      this._eventsCount = 0;
    }
    EventEmitter.prototype.eventNames = function eventNames() {
      var names = [], events, name;
      if (this._eventsCount === 0)
        return names;
      for (name in events = this._events) {
        if (has2.call(events, name))
          names.push(prefix ? name.slice(1) : name);
      }
      if (Object.getOwnPropertySymbols) {
        return names.concat(Object.getOwnPropertySymbols(events));
      }
      return names;
    };
    EventEmitter.prototype.listeners = function listeners(event) {
      var evt = prefix ? prefix + event : event, handlers = this._events[evt];
      if (!handlers)
        return [];
      if (handlers.fn)
        return [handlers.fn];
      for (var i3 = 0, l4 = handlers.length, ee = new Array(l4); i3 < l4; i3++) {
        ee[i3] = handlers[i3].fn;
      }
      return ee;
    };
    EventEmitter.prototype.listenerCount = function listenerCount(event) {
      var evt = prefix ? prefix + event : event, listeners = this._events[evt];
      if (!listeners)
        return 0;
      if (listeners.fn)
        return 1;
      return listeners.length;
    };
    EventEmitter.prototype.emit = function emit(event, a1, a22, a3, a4, a5) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt])
        return false;
      var listeners = this._events[evt], len = arguments.length, args, i3;
      if (listeners.fn) {
        if (listeners.once)
          this.removeListener(event, listeners.fn, void 0, true);
        switch (len) {
          case 1:
            return listeners.fn.call(listeners.context), true;
          case 2:
            return listeners.fn.call(listeners.context, a1), true;
          case 3:
            return listeners.fn.call(listeners.context, a1, a22), true;
          case 4:
            return listeners.fn.call(listeners.context, a1, a22, a3), true;
          case 5:
            return listeners.fn.call(listeners.context, a1, a22, a3, a4), true;
          case 6:
            return listeners.fn.call(listeners.context, a1, a22, a3, a4, a5), true;
        }
        for (i3 = 1, args = new Array(len - 1); i3 < len; i3++) {
          args[i3 - 1] = arguments[i3];
        }
        listeners.fn.apply(listeners.context, args);
      } else {
        var length = listeners.length, j3;
        for (i3 = 0; i3 < length; i3++) {
          if (listeners[i3].once)
            this.removeListener(event, listeners[i3].fn, void 0, true);
          switch (len) {
            case 1:
              listeners[i3].fn.call(listeners[i3].context);
              break;
            case 2:
              listeners[i3].fn.call(listeners[i3].context, a1);
              break;
            case 3:
              listeners[i3].fn.call(listeners[i3].context, a1, a22);
              break;
            case 4:
              listeners[i3].fn.call(listeners[i3].context, a1, a22, a3);
              break;
            default:
              if (!args)
                for (j3 = 1, args = new Array(len - 1); j3 < len; j3++) {
                  args[j3 - 1] = arguments[j3];
                }
              listeners[i3].fn.apply(listeners[i3].context, args);
          }
        }
      }
      return true;
    };
    EventEmitter.prototype.on = function on(event, fn, context) {
      return addListener(this, event, fn, context, false);
    };
    EventEmitter.prototype.once = function once(event, fn, context) {
      return addListener(this, event, fn, context, true);
    };
    EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
      var evt = prefix ? prefix + event : event;
      if (!this._events[evt])
        return this;
      if (!fn) {
        clearEvent(this, evt);
        return this;
      }
      var listeners = this._events[evt];
      if (listeners.fn) {
        if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
          clearEvent(this, evt);
        }
      } else {
        for (var i3 = 0, events = [], length = listeners.length; i3 < length; i3++) {
          if (listeners[i3].fn !== fn || once && !listeners[i3].once || context && listeners[i3].context !== context) {
            events.push(listeners[i3]);
          }
        }
        if (events.length)
          this._events[evt] = events.length === 1 ? events[0] : events;
        else
          clearEvent(this, evt);
      }
      return this;
    };
    EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
      var evt;
      if (event) {
        evt = prefix ? prefix + event : event;
        if (this._events[evt])
          clearEvent(this, evt);
      } else {
        this._events = new Events();
        this._eventsCount = 0;
      }
      return this;
    };
    EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
    EventEmitter.prototype.addListener = EventEmitter.prototype.on;
    EventEmitter.prefixed = prefix;
    EventEmitter.EventEmitter = EventEmitter;
    if ("undefined" !== typeof module2) {
      module2.exports = EventEmitter;
    }
  }
});

// node_modules/p-finally/index.js
var require_p_finally = __commonJS({
  "node_modules/p-finally/index.js"(exports, module2) {
    "use strict";
    module2.exports = (promise, onFinally) => {
      onFinally = onFinally || (() => {
      });
      return promise.then(
        (val2) => new Promise((resolve) => {
          resolve(onFinally());
        }).then(() => val2),
        (err) => new Promise((resolve) => {
          resolve(onFinally());
        }).then(() => {
          throw err;
        })
      );
    };
  }
});

// node_modules/p-timeout/index.js
var require_p_timeout = __commonJS({
  "node_modules/p-timeout/index.js"(exports, module2) {
    "use strict";
    var pFinally = require_p_finally();
    var TimeoutError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "TimeoutError";
      }
    };
    var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {
      if (typeof milliseconds !== "number" || milliseconds < 0) {
        throw new TypeError("Expected `milliseconds` to be a positive number");
      }
      if (milliseconds === Infinity) {
        resolve(promise);
        return;
      }
      const timer = setTimeout(() => {
        if (typeof fallback === "function") {
          try {
            resolve(fallback());
          } catch (error) {
            reject(error);
          }
          return;
        }
        const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
        const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
        if (typeof promise.cancel === "function") {
          promise.cancel();
        }
        reject(timeoutError);
      }, milliseconds);
      pFinally(
        // eslint-disable-next-line promise/prefer-await-to-then
        promise.then(resolve, reject),
        () => {
          clearTimeout(timer);
        }
      );
    });
    module2.exports = pTimeout;
    module2.exports.default = pTimeout;
    module2.exports.TimeoutError = TimeoutError;
  }
});

// node_modules/p-queue/dist/lower-bound.js
var require_lower_bound = __commonJS({
  "node_modules/p-queue/dist/lower-bound.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function lowerBound(array, value, comparator) {
      let first = 0;
      let count5 = array.length;
      while (count5 > 0) {
        const step = count5 / 2 | 0;
        let it = first + step;
        if (comparator(array[it], value) <= 0) {
          first = ++it;
          count5 -= step + 1;
        } else {
          count5 = step;
        }
      }
      return first;
    }
    exports.default = lowerBound;
  }
});

// node_modules/p-queue/dist/priority-queue.js
var require_priority_queue = __commonJS({
  "node_modules/p-queue/dist/priority-queue.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var lower_bound_1 = require_lower_bound();
    var PriorityQueue = class {
      constructor() {
        this._queue = [];
      }
      enqueue(run, options) {
        options = Object.assign({ priority: 0 }, options);
        const element = {
          priority: options.priority,
          run
        };
        if (this.size && this._queue[this.size - 1].priority >= options.priority) {
          this._queue.push(element);
          return;
        }
        const index2 = lower_bound_1.default(this._queue, element, (a3, b3) => b3.priority - a3.priority);
        this._queue.splice(index2, 0, element);
      }
      dequeue() {
        const item = this._queue.shift();
        return item === null || item === void 0 ? void 0 : item.run;
      }
      filter(options) {
        return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
      }
      get size() {
        return this._queue.length;
      }
    };
    exports.default = PriorityQueue;
  }
});

// node_modules/p-queue/dist/index.js
var require_dist = __commonJS({
  "node_modules/p-queue/dist/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var EventEmitter = require_eventemitter3();
    var p_timeout_1 = require_p_timeout();
    var priority_queue_1 = require_priority_queue();
    var empty = () => {
    };
    var timeoutError = new p_timeout_1.TimeoutError();
    var PQueue = class extends EventEmitter {
      constructor(options) {
        var _a5, _b, _c, _d;
        super();
        this._intervalCount = 0;
        this._intervalEnd = 0;
        this._pendingCount = 0;
        this._resolveEmpty = empty;
        this._resolveIdle = empty;
        options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);
        if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
          throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a5 = options.intervalCap) === null || _a5 === void 0 ? void 0 : _a5.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`);
        }
        if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
          throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`);
        }
        this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;
        this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;
        this._intervalCap = options.intervalCap;
        this._interval = options.interval;
        this._queue = new options.queueClass();
        this._queueClass = options.queueClass;
        this.concurrency = options.concurrency;
        this._timeout = options.timeout;
        this._throwOnTimeout = options.throwOnTimeout === true;
        this._isPaused = options.autoStart === false;
      }
      get _doesIntervalAllowAnother() {
        return this._isIntervalIgnored || this._intervalCount < this._intervalCap;
      }
      get _doesConcurrentAllowAnother() {
        return this._pendingCount < this._concurrency;
      }
      _next() {
        this._pendingCount--;
        this._tryToStartAnother();
        this.emit("next");
      }
      _resolvePromises() {
        this._resolveEmpty();
        this._resolveEmpty = empty;
        if (this._pendingCount === 0) {
          this._resolveIdle();
          this._resolveIdle = empty;
          this.emit("idle");
        }
      }
      _onResumeInterval() {
        this._onInterval();
        this._initializeIntervalIfNeeded();
        this._timeoutId = void 0;
      }
      _isIntervalPaused() {
        const now3 = Date.now();
        if (this._intervalId === void 0) {
          const delay = this._intervalEnd - now3;
          if (delay < 0) {
            this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
          } else {
            if (this._timeoutId === void 0) {
              this._timeoutId = setTimeout(() => {
                this._onResumeInterval();
              }, delay);
            }
            return true;
          }
        }
        return false;
      }
      _tryToStartAnother() {
        if (this._queue.size === 0) {
          if (this._intervalId) {
            clearInterval(this._intervalId);
          }
          this._intervalId = void 0;
          this._resolvePromises();
          return false;
        }
        if (!this._isPaused) {
          const canInitializeInterval = !this._isIntervalPaused();
          if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {
            const job = this._queue.dequeue();
            if (!job) {
              return false;
            }
            this.emit("active");
            job();
            if (canInitializeInterval) {
              this._initializeIntervalIfNeeded();
            }
            return true;
          }
        }
        return false;
      }
      _initializeIntervalIfNeeded() {
        if (this._isIntervalIgnored || this._intervalId !== void 0) {
          return;
        }
        this._intervalId = setInterval(() => {
          this._onInterval();
        }, this._interval);
        this._intervalEnd = Date.now() + this._interval;
      }
      _onInterval() {
        if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {
          clearInterval(this._intervalId);
          this._intervalId = void 0;
        }
        this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
        this._processQueue();
      }
      /**
      Executes all queued functions until it reaches the limit.
      */
      _processQueue() {
        while (this._tryToStartAnother()) {
        }
      }
      get concurrency() {
        return this._concurrency;
      }
      set concurrency(newConcurrency) {
        if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
          throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
        }
        this._concurrency = newConcurrency;
        this._processQueue();
      }
      /**
      Adds a sync or async task to the queue. Always returns a promise.
      */
      async add(fn, options = {}) {
        return new Promise((resolve, reject) => {
          const run = async () => {
            this._pendingCount++;
            this._intervalCount++;
            try {
              const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => {
                if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) {
                  reject(timeoutError);
                }
                return void 0;
              });
              resolve(await operation);
            } catch (error) {
              reject(error);
            }
            this._next();
          };
          this._queue.enqueue(run, options);
          this._tryToStartAnother();
          this.emit("add");
        });
      }
      /**
          Same as `.add()`, but accepts an array of sync or async functions.
      
          @returns A promise that resolves when all functions are resolved.
          */
      async addAll(functions, options) {
        return Promise.all(functions.map(async (function_) => this.add(function_, options)));
      }
      /**
      Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
      */
      start() {
        if (!this._isPaused) {
          return this;
        }
        this._isPaused = false;
        this._processQueue();
        return this;
      }
      /**
      Put queue execution on hold.
      */
      pause() {
        this._isPaused = true;
      }
      /**
      Clear the queue.
      */
      clear() {
        this._queue = new this._queueClass();
      }
      /**
          Can be called multiple times. Useful if you for example add additional items at a later time.
      
          @returns A promise that settles when the queue becomes empty.
          */
      async onEmpty() {
        if (this._queue.size === 0) {
          return;
        }
        return new Promise((resolve) => {
          const existingResolve = this._resolveEmpty;
          this._resolveEmpty = () => {
            existingResolve();
            resolve();
          };
        });
      }
      /**
          The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
      
          @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
          */
      async onIdle() {
        if (this._pendingCount === 0 && this._queue.size === 0) {
          return;
        }
        return new Promise((resolve) => {
          const existingResolve = this._resolveIdle;
          this._resolveIdle = () => {
            existingResolve();
            resolve();
          };
        });
      }
      /**
      Size of the queue.
      */
      get size() {
        return this._queue.size;
      }
      /**
          Size of the queue, filtered by the given options.
      
          For example, this can be used to find the number of items remaining in the queue with a specific priority level.
          */
      sizeBy(options) {
        return this._queue.filter(options).length;
      }
      /**
      Number of pending promises.
      */
      get pending() {
        return this._pendingCount;
      }
      /**
      Whether the queue is currently paused.
      */
      get isPaused() {
        return this._isPaused;
      }
      get timeout() {
        return this._timeout;
      }
      /**
      Set the timeout for future operations.
      */
      set timeout(milliseconds) {
        this._timeout = milliseconds;
      }
    };
    exports.default = PQueue;
  }
});

// node_modules/langsmith/dist/singletons/fetch.js
var DEFAULT_FETCH_IMPLEMENTATION, LANGSMITH_FETCH_IMPLEMENTATION_KEY, _getFetchImplementation;
var init_fetch = __esm({
  "node_modules/langsmith/dist/singletons/fetch.js"() {
    DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args);
    LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation");
    _getFetchImplementation = () => {
      return globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION;
    };
  }
});

// node_modules/langsmith/dist/utils/async_caller.js
var import_p_retry, import_p_queue, STATUS_NO_RETRY, STATUS_IGNORE, AsyncCaller;
var init_async_caller = __esm({
  "node_modules/langsmith/dist/utils/async_caller.js"() {
    import_p_retry = __toESM(require_p_retry(), 1);
    import_p_queue = __toESM(require_dist(), 1);
    init_fetch();
    STATUS_NO_RETRY = [
      400,
      // Bad Request
      401,
      // Unauthorized
      403,
      // Forbidden
      404,
      // Not Found
      405,
      // Method Not Allowed
      406,
      // Not Acceptable
      407,
      // Proxy Authentication Required
      408
      // Request Timeout
    ];
    STATUS_IGNORE = [
      409
      // Conflict
    ];
    AsyncCaller = class {
      constructor(params) {
        Object.defineProperty(this, "maxConcurrency", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "maxRetries", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "queue", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "onFailedResponseHook", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.maxConcurrency = params.maxConcurrency ?? Infinity;
        this.maxRetries = params.maxRetries ?? 6;
        if ("default" in import_p_queue.default) {
          this.queue = new import_p_queue.default.default({
            concurrency: this.maxConcurrency
          });
        } else {
          this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency });
        }
        this.onFailedResponseHook = params?.onFailedResponseHook;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      call(callable, ...args) {
        const onFailedResponseHook = this.onFailedResponseHook;
        return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => {
          if (error instanceof Error) {
            throw error;
          } else {
            throw new Error(error);
          }
        }), {
          async onFailedAttempt(error) {
            if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) {
              throw error;
            }
            if (error?.code === "ECONNABORTED") {
              throw error;
            }
            const response = error?.response;
            const status = response?.status;
            if (status) {
              if (STATUS_NO_RETRY.includes(+status)) {
                throw error;
              } else if (STATUS_IGNORE.includes(+status)) {
                return;
              }
              if (onFailedResponseHook) {
                await onFailedResponseHook(response);
              }
            }
          },
          // If needed we can change some of the defaults here,
          // but they're quite sensible.
          retries: this.maxRetries,
          randomize: true
        }), { throwOnTimeout: true });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      callWithOptions(options, callable, ...args) {
        if (options.signal) {
          return Promise.race([
            this.call(callable, ...args),
            new Promise((_2, reject) => {
              options.signal?.addEventListener("abort", () => {
                reject(new Error("AbortError"));
              });
            })
          ]);
        }
        return this.call(callable, ...args);
      }
      fetch(...args) {
        return this.call(() => _getFetchImplementation()(...args).then((res) => res.ok ? res : Promise.reject(res)));
      }
    };
  }
});

// node_modules/langsmith/dist/utils/messages.js
function isLangChainMessage(message) {
  return typeof message?._getType === "function";
}
function convertLangChainMessageToExample(message) {
  const converted = {
    type: message._getType(),
    data: { content: message.content }
  };
  if (message?.additional_kwargs && Object.keys(message.additional_kwargs).length > 0) {
    converted.data.additional_kwargs = { ...message.additional_kwargs };
  }
  return converted;
}
var init_messages = __esm({
  "node_modules/langsmith/dist/utils/messages.js"() {
  }
});

// node_modules/langsmith/dist/utils/_uuid.js
function assertUuid(str2, which) {
  if (!validate_default2(str2)) {
    const msg = which !== void 0 ? `Invalid UUID for ${which}: ${str2}` : `Invalid UUID: ${str2}`;
    throw new Error(msg);
  }
  return str2;
}
var init_uuid = __esm({
  "node_modules/langsmith/dist/utils/_uuid.js"() {
    init_esm_browser2();
  }
});

// node_modules/langsmith/dist/utils/warn.js
function warnOnce(message) {
  if (!warnedMessages[message]) {
    console.warn(message);
    warnedMessages[message] = true;
  }
}
var warnedMessages;
var init_warn = __esm({
  "node_modules/langsmith/dist/utils/warn.js"() {
    warnedMessages = {};
  }
});

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

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

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

// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "node_modules/semver/internal/parse-options.js"(exports, module2) {
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module2.exports = parseOptions;
  }
});

// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "node_modules/semver/internal/identifiers.js"(exports, module2) {
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = (a3, b3) => {
      const anum = numeric.test(a3);
      const bnum = numeric.test(b3);
      if (anum && bnum) {
        a3 = +a3;
        b3 = +b3;
      }
      return a3 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a3 < b3 ? -1 : 1;
    };
    var rcompareIdentifiers = (a3, b3) => compareIdentifiers(b3, a3);
    module2.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "node_modules/semver/classes/semver.js"(exports, module2) {
    var debug4 = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
    var { safeRe: re, t: t3 } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class {
      constructor(version2, options) {
        options = parseOptions(options);
        if (version2 instanceof SemVer) {
          if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) {
            return version2;
          } else {
            version2 = version2.version;
          }
        } else if (typeof version2 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);
        }
        if (version2.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug4("SemVer", version2, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m3 = version2.trim().match(options.loose ? re[t3.LOOSE] : re[t3.FULL]);
        if (!m3) {
          throw new TypeError(`Invalid Version: ${version2}`);
        }
        this.raw = version2;
        this.major = +m3[1];
        this.minor = +m3[2];
        this.patch = +m3[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m3[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m3[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m3[5] ? m3[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug4("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
      }
      comparePre(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i3 = 0;
        do {
          const a3 = this.prerelease[i3];
          const b3 = other.prerelease[i3];
          debug4("prerelease compare", i3, a3, b3);
          if (a3 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a3 === void 0) {
            return -1;
          } else if (a3 === b3) {
            continue;
          } else {
            return compareIdentifiers(a3, b3);
          }
        } while (++i3);
      }
      compareBuild(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        let i3 = 0;
        do {
          const a3 = this.build[i3];
          const b3 = other.build[i3];
          debug4("build compare", i3, a3, b3);
          if (a3 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a3 === void 0) {
            return -1;
          } else if (a3 === b3) {
            continue;
          } else {
            return compareIdentifiers(a3, b3);
          }
        } while (++i3);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (!identifier && identifierBase === false) {
              throw new Error("invalid increment argument: identifier is empty");
            }
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i3 = this.prerelease.length;
              while (--i3 >= 0) {
                if (typeof this.prerelease[i3] === "number") {
                  this.prerelease[i3]++;
                  i3 = -2;
                }
              }
              if (i3 === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

// node_modules/semver/functions/parse.js
var require_parse = __commonJS({
  "node_modules/semver/functions/parse.js"(exports, module2) {
    var SemVer = require_semver();
    var parse6 = (version2, options, throwErrors = false) => {
      if (version2 instanceof SemVer) {
        return version2;
      }
      try {
        return new SemVer(version2, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module2.exports = parse6;
  }
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "node_modules/semver/functions/valid.js"(exports, module2) {
    var parse6 = require_parse();
    var valid = (version2, options) => {
      const v5 = parse6(version2, options);
      return v5 ? v5.version : null;
    };
    module2.exports = valid;
  }
});

// node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "node_modules/semver/functions/clean.js"(exports, module2) {
    var parse6 = require_parse();
    var clean = (version2, options) => {
      const s4 = parse6(version2.trim().replace(/^[=v]+/, ""), options);
      return s4 ? s4.version : null;
    };
    module2.exports = clean;
  }
});

// node_modules/semver/functions/inc.js
var require_inc = __commonJS({
  "node_modules/semver/functions/inc.js"(exports, module2) {
    var SemVer = require_semver();
    var inc = (version2, release, options, identifier, identifierBase) => {
      if (typeof options === "string") {
        identifierBase = identifier;
        identifier = options;
        options = void 0;
      }
      try {
        return new SemVer(
          version2 instanceof SemVer ? version2.version : version2,
          options
        ).inc(release, identifier, identifierBase).version;
      } catch (er) {
        return null;
      }
    };
    module2.exports = inc;
  }
});

// node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "node_modules/semver/functions/diff.js"(exports, module2) {
    var parse6 = require_parse();
    var diff = (version1, version2) => {
      const v1 = parse6(version1, null, true);
      const v22 = parse6(version2, null, true);
      const comparison = v1.compare(v22);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v1 : v22;
      const lowVersion = v1Higher ? v22 : v1;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (highVersion.patch) {
          return "patch";
        }
        if (highVersion.minor) {
          return "minor";
        }
        return "major";
      }
      const prefix = highHasPre ? "pre" : "";
      if (v1.major !== v22.major) {
        return prefix + "major";
      }
      if (v1.minor !== v22.minor) {
        return prefix + "minor";
      }
      if (v1.patch !== v22.patch) {
        return prefix + "patch";
      }
      return "prerelease";
    };
    module2.exports = diff;
  }
});

// node_modules/semver/functions/major.js
var require_major = __commonJS({
  "node_modules/semver/functions/major.js"(exports, module2) {
    var SemVer = require_semver();
    var major = (a3, loose) => new SemVer(a3, loose).major;
    module2.exports = major;
  }
});

// node_modules/semver/functions/minor.js
var require_minor = __commonJS({
  "node_modules/semver/functions/minor.js"(exports, module2) {
    var SemVer = require_semver();
    var minor = (a3, loose) => new SemVer(a3, loose).minor;
    module2.exports = minor;
  }
});

// node_modules/semver/functions/patch.js
var require_patch = __commonJS({
  "node_modules/semver/functions/patch.js"(exports, module2) {
    var SemVer = require_semver();
    var patch = (a3, loose) => new SemVer(a3, loose).patch;
    module2.exports = patch;
  }
});

// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "node_modules/semver/functions/prerelease.js"(exports, module2) {
    var parse6 = require_parse();
    var prerelease = (version2, options) => {
      const parsed = parse6(version2, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    };
    module2.exports = prerelease;
  }
});

// node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "node_modules/semver/functions/compare.js"(exports, module2) {
    var SemVer = require_semver();
    var compare2 = (a3, b3, loose) => new SemVer(a3, loose).compare(new SemVer(b3, loose));
    module2.exports = compare2;
  }
});

// node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "node_modules/semver/functions/rcompare.js"(exports, module2) {
    var compare2 = require_compare();
    var rcompare = (a3, b3, loose) => compare2(b3, a3, loose);
    module2.exports = rcompare;
  }
});

// node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "node_modules/semver/functions/compare-loose.js"(exports, module2) {
    var compare2 = require_compare();
    var compareLoose = (a3, b3) => compare2(a3, b3, true);
    module2.exports = compareLoose;
  }
});

// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "node_modules/semver/functions/compare-build.js"(exports, module2) {
    var SemVer = require_semver();
    var compareBuild = (a3, b3, loose) => {
      const versionA = new SemVer(a3, loose);
      const versionB = new SemVer(b3, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    };
    module2.exports = compareBuild;
  }
});

// node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "node_modules/semver/functions/sort.js"(exports, module2) {
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a3, b3) => compareBuild(a3, b3, loose));
    module2.exports = sort;
  }
});

// node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "node_modules/semver/functions/rsort.js"(exports, module2) {
    var compareBuild = require_compare_build();
    var rsort = (list, loose) => list.sort((a3, b3) => compareBuild(b3, a3, loose));
    module2.exports = rsort;
  }
});

// node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "node_modules/semver/functions/gt.js"(exports, module2) {
    var compare2 = require_compare();
    var gt = (a3, b3, loose) => compare2(a3, b3, loose) > 0;
    module2.exports = gt;
  }
});

// node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "node_modules/semver/functions/lt.js"(exports, module2) {
    var compare2 = require_compare();
    var lt = (a3, b3, loose) => compare2(a3, b3, loose) < 0;
    module2.exports = lt;
  }
});

// node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "node_modules/semver/functions/eq.js"(exports, module2) {
    var compare2 = require_compare();
    var eq = (a3, b3, loose) => compare2(a3, b3, loose) === 0;
    module2.exports = eq;
  }
});

// node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "node_modules/semver/functions/neq.js"(exports, module2) {
    var compare2 = require_compare();
    var neq = (a3, b3, loose) => compare2(a3, b3, loose) !== 0;
    module2.exports = neq;
  }
});

// node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "node_modules/semver/functions/gte.js"(exports, module2) {
    var compare2 = require_compare();
    var gte = (a3, b3, loose) => compare2(a3, b3, loose) >= 0;
    module2.exports = gte;
  }
});

// node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "node_modules/semver/functions/lte.js"(exports, module2) {
    var compare2 = require_compare();
    var lte = (a3, b3, loose) => compare2(a3, b3, loose) <= 0;
    module2.exports = lte;
  }
});

// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "node_modules/semver/functions/cmp.js"(exports, module2) {
    var eq = require_eq();
    var neq = require_neq();
    var gt = require_gt();
    var gte = require_gte();
    var lt = require_lt();
    var lte = require_lte();
    var cmp = (a3, op, b3, loose) => {
      switch (op) {
        case "===":
          if (typeof a3 === "object") {
            a3 = a3.version;
          }
          if (typeof b3 === "object") {
            b3 = b3.version;
          }
          return a3 === b3;
        case "!==":
          if (typeof a3 === "object") {
            a3 = a3.version;
          }
          if (typeof b3 === "object") {
            b3 = b3.version;
          }
          return a3 !== b3;
        case "":
        case "=":
        case "==":
          return eq(a3, b3, loose);
        case "!=":
          return neq(a3, b3, loose);
        case ">":
          return gt(a3, b3, loose);
        case ">=":
          return gte(a3, b3, loose);
        case "<":
          return lt(a3, b3, loose);
        case "<=":
          return lte(a3, b3, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    module2.exports = cmp;
  }
});

// node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "node_modules/semver/functions/coerce.js"(exports, module2) {
    var SemVer = require_semver();
    var parse6 = require_parse();
    var { safeRe: re, t: t3 } = require_re();
    var coerce2 = (version2, options) => {
      if (version2 instanceof SemVer) {
        return version2;
      }
      if (typeof version2 === "number") {
        version2 = String(version2);
      }
      if (typeof version2 !== "string") {
        return null;
      }
      options = options || {};
      let match2 = null;
      if (!options.rtl) {
        match2 = version2.match(options.includePrerelease ? re[t3.COERCEFULL] : re[t3.COERCE]);
      } else {
        const coerceRtlRegex = options.includePrerelease ? re[t3.COERCERTLFULL] : re[t3.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version2)) && (!match2 || match2.index + match2[0].length !== version2.length)) {
          if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
            match2 = next;
          }
          coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
        }
        coerceRtlRegex.lastIndex = -1;
      }
      if (match2 === null) {
        return null;
      }
      const major = match2[2];
      const minor = match2[3] || "0";
      const patch = match2[4] || "0";
      const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
      const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
      return parse6(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce2;
  }
});

// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "node_modules/semver/internal/lrucache.js"(exports, module2) {
    var LRUCache = class {
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key) {
        const value = this.map.get(key);
        if (value === void 0) {
          return void 0;
        } else {
          this.map.delete(key);
          this.map.set(key, value);
          return value;
        }
      }
      delete(key) {
        return this.map.delete(key);
      }
      set(key, value) {
        const deleted = this.delete(key);
        if (!deleted && value !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key, value);
        }
        return this;
      }
    };
    module2.exports = LRUCache;
  }
});

// node_modules/semver/classes/range.js
var require_range = __commonJS({
  "node_modules/semver/classes/range.js"(exports, module2) {
    var SPACE_CHARACTERS = /\s+/g;
    var Range2 = class {
      constructor(range, options) {
        options = parseOptions(options);
        if (range instanceof Range2) {
          if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
            return range;
          } else {
            return new Range2(range.raw, options);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r4) => this.parseRange(r4.trim())).filter((c4) => c4.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first = this.set[0];
          this.set = this.set.filter((c4) => !isNullSet(c4[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c4 of this.set) {
              if (c4.length === 1 && isAny2(c4[0])) {
                this.set = [c4];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i3 = 0; i3 < this.set.length; i3++) {
            if (i3 > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i3];
            for (let k3 = 0; k3 < comps.length; k3++) {
              if (k3 > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k3].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range) {
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range;
        const cached = cache2.get(memoKey);
        if (cached) {
          return cached;
        }
        const loose = this.options.loose;
        const hr = loose ? re[t3.HYPHENRANGELOOSE] : re[t3.HYPHENRANGE];
        range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug4("hyphen replace", range);
        range = range.replace(re[t3.COMPARATORTRIM], comparatorTrimReplace);
        debug4("comparator trim", range);
        range = range.replace(re[t3.TILDETRIM], tildeTrimReplace);
        debug4("tilde trim", range);
        range = range.replace(re[t3.CARETTRIM], caretTrimReplace);
        debug4("caret trim", range);
        let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug4("loose invalid filter", comp, this.options);
            return !!comp.match(re[t3.COMPARATORLOOSE]);
          });
        }
        debug4("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache2.set(memoKey, result);
        return result;
      }
      intersects(range, options) {
        if (!(range instanceof Range2)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version2) {
        if (!version2) {
          return false;
        }
        if (typeof version2 === "string") {
          try {
            version2 = new SemVer(version2, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i3 = 0; i3 < this.set.length; i3++) {
          if (testSet(this.set[i3], version2, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module2.exports = Range2;
    var LRU = require_lrucache();
    var cache2 = new LRU();
    var parseOptions = require_parse_options();
    var Comparator = require_comparator();
    var debug4 = require_debug();
    var SemVer = require_semver();
    var {
      safeRe: re,
      t: t3,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
    var isNullSet = (c4) => c4.value === "<0.0.0-0";
    var isAny2 = (c4) => c4.value === "";
    var isSatisfiable = (comparators, options) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    };
    var parseComparator = (comp, options) => {
      debug4("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug4("caret", comp);
      comp = replaceTildes(comp, options);
      debug4("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug4("xrange", comp);
      comp = replaceStars(comp, options);
      debug4("stars", comp);
      return comp;
    };
    var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
    var replaceTildes = (comp, options) => {
      return comp.trim().split(/\s+/).map((c4) => replaceTilde(c4, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r4 = options.loose ? re[t3.TILDELOOSE] : re[t3.TILDE];
      return comp.replace(r4, (_2, M, m3, p3, pr) => {
        debug4("tilde", comp, _2, M, m3, p3, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
        } else if (isX(p3)) {
          ret = `>=${M}.${m3}.0 <${M}.${+m3 + 1}.0-0`;
        } else if (pr) {
          debug4("replaceTilde pr", pr);
          ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${+m3 + 1}.0-0`;
        } else {
          ret = `>=${M}.${m3}.${p3} <${M}.${+m3 + 1}.0-0`;
        }
        debug4("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c4) => replaceCaret(c4, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug4("caret", comp, options);
      const r4 = options.loose ? re[t3.CARETLOOSE] : re[t3.CARET];
      const z3 = options.includePrerelease ? "-0" : "";
      return comp.replace(r4, (_2, M, m3, p3, pr) => {
        debug4("caret", comp, _2, M, m3, p3, pr);
        let ret;
        if (isX(M)) {
          ret = "";
        } else if (isX(m3)) {
          ret = `>=${M}.0.0${z3} <${+M + 1}.0.0-0`;
        } else if (isX(p3)) {
          if (M === "0") {
            ret = `>=${M}.${m3}.0${z3} <${M}.${+m3 + 1}.0-0`;
          } else {
            ret = `>=${M}.${m3}.0${z3} <${+M + 1}.0.0-0`;
          }
        } else if (pr) {
          debug4("replaceCaret pr", pr);
          if (M === "0") {
            if (m3 === "0") {
              ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${m3}.${+p3 + 1}-0`;
            } else {
              ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m3}.${p3}-${pr} <${+M + 1}.0.0-0`;
          }
        } else {
          debug4("no pr");
          if (M === "0") {
            if (m3 === "0") {
              ret = `>=${M}.${m3}.${p3}${z3} <${M}.${m3}.${+p3 + 1}-0`;
            } else {
              ret = `>=${M}.${m3}.${p3}${z3} <${M}.${+m3 + 1}.0-0`;
            }
          } else {
            ret = `>=${M}.${m3}.${p3} <${+M + 1}.0.0-0`;
          }
        }
        debug4("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug4("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c4) => replaceXRange(c4, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r4 = options.loose ? re[t3.XRANGELOOSE] : re[t3.XRANGE];
      return comp.replace(r4, (ret, gtlt, M, m3, p3, pr) => {
        debug4("xRange", comp, ret, gtlt, M, m3, p3, pr);
        const xM = isX(M);
        const xm = xM || isX(m3);
        const xp = xm || isX(p3);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m3 = 0;
          }
          p3 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M = +M + 1;
              m3 = 0;
              p3 = 0;
            } else {
              m3 = +m3 + 1;
              p3 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M = +M + 1;
            } else {
              m3 = +m3 + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M}.${m3}.${p3}${pr}`;
        } else if (xm) {
          ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M}.${m3}.0${pr} <${M}.${+m3 + 1}.0-0`;
        }
        debug4("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug4("replaceStars", comp, options);
      return comp.trim().replace(re[t3.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug4("replaceGTE0", comp, options);
      return comp.trim().replace(re[options.includePrerelease ? t3.GTE0PRE : t3.GTE0], "");
    };
    var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    };
    var testSet = (set, version2, options) => {
      for (let i3 = 0; i3 < set.length; i3++) {
        if (!set[i3].test(version2)) {
          return false;
        }
      }
      if (version2.prerelease.length && !options.includePrerelease) {
        for (let i3 = 0; i3 < set.length; i3++) {
          debug4(set[i3].semver);
          if (set[i3].semver === Comparator.ANY) {
            continue;
          }
          if (set[i3].semver.prerelease.length > 0) {
            const allowed = set[i3].semver;
            if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "node_modules/semver/classes/comparator.js"(exports, module2) {
    var ANY = Symbol("SemVer ANY");
    var Comparator = class {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions(options);
        if (comp instanceof Comparator) {
          if (comp.loose === !!options.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug4("comparator", comp, options);
        this.options = options;
        this.loose = !!options.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug4("comp", this);
      }
      parse(comp) {
        const r4 = this.options.loose ? re[t3.COMPARATORLOOSE] : re[t3.COMPARATOR];
        const m3 = comp.match(r4);
        if (!m3) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m3[1] !== void 0 ? m3[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m3[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m3[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version2) {
        debug4("Comparator.test", version2, this.options.loose);
        if (this.semver === ANY || version2 === ANY) {
          return true;
        }
        if (typeof version2 === "string") {
          try {
            version2 = new SemVer(version2, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version2, this.operator, this.semver, this.options);
      }
      intersects(comp, options) {
        if (!(comp instanceof Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range2(comp.value, options).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range2(this.value, options).test(comp.semver);
        }
        options = parseOptions(options);
        if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    };
    module2.exports = Comparator;
    var parseOptions = require_parse_options();
    var { safeRe: re, t: t3 } = require_re();
    var cmp = require_cmp();
    var debug4 = require_debug();
    var SemVer = require_semver();
    var Range2 = require_range();
  }
});

// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
  "node_modules/semver/functions/satisfies.js"(exports, module2) {
    var Range2 = require_range();
    var satisfies = (version2, range, options) => {
      try {
        range = new Range2(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version2);
    };
    module2.exports = satisfies;
  }
});

// node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
  "node_modules/semver/ranges/to-comparators.js"(exports, module2) {
    var Range2 = require_range();
    var toComparators = (range, options) => new Range2(range, options).set.map((comp) => comp.map((c4) => c4.value).join(" ").trim().split(" "));
    module2.exports = toComparators;
  }
});

// node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
  "node_modules/semver/ranges/max-satisfying.js"(exports, module2) {
    var SemVer = require_semver();
    var Range2 = require_range();
    var maxSatisfying = (versions, range, options) => {
      let max2 = null;
      let maxSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range2(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v5) => {
        if (rangeObj.test(v5)) {
          if (!max2 || maxSV.compare(v5) === -1) {
            max2 = v5;
            maxSV = new SemVer(max2, options);
          }
        }
      });
      return max2;
    };
    module2.exports = maxSatisfying;
  }
});

// node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
  "node_modules/semver/ranges/min-satisfying.js"(exports, module2) {
    var SemVer = require_semver();
    var Range2 = require_range();
    var minSatisfying = (versions, range, options) => {
      let min2 = null;
      let minSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range2(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v5) => {
        if (rangeObj.test(v5)) {
          if (!min2 || minSV.compare(v5) === 1) {
            min2 = v5;
            minSV = new SemVer(min2, options);
          }
        }
      });
      return min2;
    };
    module2.exports = minSatisfying;
  }
});

// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "node_modules/semver/ranges/min-version.js"(exports, module2) {
    var SemVer = require_semver();
    var Range2 = require_range();
    var gt = require_gt();
    var minVersion = (range, loose) => {
      range = new Range2(range, loose);
      let minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (let i3 = 0; i3 < range.set.length; ++i3) {
        const comparators = range.set[i3];
        let setMin = null;
        comparators.forEach((comparator) => {
          const compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            case "":
            case ">=":
              if (!setMin || gt(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt(minver, setMin))) {
          minver = setMin;
        }
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    };
    module2.exports = minVersion;
  }
});

// node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "node_modules/semver/ranges/valid.js"(exports, module2) {
    var Range2 = require_range();
    var validRange = (range, options) => {
      try {
        return new Range2(range, options).range || "*";
      } catch (er) {
        return null;
      }
    };
    module2.exports = validRange;
  }
});

// node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "node_modules/semver/ranges/outside.js"(exports, module2) {
    var SemVer = require_semver();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var Range2 = require_range();
    var satisfies = require_satisfies();
    var gt = require_gt();
    var lt = require_lt();
    var lte = require_lte();
    var gte = require_gte();
    var outside = (version2, range, hilo, options) => {
      version2 = new SemVer(version2, options);
      range = new Range2(range, options);
      let gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt;
          ltefn = lte;
          ltfn = lt;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt;
          ltefn = gte;
          ltfn = gt;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version2, range, options)) {
        return false;
      }
      for (let i3 = 0; i3 < range.set.length; ++i3) {
        const comparators = range.set[i3];
        let high = null;
        let low = null;
        comparators.forEach((comparator) => {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version2, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module2.exports = outside;
  }
});

// node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
  "node_modules/semver/ranges/gtr.js"(exports, module2) {
    var outside = require_outside();
    var gtr = (version2, range, options) => outside(version2, range, ">", options);
    module2.exports = gtr;
  }
});

// node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
  "node_modules/semver/ranges/ltr.js"(exports, module2) {
    var outside = require_outside();
    var ltr = (version2, range, options) => outside(version2, range, "<", options);
    module2.exports = ltr;
  }
});

// node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
  "node_modules/semver/ranges/intersects.js"(exports, module2) {
    var Range2 = require_range();
    var intersects = (r1, r22, options) => {
      r1 = new Range2(r1, options);
      r22 = new Range2(r22, options);
      return r1.intersects(r22, options);
    };
    module2.exports = intersects;
  }
});

// node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "node_modules/semver/ranges/simplify.js"(exports, module2) {
    var satisfies = require_satisfies();
    var compare2 = require_compare();
    module2.exports = (versions, range, options) => {
      const set = [];
      let first = null;
      let prev = null;
      const v5 = versions.sort((a3, b3) => compare2(a3, b3, options));
      for (const version2 of v5) {
        const included = satisfies(version2, range, options);
        if (included) {
          prev = version2;
          if (!first) {
            first = version2;
          }
        } else {
          if (prev) {
            set.push([first, prev]);
          }
          prev = null;
          first = null;
        }
      }
      if (first) {
        set.push([first, null]);
      }
      const ranges = [];
      for (const [min2, max2] of set) {
        if (min2 === max2) {
          ranges.push(min2);
        } else if (!max2 && min2 === v5[0]) {
          ranges.push("*");
        } else if (!max2) {
          ranges.push(`>=${min2}`);
        } else if (min2 === v5[0]) {
          ranges.push(`<=${max2}`);
        } else {
          ranges.push(`${min2} - ${max2}`);
        }
      }
      const simplified = ranges.join(" || ");
      const original = typeof range.raw === "string" ? range.raw : String(range);
      return simplified.length < original.length ? simplified : range;
    };
  }
});

// node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "node_modules/semver/ranges/subset.js"(exports, module2) {
    var Range2 = require_range();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var satisfies = require_satisfies();
    var compare2 = require_compare();
    var subset = (sub, dom, options = {}) => {
      if (sub === dom) {
        return true;
      }
      sub = new Range2(sub, options);
      dom = new Range2(dom, options);
      let sawNonNull = false;
      OUTER:
        for (const simpleSub of sub.set) {
          for (const simpleDom of dom.set) {
            const isSub = simpleSubset(simpleSub, simpleDom, options);
            sawNonNull = sawNonNull || isSub !== null;
            if (isSub) {
              continue OUTER;
            }
          }
          if (sawNonNull) {
            return false;
          }
        }
      return true;
    };
    var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
    var minimumVersion = [new Comparator(">=0.0.0")];
    var simpleSubset = (sub, dom, options) => {
      if (sub === dom) {
        return true;
      }
      if (sub.length === 1 && sub[0].semver === ANY) {
        if (dom.length === 1 && dom[0].semver === ANY) {
          return true;
        } else if (options.includePrerelease) {
          sub = minimumVersionWithPreRelease;
        } else {
          sub = minimumVersion;
        }
      }
      if (dom.length === 1 && dom[0].semver === ANY) {
        if (options.includePrerelease) {
          return true;
        } else {
          dom = minimumVersion;
        }
      }
      const eqSet = /* @__PURE__ */ new Set();
      let gt, lt;
      for (const c4 of sub) {
        if (c4.operator === ">" || c4.operator === ">=") {
          gt = higherGT(gt, c4, options);
        } else if (c4.operator === "<" || c4.operator === "<=") {
          lt = lowerLT(lt, c4, options);
        } else {
          eqSet.add(c4.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt && lt) {
        gtltComp = compare2(gt.semver, lt.semver, options);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
          return null;
        }
      }
      for (const eq of eqSet) {
        if (gt && !satisfies(eq, String(gt), options)) {
          return null;
        }
        if (lt && !satisfies(eq, String(lt), options)) {
          return null;
        }
        for (const c4 of dom) {
          if (!satisfies(eq, String(c4), options)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
      let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c4 of dom) {
        hasDomGT = hasDomGT || c4.operator === ">" || c4.operator === ">=";
        hasDomLT = hasDomLT || c4.operator === "<" || c4.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomGTPre.major && c4.semver.minor === needDomGTPre.minor && c4.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c4.operator === ">" || c4.operator === ">=") {
            higher = higherGT(gt, c4, options);
            if (higher === c4 && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c4), options)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomLTPre.major && c4.semver.minor === needDomLTPre.minor && c4.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c4.operator === "<" || c4.operator === "<=") {
            lower = lowerLT(lt, c4, options);
            if (lower === c4 && lower !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c4), options)) {
            return false;
          }
        }
        if (!c4.operator && (lt || gt) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt && hasDomLT && !lt && gtltComp !== 0) {
        return false;
      }
      if (lt && hasDomGT && !gt && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    };
    var higherGT = (a3, b3, options) => {
      if (!a3) {
        return b3;
      }
      const comp = compare2(a3.semver, b3.semver, options);
      return comp > 0 ? a3 : comp < 0 ? b3 : b3.operator === ">" && a3.operator === ">=" ? b3 : a3;
    };
    var lowerLT = (a3, b3, options) => {
      if (!a3) {
        return b3;
      }
      const comp = compare2(a3.semver, b3.semver, options);
      return comp < 0 ? a3 : comp > 0 ? b3 : b3.operator === "<" && a3.operator === "<=" ? b3 : a3;
    };
    module2.exports = subset;
  }
});

// node_modules/semver/index.js
var require_semver2 = __commonJS({
  "node_modules/semver/index.js"(exports, module2) {
    var internalRe = require_re();
    var constants = require_constants();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse6 = require_parse();
    var valid = require_valid();
    var clean = require_clean();
    var inc = require_inc();
    var diff = require_diff();
    var major = require_major();
    var minor = require_minor();
    var patch = require_patch();
    var prerelease = require_prerelease();
    var compare2 = require_compare();
    var rcompare = require_rcompare();
    var compareLoose = require_compare_loose();
    var compareBuild = require_compare_build();
    var sort = require_sort();
    var rsort = require_rsort();
    var gt = require_gt();
    var lt = require_lt();
    var eq = require_eq();
    var neq = require_neq();
    var gte = require_gte();
    var lte = require_lte();
    var cmp = require_cmp();
    var coerce2 = require_coerce();
    var Comparator = require_comparator();
    var Range2 = require_range();
    var satisfies = require_satisfies();
    var toComparators = require_to_comparators();
    var maxSatisfying = require_max_satisfying();
    var minSatisfying = require_min_satisfying();
    var minVersion = require_min_version();
    var validRange = require_valid2();
    var outside = require_outside();
    var gtr = require_gtr();
    var ltr = require_ltr();
    var intersects = require_intersects();
    var simplifyRange = require_simplify();
    var subset = require_subset();
    module2.exports = {
      parse: parse6,
      valid,
      clean,
      inc,
      diff,
      major,
      minor,
      patch,
      prerelease,
      compare: compare2,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt,
      lt,
      eq,
      neq,
      gte,
      lte,
      cmp,
      coerce: coerce2,
      Comparator,
      Range: Range2,
      satisfies,
      toComparators,
      maxSatisfying,
      minSatisfying,
      minVersion,
      validRange,
      outside,
      gtr,
      ltr,
      intersects,
      simplifyRange,
      subset,
      SemVer,
      re: internalRe.re,
      src: internalRe.src,
      tokens: internalRe.t,
      SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants.RELEASE_TYPES,
      compareIdentifiers: identifiers.compareIdentifiers,
      rcompareIdentifiers: identifiers.rcompareIdentifiers
    };
  }
});

// node_modules/langsmith/dist/utils/prompts.js
function parsePromptIdentifier(identifier) {
  if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) {
    throw new Error(`Invalid identifier format: ${identifier}`);
  }
  const [ownerNamePart, commitPart] = identifier.split(":");
  const commit = commitPart || "latest";
  if (ownerNamePart.includes("/")) {
    const [owner, name] = ownerNamePart.split("/", 2);
    if (!owner || !name) {
      throw new Error(`Invalid identifier format: ${identifier}`);
    }
    return [owner, name, commit];
  } else {
    if (!ownerNamePart) {
      throw new Error(`Invalid identifier format: ${identifier}`);
    }
    return ["-", ownerNamePart, commit];
  }
}
var import_semver;
var init_prompts = __esm({
  "node_modules/langsmith/dist/utils/prompts.js"() {
    import_semver = __toESM(require_semver2(), 1);
  }
});

// node_modules/langsmith/dist/utils/error.js
async function raiseForStatus(response, context, consume) {
  let errorBody;
  if (response.ok) {
    if (consume) {
      errorBody = await response.text();
    }
    return;
  }
  errorBody = await response.text();
  const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`;
  if (response.status === 409) {
    throw new LangSmithConflictError(fullMessage);
  }
  throw new Error(fullMessage);
}
var LangSmithConflictError;
var init_error = __esm({
  "node_modules/langsmith/dist/utils/error.js"() {
    LangSmithConflictError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "LangSmithConflictError";
      }
    };
  }
});

// node_modules/langsmith/dist/utils/fast-safe-stringify/index.js
function defaultOptions() {
  return {
    depthLimit: Number.MAX_SAFE_INTEGER,
    edgesLimit: Number.MAX_SAFE_INTEGER
  };
}
function stringify(obj, replacer, spacer, options) {
  try {
    return JSON.stringify(obj, replacer, spacer);
  } catch (e3) {
    if (!e3.message?.includes("Converting circular structure to JSON")) {
      console.warn("[WARNING]: LangSmith received unserializable value.");
      return "[Unserializable]";
    }
    console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance.");
    if (typeof options === "undefined") {
      options = defaultOptions();
    }
    decirc(obj, "", 0, [], void 0, 0, options);
    var res;
    try {
      if (replacerStack.length === 0) {
        res = JSON.stringify(obj, replacer, spacer);
      } else {
        res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
      }
    } catch (_2) {
      return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]");
    } finally {
      while (arr.length !== 0) {
        var part = arr.pop();
        if (part.length === 4) {
          Object.defineProperty(part[0], part[1], part[3]);
        } else {
          part[0][part[1]] = part[2];
        }
      }
    }
    return res;
  }
}
function setReplace(replace, val2, k3, parent) {
  var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k3);
  if (propertyDescriptor.get !== void 0) {
    if (propertyDescriptor.configurable) {
      Object.defineProperty(parent, k3, { value: replace });
      arr.push([parent, k3, val2, propertyDescriptor]);
    } else {
      replacerStack.push([val2, k3, replace]);
    }
  } else {
    parent[k3] = replace;
    arr.push([parent, k3, val2]);
  }
}
function decirc(val2, k3, edgeIndex, stack, parent, depth, options) {
  depth += 1;
  var i3;
  if (typeof val2 === "object" && val2 !== null) {
    for (i3 = 0; i3 < stack.length; i3++) {
      if (stack[i3] === val2) {
        setReplace(CIRCULAR_REPLACE_NODE, val2, k3, parent);
        return;
      }
    }
    if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) {
      setReplace(LIMIT_REPLACE_NODE, val2, k3, parent);
      return;
    }
    if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) {
      setReplace(LIMIT_REPLACE_NODE, val2, k3, parent);
      return;
    }
    stack.push(val2);
    if (Array.isArray(val2)) {
      for (i3 = 0; i3 < val2.length; i3++) {
        decirc(val2[i3], i3, i3, stack, val2, depth, options);
      }
    } else {
      var keys = Object.keys(val2);
      for (i3 = 0; i3 < keys.length; i3++) {
        var key = keys[i3];
        decirc(val2[key], key, i3, stack, val2, depth, options);
      }
    }
    stack.pop();
  }
}
function replaceGetterValues(replacer) {
  replacer = typeof replacer !== "undefined" ? replacer : function(k3, v5) {
    return v5;
  };
  return function(key, val2) {
    if (replacerStack.length > 0) {
      for (var i3 = 0; i3 < replacerStack.length; i3++) {
        var part = replacerStack[i3];
        if (part[1] === key && part[0] === val2) {
          val2 = part[2];
          replacerStack.splice(i3, 1);
          break;
        }
      }
    }
    return replacer.call(this, key, val2);
  };
}
var LIMIT_REPLACE_NODE, CIRCULAR_REPLACE_NODE, arr, replacerStack;
var init_fast_safe_stringify = __esm({
  "node_modules/langsmith/dist/utils/fast-safe-stringify/index.js"() {
    LIMIT_REPLACE_NODE = "[...]";
    CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
    arr = [];
    replacerStack = [];
  }
});

// node_modules/langsmith/dist/client.js
function mergeRuntimeEnvIntoRunCreate(run) {
  const runtimeEnv = getRuntimeEnvironment();
  const envVars = getLangChainEnvVarsMetadata();
  const extra = run.extra ?? {};
  const metadata = extra.metadata;
  run.extra = {
    ...extra,
    runtime: {
      ...runtimeEnv,
      ...extra?.runtime
    },
    metadata: {
      ...envVars,
      ...envVars.revision_id || run.revision_id ? { revision_id: run.revision_id ?? envVars.revision_id } : {},
      ...metadata
    }
  };
  return run;
}
async function toArray(iterable) {
  const result = [];
  for await (const item of iterable) {
    result.push(item);
  }
  return result;
}
function trimQuotes(str2) {
  if (str2 === void 0) {
    return void 0;
  }
  return str2.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
}
var getTracingSamplingRate, isLocalhost, handle429, AutoBatchQueue, DEFAULT_BATCH_SIZE_LIMIT_BYTES, SERVER_INFO_REQUEST_TIMEOUT, Client;
var init_client = __esm({
  "node_modules/langsmith/dist/client.js"() {
    init_esm_browser2();
    init_async_caller();
    init_messages();
    init_env();
    init_dist();
    init_uuid();
    init_warn();
    init_prompts();
    init_error();
    init_fetch();
    init_fast_safe_stringify();
    getTracingSamplingRate = () => {
      const samplingRateStr = getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE");
      if (samplingRateStr === void 0) {
        return void 0;
      }
      const samplingRate = parseFloat(samplingRateStr);
      if (samplingRate < 0 || samplingRate > 1) {
        throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);
      }
      return samplingRate;
    };
    isLocalhost = (url) => {
      const strippedUrl = url.replace("http://", "").replace("https://", "");
      const hostname = strippedUrl.split("/")[0].split(":")[0];
      return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
    };
    handle429 = async (response) => {
      if (response?.status === 429) {
        const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1e3;
        if (retryAfter > 0) {
          await new Promise((resolve) => setTimeout(resolve, retryAfter));
          return true;
        }
      }
      return false;
    };
    AutoBatchQueue = class {
      constructor() {
        Object.defineProperty(this, "items", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "sizeBytes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: 0
        });
      }
      peek() {
        return this.items[0];
      }
      push(item) {
        let itemPromiseResolve;
        const itemPromise = new Promise((resolve) => {
          itemPromiseResolve = resolve;
        });
        const size4 = stringify(item.item).length;
        this.items.push({
          action: item.action,
          payload: item.item,
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          itemPromiseResolve,
          itemPromise,
          size: size4
        });
        this.sizeBytes += size4;
        return itemPromise;
      }
      pop(upToSizeBytes) {
        if (upToSizeBytes < 1) {
          throw new Error("Number of bytes to pop off may not be less than 1.");
        }
        const popped = [];
        let poppedSizeBytes = 0;
        while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0) {
          const item = this.items.shift();
          if (item) {
            popped.push(item);
            poppedSizeBytes += item.size;
            this.sizeBytes -= item.size;
          }
        }
        if (popped.length === 0 && this.items.length > 0) {
          const item = this.items.shift();
          popped.push(item);
          poppedSizeBytes += item.size;
          this.sizeBytes -= item.size;
        }
        return [
          popped.map((it) => ({ action: it.action, item: it.payload })),
          () => popped.forEach((it) => it.itemPromiseResolve())
        ];
      }
    };
    DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520;
    SERVER_INFO_REQUEST_TIMEOUT = 2500;
    Client = class {
      constructor(config = {}) {
        Object.defineProperty(this, "apiKey", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "apiUrl", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "webUrl", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "caller", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "batchIngestCaller", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "timeout_ms", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "_tenantId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: null
        });
        Object.defineProperty(this, "hideInputs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "hideOutputs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tracingSampleRate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "filteredPostUuids", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: /* @__PURE__ */ new Set()
        });
        Object.defineProperty(this, "autoBatchTracing", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "autoBatchQueue", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: new AutoBatchQueue()
        });
        Object.defineProperty(this, "autoBatchTimeout", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "autoBatchAggregationDelayMs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: 250
        });
        Object.defineProperty(this, "batchSizeBytesLimit", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "fetchOptions", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "settings", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "blockOnRootRunFinalization", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false"
        });
        Object.defineProperty(this, "traceBatchConcurrency", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: 5
        });
        Object.defineProperty(this, "_serverInfo", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "_getServerInfoPromise", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "manualFlushMode", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        const defaultConfig = Client.getDefaultClientConfig();
        this.tracingSampleRate = getTracingSamplingRate();
        this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? "";
        if (this.apiUrl.endsWith("/")) {
          this.apiUrl = this.apiUrl.slice(0, -1);
        }
        this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey);
        this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl);
        if (this.webUrl?.endsWith("/")) {
          this.webUrl = this.webUrl.slice(0, -1);
        }
        this.timeout_ms = config.timeout_ms ?? 9e4;
        this.caller = new AsyncCaller(config.callerOptions ?? {});
        this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency;
        if (this.traceBatchConcurrency < 1) {
          throw new Error("Trace batch concurrency must be positive.");
        }
        this.batchIngestCaller = new AsyncCaller({
          maxRetries: 2,
          maxConcurrency: this.traceBatchConcurrency,
          ...config.callerOptions ?? {},
          onFailedResponseHook: handle429
        });
        this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;
        this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;
        this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;
        this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
        this.batchSizeBytesLimit = config.batchSizeBytesLimit;
        this.fetchOptions = config.fetchOptions || {};
        this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode;
      }
      static getDefaultClientConfig() {
        const apiKey = getLangSmithEnvironmentVariable("API_KEY");
        const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? "https://api.smith.langchain.com";
        const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true";
        const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true";
        return {
          apiUrl,
          apiKey,
          webUrl: void 0,
          hideInputs,
          hideOutputs
        };
      }
      getHostUrl() {
        if (this.webUrl) {
          return this.webUrl;
        } else if (isLocalhost(this.apiUrl)) {
          this.webUrl = "http://localhost:3000";
          return this.webUrl;
        } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) {
          this.webUrl = this.apiUrl.replace("/api", "");
          return this.webUrl;
        } else if (this.apiUrl.split(".", 1)[0].includes("dev")) {
          this.webUrl = "https://dev.smith.langchain.com";
          return this.webUrl;
        } else if (this.apiUrl.split(".", 1)[0].includes("eu")) {
          this.webUrl = "https://eu.smith.langchain.com";
          return this.webUrl;
        } else {
          this.webUrl = "https://smith.langchain.com";
          return this.webUrl;
        }
      }
      get headers() {
        const headers = {
          "User-Agent": `langsmith-js/${__version__}`
        };
        if (this.apiKey) {
          headers["x-api-key"] = `${this.apiKey}`;
        }
        return headers;
      }
      processInputs(inputs) {
        if (this.hideInputs === false) {
          return inputs;
        }
        if (this.hideInputs === true) {
          return {};
        }
        if (typeof this.hideInputs === "function") {
          return this.hideInputs(inputs);
        }
        return inputs;
      }
      processOutputs(outputs) {
        if (this.hideOutputs === false) {
          return outputs;
        }
        if (this.hideOutputs === true) {
          return {};
        }
        if (typeof this.hideOutputs === "function") {
          return this.hideOutputs(outputs);
        }
        return outputs;
      }
      prepareRunCreateOrUpdateInputs(run) {
        const runParams = { ...run };
        if (runParams.inputs !== void 0) {
          runParams.inputs = this.processInputs(runParams.inputs);
        }
        if (runParams.outputs !== void 0) {
          runParams.outputs = this.processOutputs(runParams.outputs);
        }
        return runParams;
      }
      async _getResponse(path, queryParams) {
        const paramsString = queryParams?.toString() ?? "";
        const url = `${this.apiUrl}${path}?${paramsString}`;
        const response = await this.caller.call(_getFetchImplementation(), url, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `Failed to fetch ${path}`);
        return response;
      }
      async _get(path, queryParams) {
        const response = await this._getResponse(path, queryParams);
        return response.json();
      }
      async *_getPaginated(path, queryParams = new URLSearchParams(), transform) {
        let offset5 = Number(queryParams.get("offset")) || 0;
        const limit2 = Number(queryParams.get("limit")) || 100;
        while (true) {
          queryParams.set("offset", String(offset5));
          queryParams.set("limit", String(limit2));
          const url = `${this.apiUrl}${path}?${queryParams}`;
          const response = await this.caller.call(_getFetchImplementation(), url, {
            method: "GET",
            headers: this.headers,
            signal: AbortSignal.timeout(this.timeout_ms),
            ...this.fetchOptions
          });
          await raiseForStatus(response, `Failed to fetch ${path}`);
          const items = transform ? transform(await response.json()) : await response.json();
          if (items.length === 0) {
            break;
          }
          yield items;
          if (items.length < limit2) {
            break;
          }
          offset5 += items.length;
        }
      }
      async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") {
        const bodyParams = body ? { ...body } : {};
        while (true) {
          const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${path}`, {
            method: requestMethod,
            headers: { ...this.headers, "Content-Type": "application/json" },
            signal: AbortSignal.timeout(this.timeout_ms),
            ...this.fetchOptions,
            body: JSON.stringify(bodyParams)
          });
          const responseBody = await response.json();
          if (!responseBody) {
            break;
          }
          if (!responseBody[dataKey]) {
            break;
          }
          yield responseBody[dataKey];
          const cursors = responseBody.cursors;
          if (!cursors) {
            break;
          }
          if (!cursors.next) {
            break;
          }
          bodyParams.cursor = cursors.next;
        }
      }
      _filterForSampling(runs, patch = false) {
        if (this.tracingSampleRate === void 0) {
          return runs;
        }
        if (patch) {
          const sampled = [];
          for (const run of runs) {
            if (!this.filteredPostUuids.has(run.id)) {
              sampled.push(run);
            } else {
              this.filteredPostUuids.delete(run.id);
            }
          }
          return sampled;
        } else {
          const sampled = [];
          for (const run of runs) {
            if (run.id !== run.trace_id && !this.filteredPostUuids.has(run.trace_id) || Math.random() < this.tracingSampleRate) {
              sampled.push(run);
            } else {
              this.filteredPostUuids.add(run.id);
            }
          }
          return sampled;
        }
      }
      async _getBatchSizeLimitBytes() {
        const serverInfo = await this._ensureServerInfo();
        return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_BATCH_SIZE_LIMIT_BYTES;
      }
      async _getMultiPartSupport() {
        const serverInfo = await this._ensureServerInfo();
        return serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false;
      }
      drainAutoBatchQueue(batchSizeLimit) {
        const promises = [];
        while (this.autoBatchQueue.items.length > 0) {
          const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit);
          if (!batch.length) {
            done();
            break;
          }
          const batchPromise = this._processBatch(batch, done).catch(console.error);
          promises.push(batchPromise);
        }
        return Promise.all(promises);
      }
      async _processBatch(batch, done) {
        if (!batch.length) {
          done();
          return;
        }
        try {
          const ingestParams = {
            runCreates: batch.filter((item) => item.action === "create").map((item) => item.item),
            runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
          };
          const serverInfo = await this._ensureServerInfo();
          if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) {
            await this.multipartIngestRuns(ingestParams);
          } else {
            await this.batchIngestRuns(ingestParams);
          }
        } finally {
          done();
        }
      }
      async processRunOperation(item) {
        clearTimeout(this.autoBatchTimeout);
        this.autoBatchTimeout = void 0;
        if (item.action === "create") {
          item.item = mergeRuntimeEnvIntoRunCreate(item.item);
        }
        const itemPromise = this.autoBatchQueue.push(item);
        if (this.manualFlushMode) {
          return itemPromise;
        }
        const sizeLimitBytes = await this._getBatchSizeLimitBytes();
        if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) {
          void this.drainAutoBatchQueue(sizeLimitBytes);
        }
        if (this.autoBatchQueue.items.length > 0) {
          this.autoBatchTimeout = setTimeout(() => {
            this.autoBatchTimeout = void 0;
            void this.drainAutoBatchQueue(sizeLimitBytes);
          }, this.autoBatchAggregationDelayMs);
        }
        return itemPromise;
      }
      async _getServerInfo() {
        const response = await _getFetchImplementation()(`${this.apiUrl}/info`, {
          method: "GET",
          headers: { Accept: "application/json" },
          signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "get server info");
        return response.json();
      }
      async _ensureServerInfo() {
        if (this._getServerInfoPromise === void 0) {
          this._getServerInfoPromise = (async () => {
            if (this._serverInfo === void 0) {
              try {
                this._serverInfo = await this._getServerInfo();
              } catch (e3) {
                console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.`);
              }
            }
            return this._serverInfo ?? {};
          })();
        }
        return this._getServerInfoPromise.then((serverInfo) => {
          if (this._serverInfo === void 0) {
            this._getServerInfoPromise = void 0;
          }
          return serverInfo;
        });
      }
      async _getSettings() {
        if (!this.settings) {
          this.settings = this._get("/settings");
        }
        return await this.settings;
      }
      /**
       * Flushes current queued traces.
       */
      async flush() {
        const sizeLimitBytes = await this._getBatchSizeLimitBytes();
        await this.drainAutoBatchQueue(sizeLimitBytes);
      }
      async createRun(run) {
        if (!this._filterForSampling([run]).length) {
          return;
        }
        const headers = { ...this.headers, "Content-Type": "application/json" };
        const session_name = run.project_name;
        delete run.project_name;
        const runCreate = this.prepareRunCreateOrUpdateInputs({
          session_name,
          ...run,
          start_time: run.start_time ?? Date.now()
        });
        if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) {
          void this.processRunOperation({
            action: "create",
            item: runCreate
          }).catch(console.error);
          return;
        }
        const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs`, {
          method: "POST",
          headers,
          body: stringify(mergedRunCreateParam),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create run", true);
      }
      /**
       * Batch ingest/upsert multiple runs in the Langsmith system.
       * @param runs
       */
      async batchIngestRuns({ runCreates, runUpdates }) {
        if (runCreates === void 0 && runUpdates === void 0) {
          return;
        }
        let preparedCreateParams = runCreates?.map((create9) => this.prepareRunCreateOrUpdateInputs(create9)) ?? [];
        let preparedUpdateParams = runUpdates?.map((update2) => this.prepareRunCreateOrUpdateInputs(update2)) ?? [];
        if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
          const createById = preparedCreateParams.reduce((params, run) => {
            if (!run.id) {
              return params;
            }
            params[run.id] = run;
            return params;
          }, {});
          const standaloneUpdates = [];
          for (const updateParam of preparedUpdateParams) {
            if (updateParam.id !== void 0 && createById[updateParam.id]) {
              createById[updateParam.id] = {
                ...createById[updateParam.id],
                ...updateParam
              };
            } else {
              standaloneUpdates.push(updateParam);
            }
          }
          preparedCreateParams = Object.values(createById);
          preparedUpdateParams = standaloneUpdates;
        }
        const rawBatch = {
          post: this._filterForSampling(preparedCreateParams),
          patch: this._filterForSampling(preparedUpdateParams, true)
        };
        if (!rawBatch.post.length && !rawBatch.patch.length) {
          return;
        }
        const batchChunks = {
          post: [],
          patch: []
        };
        for (const k3 of ["post", "patch"]) {
          const key = k3;
          const batchItems = rawBatch[key].reverse();
          let batchItem = batchItems.pop();
          while (batchItem !== void 0) {
            batchChunks[key].push(batchItem);
            batchItem = batchItems.pop();
          }
        }
        if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {
          await this._postBatchIngestRuns(stringify(batchChunks));
        }
      }
      async _postBatchIngestRuns(body) {
        const headers = {
          ...this.headers,
          "Content-Type": "application/json",
          Accept: "application/json"
        };
        const response = await this.batchIngestCaller.call(_getFetchImplementation(), `${this.apiUrl}/runs/batch`, {
          method: "POST",
          headers,
          body,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "batch create run", true);
      }
      /**
       * Batch ingest/upsert multiple runs in the Langsmith system.
       * @param runs
       */
      async multipartIngestRuns({ runCreates, runUpdates }) {
        if (runCreates === void 0 && runUpdates === void 0) {
          return;
        }
        const allAttachments = {};
        let preparedCreateParams = [];
        for (const create9 of runCreates ?? []) {
          const preparedCreate = this.prepareRunCreateOrUpdateInputs(create9);
          if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) {
            allAttachments[preparedCreate.id] = preparedCreate.attachments;
          }
          delete preparedCreate.attachments;
          preparedCreateParams.push(preparedCreate);
        }
        let preparedUpdateParams = [];
        for (const update2 of runUpdates ?? []) {
          preparedUpdateParams.push(this.prepareRunCreateOrUpdateInputs(update2));
        }
        const invalidRunCreate = preparedCreateParams.find((runCreate) => {
          return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0;
        });
        if (invalidRunCreate !== void 0) {
          throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`);
        }
        const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => {
          return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0;
        });
        if (invalidRunUpdate !== void 0) {
          throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`);
        }
        if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
          const createById = preparedCreateParams.reduce((params, run) => {
            if (!run.id) {
              return params;
            }
            params[run.id] = run;
            return params;
          }, {});
          const standaloneUpdates = [];
          for (const updateParam of preparedUpdateParams) {
            if (updateParam.id !== void 0 && createById[updateParam.id]) {
              createById[updateParam.id] = {
                ...createById[updateParam.id],
                ...updateParam
              };
            } else {
              standaloneUpdates.push(updateParam);
            }
          }
          preparedCreateParams = Object.values(createById);
          preparedUpdateParams = standaloneUpdates;
        }
        if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) {
          return;
        }
        const accumulatedContext = [];
        const accumulatedParts = [];
        for (const [method, payloads] of [
          ["post", preparedCreateParams],
          ["patch", preparedUpdateParams]
        ]) {
          for (const originalPayload of payloads) {
            const { inputs, outputs, events, attachments, ...payload } = originalPayload;
            const fields = { inputs, outputs, events };
            const stringifiedPayload = stringify(payload);
            accumulatedParts.push({
              name: `${method}.${payload.id}`,
              payload: new Blob([stringifiedPayload], {
                type: `application/json; length=${stringifiedPayload.length}`
                // encoding=gzip
              })
            });
            for (const [key, value] of Object.entries(fields)) {
              if (value === void 0) {
                continue;
              }
              const stringifiedValue = stringify(value);
              accumulatedParts.push({
                name: `${method}.${payload.id}.${key}`,
                payload: new Blob([stringifiedValue], {
                  type: `application/json; length=${stringifiedValue.length}`
                })
              });
            }
            if (payload.id !== void 0) {
              const attachments2 = allAttachments[payload.id];
              if (attachments2) {
                delete allAttachments[payload.id];
                for (const [name, attachment] of Object.entries(attachments2)) {
                  let contentType;
                  let content;
                  if (Array.isArray(attachment)) {
                    [contentType, content] = attachment;
                  } else {
                    contentType = attachment.mimeType;
                    content = attachment.data;
                  }
                  if (name.includes(".")) {
                    console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);
                    continue;
                  }
                  accumulatedParts.push({
                    name: `attachment.${payload.id}.${name}`,
                    payload: new Blob([content], {
                      type: `${contentType}; length=${content.byteLength}`
                    })
                  });
                }
              }
            }
            accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`);
          }
        }
        await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "));
      }
      async _sendMultipartRequest(parts, context) {
        try {
          const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2);
          const chunks = [];
          for (const part of parts) {
            chunks.push(new Blob([`--${boundary}\r
`]));
            chunks.push(new Blob([
              `Content-Disposition: form-data; name="${part.name}"\r
`,
              `Content-Type: ${part.payload.type}\r
\r
`
            ]));
            chunks.push(part.payload);
            chunks.push(new Blob(["\r\n"]));
          }
          chunks.push(new Blob([`--${boundary}--\r
`]));
          const body = new Blob(chunks);
          const arrayBuffer = await body.arrayBuffer();
          const res = await this.batchIngestCaller.call(_getFetchImplementation(), `${this.apiUrl}/runs/multipart`, {
            method: "POST",
            headers: {
              ...this.headers,
              "Content-Type": `multipart/form-data; boundary=${boundary}`
            },
            body: arrayBuffer,
            signal: AbortSignal.timeout(this.timeout_ms),
            ...this.fetchOptions
          });
          await raiseForStatus(res, "ingest multipart runs", true);
        } catch (e3) {
          console.warn(`${e3.message.trim()}

Context: ${context}`);
        }
      }
      async updateRun(runId, run) {
        assertUuid(runId);
        if (run.inputs) {
          run.inputs = this.processInputs(run.inputs);
        }
        if (run.outputs) {
          run.outputs = this.processOutputs(run.outputs);
        }
        const data = { ...run, id: runId };
        if (!this._filterForSampling([data], true).length) {
          return;
        }
        if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) {
          if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) {
            await this.processRunOperation({ action: "update", item: data }).catch(console.error);
            return;
          } else {
            void this.processRunOperation({ action: "update", item: data }).catch(console.error);
          }
          return;
        }
        const headers = { ...this.headers, "Content-Type": "application/json" };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}`, {
          method: "PATCH",
          headers,
          body: stringify(run),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update run", true);
      }
      async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {
        assertUuid(runId);
        let run = await this._get(`/runs/${runId}`);
        if (loadChildRuns && run.child_run_ids) {
          run = await this._loadChildRuns(run);
        }
        return run;
      }
      async getRunUrl({ runId, run, projectOpts }) {
        if (run !== void 0) {
          let sessionId;
          if (run.session_id) {
            sessionId = run.session_id;
          } else if (projectOpts?.projectName) {
            sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id;
          } else if (projectOpts?.projectId) {
            sessionId = projectOpts?.projectId;
          } else {
            const project = await this.readProject({
              projectName: getLangSmithEnvironmentVariable("PROJECT") || "default"
            });
            sessionId = project.id;
          }
          const tenantId = await this._getTenantId();
          return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;
        } else if (runId !== void 0) {
          const run_ = await this.readRun(runId);
          if (!run_.app_path) {
            throw new Error(`Run ${runId} has no app_path`);
          }
          const baseUrl = this.getHostUrl();
          return `${baseUrl}${run_.app_path}`;
        } else {
          throw new Error("Must provide either runId or run");
        }
      }
      async _loadChildRuns(run) {
        const childRuns = await toArray(this.listRuns({ id: run.child_run_ids }));
        const treemap = {};
        const runs = {};
        childRuns.sort((a3, b3) => (a3?.dotted_order ?? "").localeCompare(b3?.dotted_order ?? ""));
        for (const childRun of childRuns) {
          if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) {
            throw new Error(`Child run ${childRun.id} has no parent`);
          }
          if (!(childRun.parent_run_id in treemap)) {
            treemap[childRun.parent_run_id] = [];
          }
          treemap[childRun.parent_run_id].push(childRun);
          runs[childRun.id] = childRun;
        }
        run.child_runs = treemap[run.id] || [];
        for (const runId in treemap) {
          if (runId !== run.id) {
            runs[runId].child_runs = treemap[runId];
          }
        }
        return run;
      }
      /**
       * List runs from the LangSmith server.
       * @param projectId - The ID of the project to filter by.
       * @param projectName - The name of the project to filter by.
       * @param parentRunId - The ID of the parent run to filter by.
       * @param traceId - The ID of the trace to filter by.
       * @param referenceExampleId - The ID of the reference example to filter by.
       * @param startTime - The start time to filter by.
       * @param isRoot - Indicates whether to only return root runs.
       * @param runType - The run type to filter by.
       * @param error - Indicates whether to filter by error runs.
       * @param id - The ID of the run to filter by.
       * @param query - The query string to filter by.
       * @param filter - The filter string to apply to the run spans.
       * @param traceFilter - The filter string to apply on the root run of the trace.
       * @param limit - The maximum number of runs to retrieve.
       * @returns {AsyncIterable<Run>} - The runs.
       *
       * @example
       * // List all runs in a project
       * const projectRuns = client.listRuns({ projectName: "<your_project>" });
       *
       * @example
       * // List LLM and Chat runs in the last 24 hours
       * const todaysLLMRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),
       *   run_type: "llm",
       * });
       *
       * @example
       * // List traces in a project
       * const rootRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   execution_order: 1,
       * });
       *
       * @example
       * // List runs without errors
       * const correctRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   error: false,
       * });
       *
       * @example
       * // List runs by run ID
       * const runIds = [
       *   "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
       *   "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
       * ];
       * const selectedRuns = client.listRuns({ run_ids: runIds });
       *
       * @example
       * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000
       * const chainRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
       * });
       *
       * @example
       * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
       * const goodExtractorRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   filter: 'eq(name, "extractor")',
       *   traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
       * });
       *
       * @example
       * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0
       * const complexRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
       * });
       *
       * @example
       * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
       * const taggedRuns = client.listRuns({
       *   projectName: "<your_project>",
       *   filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
       * });
       */
      async *listRuns(props) {
        const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter: filter2, traceFilter, treeFilter, limit: limit2, select } = props;
        let projectIds = [];
        if (projectId) {
          projectIds = Array.isArray(projectId) ? projectId : [projectId];
        }
        if (projectName) {
          const projectNames = Array.isArray(projectName) ? projectName : [projectName];
          const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));
          projectIds.push(...projectIds_);
        }
        const default_select = [
          "app_path",
          "child_run_ids",
          "completion_cost",
          "completion_tokens",
          "dotted_order",
          "end_time",
          "error",
          "events",
          "extra",
          "feedback_stats",
          "first_token_time",
          "id",
          "inputs",
          "name",
          "outputs",
          "parent_run_id",
          "parent_run_ids",
          "prompt_cost",
          "prompt_tokens",
          "reference_example_id",
          "run_type",
          "session_id",
          "start_time",
          "status",
          "tags",
          "total_cost",
          "total_tokens",
          "trace_id"
        ];
        const body = {
          session: projectIds.length ? projectIds : null,
          run_type: runType,
          reference_example: referenceExampleId,
          query,
          filter: filter2,
          trace_filter: traceFilter,
          tree_filter: treeFilter,
          execution_order: executionOrder,
          parent_run: parentRunId,
          start_time: startTime ? startTime.toISOString() : null,
          error,
          id,
          limit: limit2,
          trace: traceId,
          select: select ? select : default_select,
          is_root: isRoot
        };
        let runsYielded = 0;
        for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
          if (limit2) {
            if (runsYielded >= limit2) {
              break;
            }
            if (runs.length + runsYielded > limit2) {
              const newRuns = runs.slice(0, limit2 - runsYielded);
              yield* newRuns;
              break;
            }
            runsYielded += runs.length;
            yield* runs;
          } else {
            yield* runs;
          }
        }
      }
      async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter: filter2, traceFilter, treeFilter, isRoot, dataSourceType }) {
        let projectIds_ = projectIds || [];
        if (projectNames) {
          projectIds_ = [
            ...projectIds || [],
            ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))
          ];
        }
        const payload = {
          id,
          trace,
          parent_run: parentRun,
          run_type: runType,
          session: projectIds_,
          reference_example: referenceExampleIds,
          start_time: startTime,
          end_time: endTime,
          error,
          query,
          filter: filter2,
          trace_filter: traceFilter,
          tree_filter: treeFilter,
          is_root: isRoot,
          data_source_type: dataSourceType
        };
        const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_2, value]) => value !== void 0));
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/stats`, {
          method: "POST",
          headers: this.headers,
          body: JSON.stringify(filteredPayload),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const result = await response.json();
        return result;
      }
      async shareRun(runId, { shareId } = {}) {
        const data = {
          run_id: runId,
          share_token: shareId || v4_default2()
        };
        assertUuid(runId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, {
          method: "PUT",
          headers: this.headers,
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const result = await response.json();
        if (result === null || !("share_token" in result)) {
          throw new Error("Invalid response from server");
        }
        return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
      }
      async unshareRun(runId) {
        assertUuid(runId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "unshare run", true);
      }
      async readRunSharedLink(runId) {
        assertUuid(runId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const result = await response.json();
        if (result === null || !("share_token" in result)) {
          return void 0;
        }
        return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
      }
      async listSharedRuns(shareToken, { runIds } = {}) {
        const queryParams = new URLSearchParams({
          share_token: shareToken
        });
        if (runIds !== void 0) {
          for (const runId of runIds) {
            queryParams.append("id", runId);
          }
        }
        assertUuid(shareToken);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const runs = await response.json();
        return runs;
      }
      async readDatasetSharedSchema(datasetId, datasetName) {
        if (!datasetId && !datasetName) {
          throw new Error("Either datasetId or datasetName must be given");
        }
        if (!datasetId) {
          const dataset = await this.readDataset({ datasetName });
          datasetId = dataset.id;
        }
        assertUuid(datasetId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const shareSchema = await response.json();
        shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
        return shareSchema;
      }
      async shareDataset(datasetId, datasetName) {
        if (!datasetId && !datasetName) {
          throw new Error("Either datasetId or datasetName must be given");
        }
        if (!datasetId) {
          const dataset = await this.readDataset({ datasetName });
          datasetId = dataset.id;
        }
        const data = {
          dataset_id: datasetId
        };
        assertUuid(datasetId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, {
          method: "PUT",
          headers: this.headers,
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const shareSchema = await response.json();
        shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
        return shareSchema;
      }
      async unshareDataset(datasetId) {
        assertUuid(datasetId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "unshare dataset", true);
      }
      async readSharedDataset(shareToken) {
        assertUuid(shareToken);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/datasets`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const dataset = await response.json();
        return dataset;
      }
      /**
       * Get shared examples.
       *
       * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public.
       * @param {Object} [options] Additional options for listing the examples.
       * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by.
       * @returns {Promise<Example[]>} The shared examples.
       */
      async listSharedExamples(shareToken, options) {
        const params = {};
        if (options?.exampleIds) {
          params.id = options.exampleIds;
        }
        const urlParams = new URLSearchParams();
        Object.entries(params).forEach(([key, value]) => {
          if (Array.isArray(value)) {
            value.forEach((v5) => urlParams.append(key, v5));
          } else {
            urlParams.append(key, value);
          }
        });
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const result = await response.json();
        if (!response.ok) {
          if ("detail" in result) {
            throw new Error(`Failed to list shared examples.
Status: ${response.status}
Message: ${result.detail.join("\n")}`);
          }
          throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`);
        }
        return result.map((example) => ({
          ...example,
          _hostUrl: this.getHostUrl()
        }));
      }
      async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) {
        const upsert_ = upsert ? `?upsert=true` : "";
        const endpoint = `${this.apiUrl}/sessions${upsert_}`;
        const extra = projectExtra || {};
        if (metadata) {
          extra["metadata"] = metadata;
        }
        const body = {
          name: projectName,
          extra,
          description
        };
        if (referenceDatasetId !== null) {
          body["reference_dataset_id"] = referenceDatasetId;
        }
        const response = await this.caller.call(_getFetchImplementation(), endpoint, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create project");
        const result = await response.json();
        return result;
      }
      async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) {
        const endpoint = `${this.apiUrl}/sessions/${projectId}`;
        let extra = projectExtra;
        if (metadata) {
          extra = { ...extra || {}, metadata };
        }
        const body = {
          name,
          extra,
          description,
          end_time: endTime ? new Date(endTime).toISOString() : null
        };
        const response = await this.caller.call(_getFetchImplementation(), endpoint, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update project");
        const result = await response.json();
        return result;
      }
      async hasProject({ projectId, projectName }) {
        let path = "/sessions";
        const params = new URLSearchParams();
        if (projectId !== void 0 && projectName !== void 0) {
          throw new Error("Must provide either projectName or projectId, not both");
        } else if (projectId !== void 0) {
          assertUuid(projectId);
          path += `/${projectId}`;
        } else if (projectName !== void 0) {
          params.append("name", projectName);
        } else {
          throw new Error("Must provide projectName or projectId");
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${path}?${params}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        try {
          const result = await response.json();
          if (!response.ok) {
            return false;
          }
          if (Array.isArray(result)) {
            return result.length > 0;
          }
          return true;
        } catch (e3) {
          return false;
        }
      }
      async readProject({ projectId, projectName, includeStats }) {
        let path = "/sessions";
        const params = new URLSearchParams();
        if (projectId !== void 0 && projectName !== void 0) {
          throw new Error("Must provide either projectName or projectId, not both");
        } else if (projectId !== void 0) {
          assertUuid(projectId);
          path += `/${projectId}`;
        } else if (projectName !== void 0) {
          params.append("name", projectName);
        } else {
          throw new Error("Must provide projectName or projectId");
        }
        if (includeStats !== void 0) {
          params.append("include_stats", includeStats.toString());
        }
        const response = await this._get(path, params);
        let result;
        if (Array.isArray(response)) {
          if (response.length === 0) {
            throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);
          }
          result = response[0];
        } else {
          result = response;
        }
        return result;
      }
      async getProjectUrl({ projectId, projectName }) {
        if (projectId === void 0 && projectName === void 0) {
          throw new Error("Must provide either projectName or projectId");
        }
        const project = await this.readProject({ projectId, projectName });
        const tenantId = await this._getTenantId();
        return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;
      }
      async getDatasetUrl({ datasetId, datasetName }) {
        if (datasetId === void 0 && datasetName === void 0) {
          throw new Error("Must provide either datasetName or datasetId");
        }
        const dataset = await this.readDataset({ datasetId, datasetName });
        const tenantId = await this._getTenantId();
        return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;
      }
      async _getTenantId() {
        if (this._tenantId !== null) {
          return this._tenantId;
        }
        const queryParams = new URLSearchParams({ limit: "1" });
        for await (const projects of this._getPaginated("/sessions", queryParams)) {
          this._tenantId = projects[0].tenant_id;
          return projects[0].tenant_id;
        }
        throw new Error("No projects found to resolve tenant.");
      }
      async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata } = {}) {
        const params = new URLSearchParams();
        if (projectIds !== void 0) {
          for (const projectId of projectIds) {
            params.append("id", projectId);
          }
        }
        if (name !== void 0) {
          params.append("name", name);
        }
        if (nameContains !== void 0) {
          params.append("name_contains", nameContains);
        }
        if (referenceDatasetId !== void 0) {
          params.append("reference_dataset", referenceDatasetId);
        } else if (referenceDatasetName !== void 0) {
          const dataset = await this.readDataset({
            datasetName: referenceDatasetName
          });
          params.append("reference_dataset", dataset.id);
        }
        if (referenceFree !== void 0) {
          params.append("reference_free", referenceFree.toString());
        }
        if (metadata !== void 0) {
          params.append("metadata", JSON.stringify(metadata));
        }
        for await (const projects of this._getPaginated("/sessions", params)) {
          yield* projects;
        }
      }
      async deleteProject({ projectId, projectName }) {
        let projectId_;
        if (projectId === void 0 && projectName === void 0) {
          throw new Error("Must provide projectName or projectId");
        } else if (projectId !== void 0 && projectName !== void 0) {
          throw new Error("Must provide either projectName or projectId, not both");
        } else if (projectId === void 0) {
          projectId_ = (await this.readProject({ projectName })).id;
        } else {
          projectId_ = projectId;
        }
        assertUuid(projectId_);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/sessions/${projectId_}`, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true);
      }
      async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) {
        const url = `${this.apiUrl}/datasets/upload`;
        const formData = new FormData();
        formData.append("file", csvFile, fileName);
        inputKeys.forEach((key) => {
          formData.append("input_keys", key);
        });
        outputKeys.forEach((key) => {
          formData.append("output_keys", key);
        });
        if (description) {
          formData.append("description", description);
        }
        if (dataType) {
          formData.append("data_type", dataType);
        }
        if (name) {
          formData.append("name", name);
        }
        const response = await this.caller.call(_getFetchImplementation(), url, {
          method: "POST",
          headers: this.headers,
          body: formData,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "upload CSV");
        const result = await response.json();
        return result;
      }
      async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) {
        const body = {
          name,
          description,
          extra: metadata ? { metadata } : void 0
        };
        if (dataType) {
          body.data_type = dataType;
        }
        if (inputsSchema) {
          body.inputs_schema_definition = inputsSchema;
        }
        if (outputsSchema) {
          body.outputs_schema_definition = outputsSchema;
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create dataset");
        const result = await response.json();
        return result;
      }
      async readDataset({ datasetId, datasetName }) {
        let path = "/datasets";
        const params = new URLSearchParams({ limit: "1" });
        if (datasetId !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId !== void 0) {
          assertUuid(datasetId);
          path += `/${datasetId}`;
        } else if (datasetName !== void 0) {
          params.append("name", datasetName);
        } else {
          throw new Error("Must provide datasetName or datasetId");
        }
        const response = await this._get(path, params);
        let result;
        if (Array.isArray(response)) {
          if (response.length === 0) {
            throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);
          }
          result = response[0];
        } else {
          result = response;
        }
        return result;
      }
      async hasDataset({ datasetId, datasetName }) {
        try {
          await this.readDataset({ datasetId, datasetName });
          return true;
        } catch (e3) {
          if (
            // eslint-disable-next-line no-instanceof/no-instanceof
            e3 instanceof Error && e3.message.toLocaleLowerCase().includes("not found")
          ) {
            return false;
          }
          throw e3;
        }
      }
      async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) {
        let datasetId_ = datasetId;
        if (datasetId_ === void 0 && datasetName === void 0) {
          throw new Error("Must provide either datasetName or datasetId");
        } else if (datasetId_ !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId_ === void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        }
        const urlParams = new URLSearchParams({
          from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(),
          to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString()
        });
        const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);
        return response;
      }
      async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
        const path = "/datasets";
        if (datasetId !== void 0) {
        } else if (datasetName !== void 0) {
          datasetId = (await this.readDataset({ datasetName })).id;
        } else {
          throw new Error("Must provide datasetName or datasetId");
        }
        const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);
        const datasetText = await response.text();
        const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
        return dataset;
      }
      async *listDatasets({ limit: limit2 = 100, offset: offset5 = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) {
        const path = "/datasets";
        const params = new URLSearchParams({
          limit: limit2.toString(),
          offset: offset5.toString()
        });
        if (datasetIds !== void 0) {
          for (const id_ of datasetIds) {
            params.append("id", id_);
          }
        }
        if (datasetName !== void 0) {
          params.append("name", datasetName);
        }
        if (datasetNameContains !== void 0) {
          params.append("name_contains", datasetNameContains);
        }
        if (metadata !== void 0) {
          params.append("metadata", JSON.stringify(metadata));
        }
        for await (const datasets of this._getPaginated(path, params)) {
          yield* datasets;
        }
      }
      /**
       * Update a dataset
       * @param props The dataset details to update
       * @returns The updated dataset
       */
      async updateDataset(props) {
        const { datasetId, datasetName, ...update2 } = props;
        if (!datasetId && !datasetName) {
          throw new Error("Must provide either datasetName or datasetId");
        }
        const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;
        assertUuid(_datasetId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${_datasetId}`, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(update2),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update dataset");
        return await response.json();
      }
      async deleteDataset({ datasetId, datasetName }) {
        let path = "/datasets";
        let datasetId_ = datasetId;
        if (datasetId !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetName !== void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        }
        if (datasetId_ !== void 0) {
          assertUuid(datasetId_);
          path += `/${datasetId_}`;
        } else {
          throw new Error("Must provide datasetName or datasetId");
        }
        const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `delete ${path}`);
        await response.json();
      }
      async indexDataset({ datasetId, datasetName, tag }) {
        let datasetId_ = datasetId;
        if (!datasetId_ && !datasetName) {
          throw new Error("Must provide either datasetName or datasetId");
        } else if (datasetId_ && datasetName) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (!datasetId_) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        }
        assertUuid(datasetId_);
        const data = {
          tag
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId_}/index`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "index dataset");
        await response.json();
      }
      /**
       * Lets you run a similarity search query on a dataset.
       *
       * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing.
       *
       * @param inputs      The input on which to run the similarity search. Must have the
       *                    same schema as the dataset.
       *
       * @param datasetId   The dataset to search for similar examples.
       *
       * @param limit       The maximum number of examples to return. Will return the top `limit` most
       *                    similar examples in order of most similar to least similar. If no similar
       *                    examples are found, random examples will be returned.
       *
       * @param filter      A filter string to apply to the search. Only examples will be returned that
       *                    match the filter string. Some examples of filters
       *
       *                    - eq(metadata.mykey, "value")
       *                    - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value"))
       *                    - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue"))
       *
       * @returns           A list of similar examples.
       *
       *
       * @example
       * dataset_id = "123e4567-e89b-12d3-a456-426614174000"
       * inputs = {"text": "How many people live in Berlin?"}
       * limit = 5
       * examples = await client.similarExamples(inputs, dataset_id, limit)
       */
      async similarExamples(inputs, datasetId, limit2, { filter: filter2 } = {}) {
        const data = {
          limit: limit2,
          inputs
        };
        if (filter2 !== void 0) {
          data["filter"] = filter2;
        }
        assertUuid(datasetId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/search`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "fetch similar examples");
        const result = await response.json();
        return result["examples"];
      }
      async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, split, sourceRunId }) {
        let datasetId_ = datasetId;
        if (datasetId_ === void 0 && datasetName === void 0) {
          throw new Error("Must provide either datasetName or datasetId");
        } else if (datasetId_ !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId_ === void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        }
        const createdAt_ = createdAt || new Date();
        const data = {
          dataset_id: datasetId_,
          inputs,
          outputs,
          created_at: createdAt_?.toISOString(),
          id: exampleId,
          metadata,
          split,
          source_run_id: sourceRunId
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create example");
        const result = await response.json();
        return result;
      }
      async createExamples(props) {
        const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName } = props;
        let datasetId_ = datasetId;
        if (datasetId_ === void 0 && datasetName === void 0) {
          throw new Error("Must provide either datasetName or datasetId");
        } else if (datasetId_ !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId_ === void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        }
        const formattedExamples = inputs.map((input, idx) => {
          return {
            dataset_id: datasetId_,
            inputs: input,
            outputs: outputs ? outputs[idx] : void 0,
            metadata: metadata ? metadata[idx] : void 0,
            split: props.splits ? props.splits[idx] : void 0,
            id: exampleIds ? exampleIds[idx] : void 0,
            source_run_id: sourceRunIds ? sourceRunIds[idx] : void 0
          };
        });
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/bulk`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(formattedExamples),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create examples");
        const result = await response.json();
        return result;
      }
      async createLLMExample(input, generation, options) {
        return this.createExample({ input }, { output: generation }, options);
      }
      async createChatExample(input, generations, options) {
        const finalInput = input.map((message) => {
          if (isLangChainMessage(message)) {
            return convertLangChainMessageToExample(message);
          }
          return message;
        });
        const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations;
        return this.createExample({ input: finalInput }, { output: finalOutput }, options);
      }
      async readExample(exampleId) {
        assertUuid(exampleId);
        const path = `/examples/${exampleId}`;
        const rawExample = await this._get(path);
        const { attachment_urls, ...rest } = rawExample;
        const example = rest;
        if (attachment_urls) {
          example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {
            acc[key.slice("attachment.".length)] = {
              presigned_url: value.presigned_url
            };
            return acc;
          }, {});
        }
        return example;
      }
      async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit: limit2, offset: offset5, filter: filter2, includeAttachments } = {}) {
        let datasetId_;
        if (datasetId !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId !== void 0) {
          datasetId_ = datasetId;
        } else if (datasetName !== void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        } else {
          throw new Error("Must provide a datasetName or datasetId");
        }
        const params = new URLSearchParams({ dataset: datasetId_ });
        const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0;
        if (dataset_version) {
          params.append("as_of", dataset_version);
        }
        const inlineS3Urls_ = inlineS3Urls ?? true;
        params.append("inline_s3_urls", inlineS3Urls_.toString());
        if (exampleIds !== void 0) {
          for (const id_ of exampleIds) {
            params.append("id", id_);
          }
        }
        if (splits !== void 0) {
          for (const split of splits) {
            params.append("splits", split);
          }
        }
        if (metadata !== void 0) {
          const serializedMetadata = JSON.stringify(metadata);
          params.append("metadata", serializedMetadata);
        }
        if (limit2 !== void 0) {
          params.append("limit", limit2.toString());
        }
        if (offset5 !== void 0) {
          params.append("offset", offset5.toString());
        }
        if (filter2 !== void 0) {
          params.append("filter", filter2);
        }
        if (includeAttachments === true) {
          ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field));
        }
        let i3 = 0;
        for await (const rawExamples of this._getPaginated("/examples", params)) {
          for (const rawExample of rawExamples) {
            const { attachment_urls, ...rest } = rawExample;
            const example = rest;
            if (attachment_urls) {
              example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {
                acc[key.slice("attachment.".length)] = {
                  presigned_url: value.presigned_url
                };
                return acc;
              }, {});
            }
            yield example;
            i3++;
          }
          if (limit2 !== void 0 && i3 >= limit2) {
            break;
          }
        }
      }
      async deleteExample(exampleId) {
        assertUuid(exampleId);
        const path = `/examples/${exampleId}`;
        const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `delete ${path}`);
        await response.json();
      }
      async updateExample(exampleId, update2) {
        assertUuid(exampleId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/${exampleId}`, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(update2),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update example");
        const result = await response.json();
        return result;
      }
      async updateExamples(update2) {
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/bulk`, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(update2),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update examples");
        const result = await response.json();
        return result;
      }
      async listDatasetSplits({ datasetId, datasetName, asOf }) {
        let datasetId_;
        if (datasetId === void 0 && datasetName === void 0) {
          throw new Error("Must provide dataset name or ID");
        } else if (datasetId !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId === void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        } else {
          datasetId_ = datasetId;
        }
        assertUuid(datasetId_);
        const params = new URLSearchParams();
        const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0;
        if (dataset_version) {
          params.append("as_of", dataset_version);
        }
        const response = await this._get(`/datasets/${datasetId_}/splits`, params);
        return response;
      }
      async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove: remove6 = false }) {
        let datasetId_;
        if (datasetId === void 0 && datasetName === void 0) {
          throw new Error("Must provide dataset name or ID");
        } else if (datasetId !== void 0 && datasetName !== void 0) {
          throw new Error("Must provide either datasetName or datasetId, not both");
        } else if (datasetId === void 0) {
          const dataset = await this.readDataset({ datasetName });
          datasetId_ = dataset.id;
        } else {
          datasetId_ = datasetId;
        }
        assertUuid(datasetId_);
        const data = {
          split_name: splitName,
          examples: exampleIds.map((id) => {
            assertUuid(id);
            return id;
          }),
          remove: remove6
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId_}/splits`, {
          method: "PUT",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update dataset splits", true);
      }
      /**
       * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.
       */
      async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) {
        warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");
        let run_;
        if (typeof run === "string") {
          run_ = await this.readRun(run, { loadChildRuns });
        } else if (typeof run === "object" && "id" in run) {
          run_ = run;
        } else {
          throw new Error(`Invalid run type: ${typeof run}`);
        }
        if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) {
          referenceExample = await this.readExample(run_.reference_example_id);
        }
        const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);
        const [_2, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);
        return feedbacks[0];
      }
      async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
        if (!runId && !projectId) {
          throw new Error("One of runId or projectId must be provided");
        }
        if (runId && projectId) {
          throw new Error("Only one of runId or projectId can be provided");
        }
        const feedback_source = {
          type: feedbackSourceType ?? "api",
          metadata: sourceInfo ?? {}
        };
        if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) {
          feedback_source.metadata["__run"] = { run_id: sourceRunId };
        }
        if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) {
          assertUuid(feedback_source.metadata["__run"].run_id);
        }
        const feedback = {
          id: feedbackId ?? v4_default2(),
          run_id: runId,
          key,
          score,
          value,
          correction,
          comment,
          feedback_source,
          comparative_experiment_id: comparativeExperimentId,
          feedbackConfig,
          session_id: projectId
        };
        const url = `${this.apiUrl}/feedback`;
        const response = await this.caller.call(_getFetchImplementation(), url, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(feedback),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create feedback", true);
        return feedback;
      }
      async updateFeedback(feedbackId, { score, value, correction, comment }) {
        const feedbackUpdate = {};
        if (score !== void 0 && score !== null) {
          feedbackUpdate["score"] = score;
        }
        if (value !== void 0 && value !== null) {
          feedbackUpdate["value"] = value;
        }
        if (correction !== void 0 && correction !== null) {
          feedbackUpdate["correction"] = correction;
        }
        if (comment !== void 0 && comment !== null) {
          feedbackUpdate["comment"] = comment;
        }
        assertUuid(feedbackId);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/feedback/${feedbackId}`, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(feedbackUpdate),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update feedback", true);
      }
      async readFeedback(feedbackId) {
        assertUuid(feedbackId);
        const path = `/feedback/${feedbackId}`;
        const response = await this._get(path);
        return response;
      }
      async deleteFeedback(feedbackId) {
        assertUuid(feedbackId);
        const path = `/feedback/${feedbackId}`;
        const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `delete ${path}`);
        await response.json();
      }
      async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) {
        const queryParams = new URLSearchParams();
        if (runIds) {
          queryParams.append("run", runIds.join(","));
        }
        if (feedbackKeys) {
          for (const key of feedbackKeys) {
            queryParams.append("key", key);
          }
        }
        if (feedbackSourceTypes) {
          for (const type of feedbackSourceTypes) {
            queryParams.append("source", type);
          }
        }
        for await (const feedbacks of this._getPaginated("/feedback", queryParams)) {
          yield* feedbacks;
        }
      }
      /**
       * Creates a presigned feedback token and URL.
       *
       * The token can be used to authorize feedback metrics without
       * needing an API key. This is useful for giving browser-based
       * applications the ability to submit feedback without needing
       * to expose an API key.
       *
       * @param runId - The ID of the run.
       * @param feedbackKey - The feedback key.
       * @param options - Additional options for the token.
       * @param options.expiration - The expiration time for the token.
       *
       * @returns A promise that resolves to a FeedbackIngestToken.
       */
      async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) {
        const body = {
          run_id: runId,
          feedback_key: feedbackKey,
          feedback_config: feedbackConfig
        };
        if (expiration) {
          if (typeof expiration === "string") {
            body["expires_at"] = expiration;
          } else if (expiration?.hours || expiration?.minutes || expiration?.days) {
            body["expires_in"] = expiration;
          }
        } else {
          body["expires_in"] = {
            hours: 3
          };
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/feedback/tokens`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const result = await response.json();
        return result;
      }
      async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) {
        if (experimentIds.length === 0) {
          throw new Error("At least one experiment is required");
        }
        if (!referenceDatasetId) {
          referenceDatasetId = (await this.readProject({
            projectId: experimentIds[0]
          })).reference_dataset_id;
        }
        if (!referenceDatasetId == null) {
          throw new Error("A reference dataset is required");
        }
        const body = {
          id,
          name,
          experiment_ids: experimentIds,
          reference_dataset_id: referenceDatasetId,
          description,
          created_at: (createdAt ?? new Date())?.toISOString(),
          extra: {}
        };
        if (metadata)
          body.extra["metadata"] = metadata;
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/comparative`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        return await response.json();
      }
      /**
       * Retrieves a list of presigned feedback tokens for a given run ID.
       * @param runId The ID of the run.
       * @returns An async iterable of FeedbackIngestToken objects.
       */
      async *listPresignedFeedbackTokens(runId) {
        assertUuid(runId);
        const params = new URLSearchParams({ run_id: runId });
        for await (const tokens of this._getPaginated("/feedback/tokens", params)) {
          yield* tokens;
        }
      }
      _selectEvalResults(results) {
        let results_;
        if ("results" in results) {
          results_ = results.results;
        } else {
          results_ = [results];
        }
        return results_;
      }
      async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
        const evalResults = this._selectEvalResults(evaluatorResponse);
        const feedbacks = [];
        for (const res of evalResults) {
          let sourceInfo_ = sourceInfo || {};
          if (res.evaluatorInfo) {
            sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ };
          }
          let runId_ = null;
          if (res.targetRunId) {
            runId_ = res.targetRunId;
          } else if (run) {
            runId_ = run.id;
          }
          feedbacks.push(await this.createFeedback(runId_, res.key, {
            score: res.score,
            value: res.value,
            comment: res.comment,
            correction: res.correction,
            sourceInfo: sourceInfo_,
            sourceRunId: res.sourceRunId,
            feedbackConfig: res.feedbackConfig,
            feedbackSourceType: "model"
          }));
        }
        return [evalResults, feedbacks];
      }
      async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
        const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);
        return results;
      }
      /**
       * API for managing annotation queues
       */
      /**
       * List the annotation queues on the LangSmith API.
       * @param options - The options for listing annotation queues
       * @param options.queueIds - The IDs of the queues to filter by
       * @param options.name - The name of the queue to filter by
       * @param options.nameContains - The substring that the queue name should contain
       * @param options.limit - The maximum number of queues to return
       * @returns An iterator of AnnotationQueue objects
       */
      async *listAnnotationQueues(options = {}) {
        const { queueIds, name, nameContains, limit: limit2 } = options;
        const params = new URLSearchParams();
        if (queueIds) {
          queueIds.forEach((id, i3) => {
            assertUuid(id, `queueIds[${i3}]`);
            params.append("ids", id);
          });
        }
        if (name)
          params.append("name", name);
        if (nameContains)
          params.append("name_contains", nameContains);
        params.append("limit", (limit2 !== void 0 ? Math.min(limit2, 100) : 100).toString());
        let count5 = 0;
        for await (const queues of this._getPaginated("/annotation-queues", params)) {
          yield* queues;
          count5++;
          if (limit2 !== void 0 && count5 >= limit2)
            break;
        }
      }
      /**
       * Create an annotation queue on the LangSmith API.
       * @param options - The options for creating an annotation queue
       * @param options.name - The name of the annotation queue
       * @param options.description - The description of the annotation queue
       * @param options.queueId - The ID of the annotation queue
       * @returns The created AnnotationQueue object
       */
      async createAnnotationQueue(options) {
        const { name, description, queueId } = options;
        const body = {
          name,
          description,
          id: queueId || v4_default2()
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_2, v5]) => v5 !== void 0))),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create annotation queue");
        const data = await response.json();
        return data;
      }
      /**
       * Read an annotation queue with the specified queue ID.
       * @param queueId - The ID of the annotation queue to read
       * @returns The AnnotationQueue object
       */
      async readAnnotationQueue(queueId) {
        const queueIteratorResult = await this.listAnnotationQueues({
          queueIds: [queueId]
        }).next();
        if (queueIteratorResult.done) {
          throw new Error(`Annotation queue with ID ${queueId} not found`);
        }
        return queueIteratorResult.value;
      }
      /**
       * Update an annotation queue with the specified queue ID.
       * @param queueId - The ID of the annotation queue to update
       * @param options - The options for updating the annotation queue
       * @param options.name - The new name for the annotation queue
       * @param options.description - The new description for the annotation queue
       */
      async updateAnnotationQueue(queueId, options) {
        const { name, description } = options;
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, {
          method: "PATCH",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify({ name, description }),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update annotation queue");
      }
      /**
       * Delete an annotation queue with the specified queue ID.
       * @param queueId - The ID of the annotation queue to delete
       */
      async deleteAnnotationQueue(queueId) {
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, {
          method: "DELETE",
          headers: { ...this.headers, Accept: "application/json" },
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "delete annotation queue");
      }
      /**
       * Add runs to an annotation queue with the specified queue ID.
       * @param queueId - The ID of the annotation queue
       * @param runIds - The IDs of the runs to be added to the annotation queue
       */
      async addRunsToAnnotationQueue(queueId, runIds) {
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(runIds.map((id, i3) => assertUuid(id, `runIds[${i3}]`).toString())),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "add runs to annotation queue");
      }
      /**
       * Get a run from an annotation queue at the specified index.
       * @param queueId - The ID of the annotation queue
       * @param index - The index of the run to retrieve
       * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object
       * @throws {Error} If the run is not found at the given index or for other API-related errors
       */
      async getRunFromAnnotationQueue(queueId, index2) {
        const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`;
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${baseUrl}/${index2}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "get run from annotation queue");
        return await response.json();
      }
      async _currentTenantIsOwner(owner) {
        const settings = await this._getSettings();
        return owner == "-" || settings.tenant_handle === owner;
      }
      async _ownerConflictError(action, owner) {
        const settings = await this._getSettings();
        return new Error(`Cannot ${action} for another tenant.

      Current tenant: ${settings.tenant_handle}

      Requested tenant: ${owner}`);
      }
      async _getLatestCommitHash(promptOwnerAndName) {
        const res = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        const json = await res.json();
        if (!res.ok) {
          const detail = typeof json.detail === "string" ? json.detail : JSON.stringify(json.detail);
          const error = new Error(`Error ${res.status}: ${res.statusText}
${detail}`);
          error.statusCode = res.status;
          throw error;
        }
        if (json.commits.length === 0) {
          return void 0;
        }
        return json.commits[0].commit_hash;
      }
      async _likeOrUnlikePrompt(promptIdentifier, like) {
        const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/likes/${owner}/${promptName}`, {
          method: "POST",
          body: JSON.stringify({ like }),
          headers: { ...this.headers, "Content-Type": "application/json" },
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`);
        return await response.json();
      }
      async _getPromptUrl(promptIdentifier) {
        const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);
        if (!await this._currentTenantIsOwner(owner)) {
          if (commitHash !== "latest") {
            return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`;
          } else {
            return `${this.getHostUrl()}/hub/${owner}/${promptName}`;
          }
        } else {
          const settings = await this._getSettings();
          if (commitHash !== "latest") {
            return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`;
          } else {
            return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`;
          }
        }
      }
      async promptExists(promptIdentifier) {
        const prompt = await this.getPrompt(promptIdentifier);
        return !!prompt;
      }
      async likePrompt(promptIdentifier) {
        return this._likeOrUnlikePrompt(promptIdentifier, true);
      }
      async unlikePrompt(promptIdentifier) {
        return this._likeOrUnlikePrompt(promptIdentifier, false);
      }
      async *listCommits(promptOwnerAndName) {
        for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) {
          yield* commits;
        }
      }
      async *listPrompts(options) {
        const params = new URLSearchParams();
        params.append("sort_field", options?.sortField ?? "updated_at");
        params.append("sort_direction", "desc");
        params.append("is_archived", (!!options?.isArchived).toString());
        if (options?.isPublic !== void 0) {
          params.append("is_public", options.isPublic.toString());
        }
        if (options?.query) {
          params.append("query", options.query);
        }
        for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) {
          yield* prompts;
        }
      }
      async getPrompt(promptIdentifier) {
        const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/${owner}/${promptName}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        if (response.status === 404) {
          return null;
        }
        await raiseForStatus(response, "get prompt");
        const result = await response.json();
        if (result.repo) {
          return result.repo;
        } else {
          return null;
        }
      }
      async createPrompt(promptIdentifier, options) {
        const settings = await this._getSettings();
        if (options?.isPublic && !settings.tenant_handle) {
          throw new Error(`Cannot create a public prompt without first

        creating a LangChain Hub handle. 
        You can add a handle by creating a public prompt at:

        https://smith.langchain.com/prompts`);
        }
        const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier);
        if (!await this._currentTenantIsOwner(owner)) {
          throw await this._ownerConflictError("create a prompt", owner);
        }
        const data = {
          repo_handle: promptName,
          ...options?.description && { description: options.description },
          ...options?.readme && { readme: options.readme },
          ...options?.tags && { tags: options.tags },
          is_public: !!options?.isPublic
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(data),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create prompt");
        const { repo } = await response.json();
        return repo;
      }
      async createCommit(promptIdentifier, object, options) {
        if (!await this.promptExists(promptIdentifier)) {
          throw new Error("Prompt does not exist, you must create it first.");
        }
        const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier);
        const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash;
        const payload = {
          manifest: JSON.parse(JSON.stringify(object)),
          parent_commit: resolvedParentCommitHash
        };
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${owner}/${promptName}`, {
          method: "POST",
          headers: { ...this.headers, "Content-Type": "application/json" },
          body: JSON.stringify(payload),
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "create commit");
        const result = await response.json();
        return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`);
      }
      /**
       * Update examples with attachments using multipart form data.
       * @param updates List of ExampleUpdateWithAttachments objects to upsert
       * @returns Promise with the update response
       */
      async updateExamplesMultipart(datasetId, updates = []) {
        if (!await this._getMultiPartSupport()) {
          throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");
        }
        const formData = new FormData();
        for (const example of updates) {
          const exampleId = example.id;
          const exampleBody = {
            ...example.metadata && { metadata: example.metadata },
            ...example.split && { split: example.split }
          };
          const stringifiedExample = stringify(exampleBody);
          const exampleBlob = new Blob([stringifiedExample], {
            type: "application/json"
          });
          formData.append(exampleId, exampleBlob);
          if (example.inputs) {
            const stringifiedInputs = stringify(example.inputs);
            const inputsBlob = new Blob([stringifiedInputs], {
              type: "application/json"
            });
            formData.append(`${exampleId}.inputs`, inputsBlob);
          }
          if (example.outputs) {
            const stringifiedOutputs = stringify(example.outputs);
            const outputsBlob = new Blob([stringifiedOutputs], {
              type: "application/json"
            });
            formData.append(`${exampleId}.outputs`, outputsBlob);
          }
          if (example.attachments) {
            for (const [name, attachment] of Object.entries(example.attachments)) {
              let mimeType;
              let data;
              if (Array.isArray(attachment)) {
                [mimeType, data] = attachment;
              } else {
                mimeType = attachment.mimeType;
                data = attachment.data;
              }
              const attachmentBlob = new Blob([data], {
                type: `${mimeType}; length=${data.byteLength}`
              });
              formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);
            }
          }
          if (example.attachments_operations) {
            const stringifiedAttachmentsOperations = stringify(example.attachments_operations);
            const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], {
              type: "application/json"
            });
            formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob);
          }
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, {
          method: "PATCH",
          headers: this.headers,
          body: formData
        });
        const result = await response.json();
        return result;
      }
      /**
       * Upload examples with attachments using multipart form data.
       * @param uploads List of ExampleUploadWithAttachments objects to upload
       * @returns Promise with the upload response
       */
      async uploadExamplesMultipart(datasetId, uploads = []) {
        if (!await this._getMultiPartSupport()) {
          throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");
        }
        const formData = new FormData();
        for (const example of uploads) {
          const exampleId = (example.id ?? v4_default2()).toString();
          const exampleBody = {
            created_at: example.created_at,
            ...example.metadata && { metadata: example.metadata },
            ...example.split && { split: example.split }
          };
          const stringifiedExample = stringify(exampleBody);
          const exampleBlob = new Blob([stringifiedExample], {
            type: "application/json"
          });
          formData.append(exampleId, exampleBlob);
          const stringifiedInputs = stringify(example.inputs);
          const inputsBlob = new Blob([stringifiedInputs], {
            type: "application/json"
          });
          formData.append(`${exampleId}.inputs`, inputsBlob);
          if (example.outputs) {
            const stringifiedOutputs = stringify(example.outputs);
            const outputsBlob = new Blob([stringifiedOutputs], {
              type: "application/json"
            });
            formData.append(`${exampleId}.outputs`, outputsBlob);
          }
          if (example.attachments) {
            for (const [name, attachment] of Object.entries(example.attachments)) {
              let mimeType;
              let data;
              if (Array.isArray(attachment)) {
                [mimeType, data] = attachment;
              } else {
                mimeType = attachment.mimeType;
                data = attachment.data;
              }
              const attachmentBlob = new Blob([data], {
                type: `${mimeType}; length=${data.byteLength}`
              });
              formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);
            }
          }
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, {
          method: "POST",
          headers: this.headers,
          body: formData
        });
        const result = await response.json();
        return result;
      }
      async updatePrompt(promptIdentifier, options) {
        if (!await this.promptExists(promptIdentifier)) {
          throw new Error("Prompt does not exist, you must create it first.");
        }
        const [owner, promptName] = parsePromptIdentifier(promptIdentifier);
        if (!await this._currentTenantIsOwner(owner)) {
          throw await this._ownerConflictError("update a prompt", owner);
        }
        const payload = {};
        if (options?.description !== void 0)
          payload.description = options.description;
        if (options?.readme !== void 0)
          payload.readme = options.readme;
        if (options?.tags !== void 0)
          payload.tags = options.tags;
        if (options?.isPublic !== void 0)
          payload.is_public = options.isPublic;
        if (options?.isArchived !== void 0)
          payload.is_archived = options.isArchived;
        if (Object.keys(payload).length === 0) {
          throw new Error("No valid update options provided");
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/${owner}/${promptName}`, {
          method: "PATCH",
          body: JSON.stringify(payload),
          headers: {
            ...this.headers,
            "Content-Type": "application/json"
          },
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "update prompt");
        return response.json();
      }
      async deletePrompt(promptIdentifier) {
        if (!await this.promptExists(promptIdentifier)) {
          throw new Error("Prompt does not exist, you must create it first.");
        }
        const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier);
        if (!await this._currentTenantIsOwner(owner)) {
          throw await this._ownerConflictError("delete a prompt", owner);
        }
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/${owner}/${promptName}`, {
          method: "DELETE",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        return await response.json();
      }
      async pullPromptCommit(promptIdentifier, options) {
        const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);
        const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, {
          method: "GET",
          headers: this.headers,
          signal: AbortSignal.timeout(this.timeout_ms),
          ...this.fetchOptions
        });
        await raiseForStatus(response, "pull prompt commit");
        const result = await response.json();
        return {
          owner,
          repo: promptName,
          commit_hash: result.commit_hash,
          manifest: result.manifest,
          examples: result.examples
        };
      }
      /**
       * This method should not be used directly, use `import { pull } from "langchain/hub"` instead.
       * Using this method directly returns the JSON string of the prompt rather than a LangChain object.
       * @private
       */
      async _pullPrompt(promptIdentifier, options) {
        const promptObject = await this.pullPromptCommit(promptIdentifier, {
          includeModel: options?.includeModel
        });
        const prompt = JSON.stringify(promptObject.manifest);
        return prompt;
      }
      async pushPrompt(promptIdentifier, options) {
        if (await this.promptExists(promptIdentifier)) {
          if (options && Object.keys(options).some((key) => key !== "object")) {
            await this.updatePrompt(promptIdentifier, {
              description: options?.description,
              readme: options?.readme,
              tags: options?.tags,
              isPublic: options?.isPublic
            });
          }
        } else {
          await this.createPrompt(promptIdentifier, {
            description: options?.description,
            readme: options?.readme,
            tags: options?.tags,
            isPublic: options?.isPublic
          });
        }
        if (!options?.object) {
          return await this._getPromptUrl(promptIdentifier);
        }
        const url = await this.createCommit(promptIdentifier, options?.object, {
          parentCommitHash: options?.parentCommitHash
        });
        return url;
      }
      /**
         * Clone a public dataset to your own langsmith tenant.
         * This operation is idempotent. If you already have a dataset with the given name,
         * this function will do nothing.
      
         * @param {string} tokenOrUrl The token of the public dataset to clone.
         * @param {Object} [options] Additional options for cloning the dataset.
         * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client.
         * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset.
         * @returns {Promise<void>}
         */
      async clonePublicDataset(tokenOrUrl, options = {}) {
        const { sourceApiUrl = this.apiUrl, datasetName } = options;
        const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl);
        const sourceClient = new Client({
          apiUrl: parsedApiUrl,
          // Placeholder API key not needed anymore in most cases, but
          // some private deployments may have API key-based rate limiting
          // that would cause this to fail if we provide no value.
          apiKey: "placeholder"
        });
        const ds = await sourceClient.readSharedDataset(tokenUuid);
        const finalDatasetName = datasetName || ds.name;
        try {
          if (await this.hasDataset({ datasetId: finalDatasetName })) {
            console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`);
            return;
          }
        } catch (_2) {
        }
        const examples = await sourceClient.listSharedExamples(tokenUuid);
        const dataset = await this.createDataset(finalDatasetName, {
          description: ds.description,
          dataType: ds.data_type || "kv",
          inputsSchema: ds.inputs_schema_definition ?? void 0,
          outputsSchema: ds.outputs_schema_definition ?? void 0
        });
        try {
          await this.createExamples({
            inputs: examples.map((e3) => e3.inputs),
            outputs: examples.flatMap((e3) => e3.outputs ? [e3.outputs] : []),
            datasetId: dataset.id
          });
        } catch (e3) {
          console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`);
          throw e3;
        }
      }
      parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind4 = "dataset") {
        try {
          assertUuid(urlOrToken);
          return [apiUrl, urlOrToken];
        } catch (_2) {
        }
        try {
          const parsedUrl = new URL(urlOrToken);
          const pathParts = parsedUrl.pathname.split("/").filter((part) => part !== "");
          if (pathParts.length >= numParts) {
            const tokenUuid = pathParts[pathParts.length - numParts];
            return [apiUrl, tokenUuid];
          } else {
            throw new Error(`Invalid public ${kind4} URL: ${urlOrToken}`);
          }
        } catch (error) {
          throw new Error(`Invalid public ${kind4} URL or token: ${urlOrToken}`);
        }
      }
      /**
       * Awaits all pending trace batches. Useful for environments where
       * you need to be sure that all tracing requests finish before execution ends,
       * such as serverless environments.
       *
       * @example
       * ```
       * import { Client } from "langsmith";
       *
       * const client = new Client();
       *
       * try {
       *   // Tracing happens here
       *   ...
       * } finally {
       *   await client.awaitPendingTraceBatches();
       * }
       * ```
       *
       * @returns A promise that resolves once all currently pending traces have sent.
       */
      awaitPendingTraceBatches() {
        if (this.manualFlushMode) {
          console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches.");
          return Promise.resolve();
        }
        return Promise.all([
          ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise),
          this.batchIngestCaller.queue.onIdle()
        ]);
      }
    };
  }
});

// node_modules/langsmith/dist/index.js
var __version__;
var init_dist = __esm({
  "node_modules/langsmith/dist/index.js"() {
    init_client();
    init_run_trees();
    init_fetch();
    __version__ = "0.2.14";
  }
});

// node_modules/langsmith/dist/utils/env.js
function getRuntimeEnvironment() {
  if (runtimeEnvironment === void 0) {
    const env = getEnv();
    const releaseEnv = getShas();
    runtimeEnvironment = {
      library: "langsmith",
      runtime: env,
      sdk: "langsmith-js",
      sdk_version: __version__,
      ...releaseEnv
    };
  }
  return runtimeEnvironment;
}
function getLangChainEnvVarsMetadata() {
  const allEnvVars = getEnvironmentVariables() || {};
  const envVars = {};
  const excluded = [
    "LANGCHAIN_API_KEY",
    "LANGCHAIN_ENDPOINT",
    "LANGCHAIN_TRACING_V2",
    "LANGCHAIN_PROJECT",
    "LANGCHAIN_SESSION",
    "LANGSMITH_API_KEY",
    "LANGSMITH_ENDPOINT",
    "LANGSMITH_TRACING_V2",
    "LANGSMITH_PROJECT",
    "LANGSMITH_SESSION"
  ];
  for (const [key, value] of Object.entries(allEnvVars)) {
    if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) {
      if (key === "LANGCHAIN_REVISION_ID") {
        envVars["revision_id"] = value;
      } else {
        envVars[key] = value;
      }
    }
  }
  return envVars;
}
function getEnvironmentVariables() {
  try {
    if (typeof process !== "undefined" && process.env) {
      return Object.entries(process.env).reduce((acc, [key, value]) => {
        acc[key] = String(value);
        return acc;
      }, {});
    }
    return void 0;
  } catch (e3) {
    return void 0;
  }
}
function getEnvironmentVariable(name) {
  try {
    return typeof process !== "undefined" ? (
      // eslint-disable-next-line no-process-env
      process.env?.[name]
    ) : void 0;
  } catch (e3) {
    return void 0;
  }
}
function getLangSmithEnvironmentVariable(name) {
  return getEnvironmentVariable(`LANGSMITH_${name}`) || getEnvironmentVariable(`LANGCHAIN_${name}`);
}
function getShas() {
  if (cachedCommitSHAs !== void 0) {
    return cachedCommitSHAs;
  }
  const common_release_envs = [
    "VERCEL_GIT_COMMIT_SHA",
    "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
    "COMMIT_REF",
    "RENDER_GIT_COMMIT",
    "CI_COMMIT_SHA",
    "CIRCLE_SHA1",
    "CF_PAGES_COMMIT_SHA",
    "REACT_APP_GIT_SHA",
    "SOURCE_VERSION",
    "GITHUB_SHA",
    "TRAVIS_COMMIT",
    "GIT_COMMIT",
    "BUILD_VCS_NUMBER",
    "bamboo_planRepository_revision",
    "Build.SourceVersion",
    "BITBUCKET_COMMIT",
    "DRONE_COMMIT_SHA",
    "SEMAPHORE_GIT_SHA",
    "BUILDKITE_COMMIT"
  ];
  const shas = {};
  for (const env of common_release_envs) {
    const envVar = getEnvironmentVariable(env);
    if (envVar !== void 0) {
      shas[env] = envVar;
    }
  }
  cachedCommitSHAs = shas;
  return shas;
}
var globalEnv, isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment, cachedCommitSHAs;
var init_env = __esm({
  "node_modules/langsmith/dist/utils/env.js"() {
    init_dist();
    isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
    isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
    isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom"));
    isDeno = () => typeof Deno !== "undefined";
    isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno();
    getEnv = () => {
      if (globalEnv) {
        return globalEnv;
      }
      if (isBrowser()) {
        globalEnv = "browser";
      } else if (isNode()) {
        globalEnv = "node";
      } else if (isWebWorker()) {
        globalEnv = "webworker";
      } else if (isJsDom()) {
        globalEnv = "jsdom";
      } else if (isDeno()) {
        globalEnv = "deno";
      } else {
        globalEnv = "other";
      }
      return globalEnv;
    };
  }
});

// node_modules/langsmith/dist/env.js
var isTracingEnabled;
var init_env2 = __esm({
  "node_modules/langsmith/dist/env.js"() {
    init_env();
    isTracingEnabled = (tracingEnabled) => {
      if (tracingEnabled !== void 0) {
        return tracingEnabled;
      }
      const envVars = ["TRACING_V2", "TRACING"];
      return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true");
    };
  }
});

// node_modules/langsmith/dist/singletons/constants.js
var _LC_CONTEXT_VARIABLES_KEY;
var init_constants = __esm({
  "node_modules/langsmith/dist/singletons/constants.js"() {
    _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
  }
});

// node_modules/langsmith/dist/run_trees.js
function stripNonAlphanumeric(input) {
  return input.replace(/[-:.]/g, "");
}
function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) {
  const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
  return stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId;
}
function isRunTree(x2) {
  return x2 !== void 0 && typeof x2.createChild === "function" && typeof x2.postRun === "function";
}
function isLangChainTracerLike(x2) {
  return typeof x2 === "object" && x2 != null && typeof x2.name === "string" && x2.name === "langchain_tracer";
}
function containsLangChainTracerLike(x2) {
  return Array.isArray(x2) && x2.some((callback) => isLangChainTracerLike(callback));
}
function isCallbackManagerLike(x2) {
  return typeof x2 === "object" && x2 != null && Array.isArray(x2.handlers);
}
function isRunnableConfigLike(x2) {
  return x2 !== void 0 && typeof x2.callbacks === "object" && // Callback manager with a langchain tracer
  (containsLangChainTracerLike(x2.callbacks?.handlers) || // Or it's an array with a LangChainTracerLike object within it
  containsLangChainTracerLike(x2.callbacks));
}
var Baggage, RunTree;
var init_run_trees = __esm({
  "node_modules/langsmith/dist/run_trees.js"() {
    init_esm_browser2();
    init_env();
    init_client();
    init_env2();
    init_warn();
    init_constants();
    Baggage = class {
      constructor(metadata, tags) {
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.metadata = metadata;
        this.tags = tags;
      }
      static fromHeader(value) {
        const items = value.split(",");
        let metadata = {};
        let tags = [];
        for (const item of items) {
          const [key, uriValue] = item.split("=");
          const value2 = decodeURIComponent(uriValue);
          if (key === "langsmith-metadata") {
            metadata = JSON.parse(value2);
          } else if (key === "langsmith-tags") {
            tags = value2.split(",");
          }
        }
        return new Baggage(metadata, tags);
      }
      toHeader() {
        const items = [];
        if (this.metadata && Object.keys(this.metadata).length > 0) {
          items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);
        }
        if (this.tags && this.tags.length > 0) {
          items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);
        }
        return items.join(",");
      }
    };
    RunTree = class {
      constructor(originalConfig) {
        Object.defineProperty(this, "id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "run_type", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "project_name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "parent_run", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "child_runs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "start_time", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "end_time", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "extra", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "error", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "serialized", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "inputs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "outputs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "reference_example_id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "client", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "events", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "trace_id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "dotted_order", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tracingEnabled", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "execution_order", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "child_execution_order", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "attachments", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (isRunTree(originalConfig)) {
          Object.assign(this, { ...originalConfig });
          return;
        }
        const defaultConfig = RunTree.getDefaultConfig();
        const { metadata, ...config } = originalConfig;
        const client2 = config.client ?? RunTree.getSharedClient();
        const dedupedMetadata = {
          ...metadata,
          ...config?.extra?.metadata
        };
        config.extra = { ...config.extra, metadata: dedupedMetadata };
        Object.assign(this, { ...defaultConfig, ...config, client: client2 });
        if (!this.trace_id) {
          if (this.parent_run) {
            this.trace_id = this.parent_run.trace_id ?? this.id;
          } else {
            this.trace_id = this.id;
          }
        }
        this.execution_order ?? (this.execution_order = 1);
        this.child_execution_order ?? (this.child_execution_order = 1);
        if (!this.dotted_order) {
          const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order);
          if (this.parent_run) {
            this.dotted_order = this.parent_run.dotted_order + "." + currentDottedOrder;
          } else {
            this.dotted_order = currentDottedOrder;
          }
        }
      }
      static getDefaultConfig() {
        return {
          id: v4_default2(),
          run_type: "chain",
          project_name: getEnvironmentVariable("LANGCHAIN_PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate
          "default",
          child_runs: [],
          api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984",
          api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"),
          caller_options: {},
          start_time: Date.now(),
          serialized: {},
          inputs: {},
          extra: {}
        };
      }
      static getSharedClient() {
        if (!RunTree.sharedClient) {
          RunTree.sharedClient = new Client();
        }
        return RunTree.sharedClient;
      }
      createChild(config) {
        const child_execution_order = this.child_execution_order + 1;
        const child = new RunTree({
          ...config,
          parent_run: this,
          project_name: this.project_name,
          client: this.client,
          tracingEnabled: this.tracingEnabled,
          execution_order: child_execution_order,
          child_execution_order
        });
        if (_LC_CONTEXT_VARIABLES_KEY in this) {
          child[_LC_CONTEXT_VARIABLES_KEY] = this[_LC_CONTEXT_VARIABLES_KEY];
        }
        const LC_CHILD = Symbol.for("lc:child_config");
        const presentConfig = config.extra?.[LC_CHILD] ?? this.extra[LC_CHILD];
        if (isRunnableConfigLike(presentConfig)) {
          const newConfig = { ...presentConfig };
          const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0;
          if (callbacks) {
            Object.assign(callbacks, { _parentRunId: child.id });
            callbacks.handlers?.find(isLangChainTracerLike)?.updateFromRunTree?.(child);
            newConfig.callbacks = callbacks;
          }
          child.extra[LC_CHILD] = newConfig;
        }
        const visited = /* @__PURE__ */ new Set();
        let current = this;
        while (current != null && !visited.has(current.id)) {
          visited.add(current.id);
          current.child_execution_order = Math.max(current.child_execution_order, child_execution_order);
          current = current.parent_run;
        }
        this.child_runs.push(child);
        return child;
      }
      async end(outputs, error, endTime = Date.now(), metadata) {
        this.outputs = this.outputs ?? outputs;
        this.error = this.error ?? error;
        this.end_time = this.end_time ?? endTime;
        if (metadata && Object.keys(metadata).length > 0) {
          this.extra = this.extra ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } : { metadata };
        }
      }
      _convertToCreate(run, runtimeEnv, excludeChildRuns = true) {
        const runExtra = run.extra ?? {};
        if (!runExtra.runtime) {
          runExtra.runtime = {};
        }
        if (runtimeEnv) {
          for (const [k3, v5] of Object.entries(runtimeEnv)) {
            if (!runExtra.runtime[k3]) {
              runExtra.runtime[k3] = v5;
            }
          }
        }
        let child_runs;
        let parent_run_id;
        if (!excludeChildRuns) {
          child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns));
          parent_run_id = void 0;
        } else {
          parent_run_id = run.parent_run?.id;
          child_runs = [];
        }
        const persistedRun = {
          id: run.id,
          name: run.name,
          start_time: run.start_time,
          end_time: run.end_time,
          run_type: run.run_type,
          reference_example_id: run.reference_example_id,
          extra: runExtra,
          serialized: run.serialized,
          error: run.error,
          inputs: run.inputs,
          outputs: run.outputs,
          session_name: run.project_name,
          child_runs,
          parent_run_id,
          trace_id: run.trace_id,
          dotted_order: run.dotted_order,
          tags: run.tags,
          attachments: run.attachments
        };
        return persistedRun;
      }
      async postRun(excludeChildRuns = true) {
        try {
          const runtimeEnv = getRuntimeEnvironment();
          const runCreate = await this._convertToCreate(this, runtimeEnv, true);
          await this.client.createRun(runCreate);
          if (!excludeChildRuns) {
            warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");
            for (const childRun of this.child_runs) {
              await childRun.postRun(false);
            }
          }
        } catch (error) {
          console.error(`Error in postRun for run ${this.id}:`, error);
        }
      }
      async patchRun() {
        try {
          const runUpdate = {
            end_time: this.end_time,
            error: this.error,
            inputs: this.inputs,
            outputs: this.outputs,
            parent_run_id: this.parent_run?.id,
            reference_example_id: this.reference_example_id,
            extra: this.extra,
            events: this.events,
            dotted_order: this.dotted_order,
            trace_id: this.trace_id,
            tags: this.tags,
            attachments: this.attachments
          };
          await this.client.updateRun(this.id, runUpdate);
        } catch (error) {
          console.error(`Error in patchRun for run ${this.id}`, error);
        }
      }
      toJSON() {
        return this._convertToCreate(this, void 0, false);
      }
      static fromRunnableConfig(parentConfig, props) {
        const callbackManager = parentConfig?.callbacks;
        let parentRun;
        let projectName;
        let client2;
        let tracingEnabled = isTracingEnabled();
        if (callbackManager) {
          const parentRunId = callbackManager?.getParentRunId?.() ?? "";
          const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer");
          parentRun = langChainTracer?.getRun?.(parentRunId);
          projectName = langChainTracer?.projectName;
          client2 = langChainTracer?.client;
          tracingEnabled = tracingEnabled || !!langChainTracer;
        }
        if (!parentRun) {
          return new RunTree({
            ...props,
            client: client2,
            tracingEnabled,
            project_name: projectName
          });
        }
        const parentRunTree = new RunTree({
          name: parentRun.name,
          id: parentRun.id,
          trace_id: parentRun.trace_id,
          dotted_order: parentRun.dotted_order,
          client: client2,
          tracingEnabled,
          project_name: projectName,
          tags: [
            ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? []))
          ],
          extra: {
            metadata: {
              ...parentRun?.extra?.metadata,
              ...parentConfig?.metadata
            }
          }
        });
        return parentRunTree.createChild(props);
      }
      static fromDottedOrder(dottedOrder) {
        return this.fromHeaders({ "langsmith-trace": dottedOrder });
      }
      static fromHeaders(headers, inheritArgs) {
        const rawHeaders = "get" in headers && typeof headers.get === "function" ? {
          "langsmith-trace": headers.get("langsmith-trace"),
          baggage: headers.get("baggage")
        } : headers;
        const headerTrace = rawHeaders["langsmith-trace"];
        if (!headerTrace || typeof headerTrace !== "string")
          return void 0;
        const parentDottedOrder = headerTrace.trim();
        const parsedDottedOrder = parentDottedOrder.split(".").map((part) => {
          const [strTime, uuid] = part.split("Z");
          return { strTime, time: Date.parse(strTime + "Z"), uuid };
        });
        const traceId = parsedDottedOrder[0].uuid;
        const config = {
          ...inheritArgs,
          name: inheritArgs?.["name"] ?? "parent",
          run_type: inheritArgs?.["run_type"] ?? "chain",
          start_time: inheritArgs?.["start_time"] ?? Date.now(),
          id: parsedDottedOrder.at(-1)?.uuid,
          trace_id: traceId,
          dotted_order: parentDottedOrder
        };
        if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") {
          const baggage = Baggage.fromHeader(rawHeaders["baggage"]);
          config.metadata = baggage.metadata;
          config.tags = baggage.tags;
        }
        return new RunTree(config);
      }
      toHeaders(headers) {
        const result = {
          "langsmith-trace": this.dotted_order,
          baggage: new Baggage(this.extra?.metadata, this.tags).toHeader()
        };
        if (headers) {
          for (const [key, value] of Object.entries(result)) {
            headers.set(key, value);
          }
        }
        return result;
      }
    };
    Object.defineProperty(RunTree, "sharedClient", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: null
    });
  }
});

// node_modules/langsmith/dist/singletons/traceable.js
function isTraceableFunction(x2) {
  return typeof x2 === "function" && "langsmith:traceable" in x2;
}
var MockAsyncLocalStorage, TRACING_ALS_KEY, mockAsyncLocalStorage, AsyncLocalStorageProvider, AsyncLocalStorageProviderSingleton, getCurrentRunTree, ROOT;
var init_traceable = __esm({
  "node_modules/langsmith/dist/singletons/traceable.js"() {
    init_run_trees();
    MockAsyncLocalStorage = class {
      getStore() {
        return void 0;
      }
      run(_2, callback) {
        return callback();
      }
    };
    TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage");
    mockAsyncLocalStorage = new MockAsyncLocalStorage();
    AsyncLocalStorageProvider = class {
      getInstance() {
        return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage;
      }
      initializeGlobalInstance(instance) {
        if (globalThis[TRACING_ALS_KEY] === void 0) {
          globalThis[TRACING_ALS_KEY] = instance;
        }
      }
    };
    AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();
    getCurrentRunTree = () => {
      const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore();
      if (!isRunTree(runTree)) {
        throw new Error([
          "Could not get the current run tree.",
          "",
          "Please make sure you are calling this method within a traceable function or the tracing is enabled."
        ].join("\n"));
      }
      return runTree;
    };
    ROOT = Symbol.for("langsmith:traceable:root");
  }
});

// node_modules/langsmith/singletons/traceable.js
var init_traceable2 = __esm({
  "node_modules/langsmith/singletons/traceable.js"() {
    init_traceable();
  }
});

// node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js
function hasOwnProperty(obj, key) {
  return _hasOwnProperty.call(obj, key);
}
function _objectKeys(obj) {
  if (Array.isArray(obj)) {
    const keys2 = new Array(obj.length);
    for (let k3 = 0; k3 < keys2.length; k3++) {
      keys2[k3] = "" + k3;
    }
    return keys2;
  }
  if (Object.keys) {
    return Object.keys(obj);
  }
  let keys = [];
  for (let i3 in obj) {
    if (hasOwnProperty(obj, i3)) {
      keys.push(i3);
    }
  }
  return keys;
}
function _deepClone(obj) {
  switch (typeof obj) {
    case "object":
      return JSON.parse(JSON.stringify(obj));
    case "undefined":
      return null;
    default:
      return obj;
  }
}
function isInteger(str2) {
  let i3 = 0;
  const len = str2.length;
  let charCode;
  while (i3 < len) {
    charCode = str2.charCodeAt(i3);
    if (charCode >= 48 && charCode <= 57) {
      i3++;
      continue;
    }
    return false;
  }
  return true;
}
function escapePathComponent(path) {
  if (path.indexOf("/") === -1 && path.indexOf("~") === -1)
    return path;
  return path.replace(/~/g, "~0").replace(/\//g, "~1");
}
function unescapePathComponent(path) {
  return path.replace(/~1/g, "/").replace(/~0/g, "~");
}
function hasUndefined(obj) {
  if (obj === void 0) {
    return true;
  }
  if (obj) {
    if (Array.isArray(obj)) {
      for (let i4 = 0, len = obj.length; i4 < len; i4++) {
        if (hasUndefined(obj[i4])) {
          return true;
        }
      }
    } else if (typeof obj === "object") {
      const objKeys = _objectKeys(obj);
      const objKeysLength = objKeys.length;
      for (var i3 = 0; i3 < objKeysLength; i3++) {
        if (hasUndefined(obj[objKeys[i3]])) {
          return true;
        }
      }
    }
  }
  return false;
}
function patchErrorMessageFormatter(message, args) {
  const messageParts = [message];
  for (const key in args) {
    const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key];
    if (typeof value !== "undefined") {
      messageParts.push(`${key}: ${value}`);
    }
  }
  return messageParts.join("\n");
}
var _hasOwnProperty, PatchError;
var init_helpers = __esm({
  "node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js"() {
    _hasOwnProperty = Object.prototype.hasOwnProperty;
    PatchError = class extends Error {
      constructor(message, name, index2, operation, tree) {
        super(patchErrorMessageFormatter(message, { name, index: index2, operation, tree }));
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: name
        });
        Object.defineProperty(this, "index", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: index2
        });
        Object.defineProperty(this, "operation", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: operation
        });
        Object.defineProperty(this, "tree", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: tree
        });
        Object.setPrototypeOf(this, new.target.prototype);
        this.message = patchErrorMessageFormatter(message, {
          name,
          index: index2,
          operation,
          tree
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js
var core_exports = {};
__export(core_exports, {
  JsonPatchError: () => JsonPatchError,
  _areEquals: () => _areEquals,
  applyOperation: () => applyOperation,
  applyPatch: () => applyPatch,
  applyReducer: () => applyReducer,
  deepClone: () => deepClone,
  getValueByPointer: () => getValueByPointer,
  validate: () => validate3,
  validator: () => validator
});
function getValueByPointer(document2, pointer) {
  if (pointer == "") {
    return document2;
  }
  var getOriginalDestination = { op: "_get", path: pointer };
  applyOperation(document2, getOriginalDestination);
  return getOriginalDestination.value;
}
function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index2 = 0) {
  if (validateOperation) {
    if (typeof validateOperation == "function") {
      validateOperation(operation, 0, document2, operation.path);
    } else {
      validator(operation, 0);
    }
  }
  if (operation.path === "") {
    let returnValue = { newDocument: document2 };
    if (operation.op === "add") {
      returnValue.newDocument = operation.value;
      return returnValue;
    } else if (operation.op === "replace") {
      returnValue.newDocument = operation.value;
      returnValue.removed = document2;
      return returnValue;
    } else if (operation.op === "move" || operation.op === "copy") {
      returnValue.newDocument = getValueByPointer(document2, operation.from);
      if (operation.op === "move") {
        returnValue.removed = document2;
      }
      return returnValue;
    } else if (operation.op === "test") {
      returnValue.test = _areEquals(document2, operation.value);
      if (returnValue.test === false) {
        throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2);
      }
      returnValue.newDocument = document2;
      return returnValue;
    } else if (operation.op === "remove") {
      returnValue.removed = document2;
      returnValue.newDocument = null;
      return returnValue;
    } else if (operation.op === "_get") {
      operation.value = document2;
      return returnValue;
    } else {
      if (validateOperation) {
        throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2);
      } else {
        return returnValue;
      }
    }
  } else {
    if (!mutateDocument) {
      document2 = _deepClone(document2);
    }
    const path = operation.path || "";
    const keys = path.split("/");
    let obj = document2;
    let t3 = 1;
    let len = keys.length;
    let existingPathFragment = void 0;
    let key;
    let validateFunction;
    if (typeof validateOperation == "function") {
      validateFunction = validateOperation;
    } else {
      validateFunction = validator;
    }
    while (true) {
      key = keys[t3];
      if (key && key.indexOf("~") != -1) {
        key = unescapePathComponent(key);
      }
      if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t3 > 0 && keys[t3 - 1] == "constructor")) {
        throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");
      }
      if (validateOperation) {
        if (existingPathFragment === void 0) {
          if (obj[key] === void 0) {
            existingPathFragment = keys.slice(0, t3).join("/");
          } else if (t3 == len - 1) {
            existingPathFragment = operation.path;
          }
          if (existingPathFragment !== void 0) {
            validateFunction(operation, 0, document2, existingPathFragment);
          }
        }
      }
      t3++;
      if (Array.isArray(obj)) {
        if (key === "-") {
          key = obj.length;
        } else {
          if (validateOperation && !isInteger(key)) {
            throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index2, operation, document2);
          } else if (isInteger(key)) {
            key = ~~key;
          }
        }
        if (t3 >= len) {
          if (validateOperation && operation.op === "add" && key > obj.length) {
            throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index2, operation, document2);
          }
          const returnValue = arrOps[operation.op].call(operation, obj, key, document2);
          if (returnValue.test === false) {
            throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2);
          }
          return returnValue;
        }
      } else {
        if (t3 >= len) {
          const returnValue = objOps[operation.op].call(operation, obj, key, document2);
          if (returnValue.test === false) {
            throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2);
          }
          return returnValue;
        }
      }
      obj = obj[key];
      if (validateOperation && t3 < len && (!obj || typeof obj !== "object")) {
        throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2);
      }
    }
  }
}
function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) {
  if (validateOperation) {
    if (!Array.isArray(patch)) {
      throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
    }
  }
  if (!mutateDocument) {
    document2 = _deepClone(document2);
  }
  const results = new Array(patch.length);
  for (let i3 = 0, length = patch.length; i3 < length; i3++) {
    results[i3] = applyOperation(document2, patch[i3], validateOperation, true, banPrototypeModifications, i3);
    document2 = results[i3].newDocument;
  }
  results.newDocument = document2;
  return results;
}
function applyReducer(document2, operation, index2) {
  const operationResult = applyOperation(document2, operation);
  if (operationResult.test === false) {
    throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2);
  }
  return operationResult.newDocument;
}
function validator(operation, index2, document2, existingPathFragment) {
  if (typeof operation !== "object" || operation === null || Array.isArray(operation)) {
    throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index2, operation, document2);
  } else if (!objOps[operation.op]) {
    throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2);
  } else if (typeof operation.path !== "string") {
    throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index2, operation, document2);
  } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) {
    throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index2, operation, document2);
  } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") {
    throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index2, operation, document2);
  } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) {
    throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index2, operation, document2);
  } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) {
    throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index2, operation, document2);
  } else if (document2) {
    if (operation.op == "add") {
      var pathLen = operation.path.split("/").length;
      var existingPathLen = existingPathFragment.split("/").length;
      if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
        throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index2, operation, document2);
      }
    } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") {
      if (operation.path !== existingPathFragment) {
        throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2);
      }
    } else if (operation.op === "move" || operation.op === "copy") {
      var existingValue = {
        op: "_get",
        path: operation.from,
        value: void 0
      };
      var error = validate3([existingValue], document2);
      if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") {
        throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index2, operation, document2);
      }
    }
  }
}
function validate3(sequence, document2, externalValidator) {
  try {
    if (!Array.isArray(sequence)) {
      throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
    }
    if (document2) {
      applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true);
    } else {
      externalValidator = externalValidator || validator;
      for (var i3 = 0; i3 < sequence.length; i3++) {
        externalValidator(sequence[i3], i3, document2, void 0);
      }
    }
  } catch (e3) {
    if (e3 instanceof JsonPatchError) {
      return e3;
    } else {
      throw e3;
    }
  }
}
function _areEquals(a3, b3) {
  if (a3 === b3)
    return true;
  if (a3 && b3 && typeof a3 == "object" && typeof b3 == "object") {
    var arrA = Array.isArray(a3), arrB = Array.isArray(b3), i3, length, key;
    if (arrA && arrB) {
      length = a3.length;
      if (length != b3.length)
        return false;
      for (i3 = length; i3-- !== 0; )
        if (!_areEquals(a3[i3], b3[i3]))
          return false;
      return true;
    }
    if (arrA != arrB)
      return false;
    var keys = Object.keys(a3);
    length = keys.length;
    if (length !== Object.keys(b3).length)
      return false;
    for (i3 = length; i3-- !== 0; )
      if (!b3.hasOwnProperty(keys[i3]))
        return false;
    for (i3 = length; i3-- !== 0; ) {
      key = keys[i3];
      if (!_areEquals(a3[key], b3[key]))
        return false;
    }
    return true;
  }
  return a3 !== a3 && b3 !== b3;
}
var JsonPatchError, deepClone, objOps, arrOps;
var init_core = __esm({
  "node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js"() {
    init_helpers();
    JsonPatchError = PatchError;
    deepClone = _deepClone;
    objOps = {
      add: function(obj, key, document2) {
        obj[key] = this.value;
        return { newDocument: document2 };
      },
      remove: function(obj, key, document2) {
        var removed = obj[key];
        delete obj[key];
        return { newDocument: document2, removed };
      },
      replace: function(obj, key, document2) {
        var removed = obj[key];
        obj[key] = this.value;
        return { newDocument: document2, removed };
      },
      move: function(obj, key, document2) {
        let removed = getValueByPointer(document2, this.path);
        if (removed) {
          removed = _deepClone(removed);
        }
        const originalValue = applyOperation(document2, {
          op: "remove",
          path: this.from
        }).removed;
        applyOperation(document2, {
          op: "add",
          path: this.path,
          value: originalValue
        });
        return { newDocument: document2, removed };
      },
      copy: function(obj, key, document2) {
        const valueToCopy = getValueByPointer(document2, this.from);
        applyOperation(document2, {
          op: "add",
          path: this.path,
          value: _deepClone(valueToCopy)
        });
        return { newDocument: document2 };
      },
      test: function(obj, key, document2) {
        return { newDocument: document2, test: _areEquals(obj[key], this.value) };
      },
      _get: function(obj, key, document2) {
        this.value = obj[key];
        return { newDocument: document2 };
      }
    };
    arrOps = {
      add: function(arr2, i3, document2) {
        if (isInteger(i3)) {
          arr2.splice(i3, 0, this.value);
        } else {
          arr2[i3] = this.value;
        }
        return { newDocument: document2, index: i3 };
      },
      remove: function(arr2, i3, document2) {
        var removedList = arr2.splice(i3, 1);
        return { newDocument: document2, removed: removedList[0] };
      },
      replace: function(arr2, i3, document2) {
        var removed = arr2[i3];
        arr2[i3] = this.value;
        return { newDocument: document2, removed };
      },
      move: objOps.move,
      copy: objOps.copy,
      test: objOps.test,
      _get: objOps._get
    };
  }
});

// node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js
function _generate(mirror, obj, patches, path, invertible) {
  if (obj === mirror) {
    return;
  }
  if (typeof obj.toJSON === "function") {
    obj = obj.toJSON();
  }
  var newKeys = _objectKeys(obj);
  var oldKeys = _objectKeys(mirror);
  var changed = false;
  var deleted = false;
  for (var t3 = oldKeys.length - 1; t3 >= 0; t3--) {
    var key = oldKeys[t3];
    var oldVal = mirror[key];
    if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {
      var newVal = obj[key];
      if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
        _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible);
      } else {
        if (oldVal !== newVal) {
          changed = true;
          if (invertible) {
            patches.push({
              op: "test",
              path: path + "/" + escapePathComponent(key),
              value: _deepClone(oldVal)
            });
          }
          patches.push({
            op: "replace",
            path: path + "/" + escapePathComponent(key),
            value: _deepClone(newVal)
          });
        }
      }
    } else if (Array.isArray(mirror) === Array.isArray(obj)) {
      if (invertible) {
        patches.push({
          op: "test",
          path: path + "/" + escapePathComponent(key),
          value: _deepClone(oldVal)
        });
      }
      patches.push({
        op: "remove",
        path: path + "/" + escapePathComponent(key)
      });
      deleted = true;
    } else {
      if (invertible) {
        patches.push({ op: "test", path, value: mirror });
      }
      patches.push({ op: "replace", path, value: obj });
      changed = true;
    }
  }
  if (!deleted && newKeys.length == oldKeys.length) {
    return;
  }
  for (var t3 = 0; t3 < newKeys.length; t3++) {
    var key = newKeys[t3];
    if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) {
      patches.push({
        op: "add",
        path: path + "/" + escapePathComponent(key),
        value: _deepClone(obj[key])
      });
    }
  }
}
function compare(tree1, tree2, invertible = false) {
  var patches = [];
  _generate(tree1, tree2, patches, "", invertible);
  return patches;
}
var init_duplex = __esm({
  "node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js"() {
    init_helpers();
    init_core();
  }
});

// node_modules/@langchain/core/dist/utils/fast-json-patch/index.js
var fast_json_patch_default;
var init_fast_json_patch = __esm({
  "node_modules/@langchain/core/dist/utils/fast-json-patch/index.js"() {
    init_core();
    init_duplex();
    init_helpers();
    init_core();
    init_helpers();
    fast_json_patch_default = {
      ...core_exports,
      // ...duplex,
      JsonPatchError: PatchError,
      deepClone: _deepClone,
      escapePathComponent,
      unescapePathComponent
    };
  }
});

// node_modules/decamelize/index.js
var require_decamelize = __commonJS({
  "node_modules/decamelize/index.js"(exports, module2) {
    "use strict";
    module2.exports = function(str2, sep) {
      if (typeof str2 !== "string") {
        throw new TypeError("Expected a string");
      }
      sep = typeof sep === "undefined" ? "_" : sep;
      return str2.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase();
    };
  }
});

// node_modules/@langchain/core/node_modules/camelcase/index.js
var require_camelcase = __commonJS({
  "node_modules/@langchain/core/node_modules/camelcase/index.js"(exports, module2) {
    "use strict";
    var UPPERCASE = /[\p{Lu}]/u;
    var LOWERCASE = /[\p{Ll}]/u;
    var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
    var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
    var SEPARATORS = /[_.\- ]+/;
    var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
    var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
    var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
    var preserveCamelCase = (string, toLowerCase, toUpperCase) => {
      let isLastCharLower = false;
      let isLastCharUpper = false;
      let isLastLastCharUpper = false;
      for (let i3 = 0; i3 < string.length; i3++) {
        const character = string[i3];
        if (isLastCharLower && UPPERCASE.test(character)) {
          string = string.slice(0, i3) + "-" + string.slice(i3);
          isLastCharLower = false;
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = true;
          i3++;
        } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
          string = string.slice(0, i3 - 1) + "-" + string.slice(i3 - 1);
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = false;
          isLastCharLower = true;
        } else {
          isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
          isLastLastCharUpper = isLastCharUpper;
          isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
        }
      }
      return string;
    };
    var preserveConsecutiveUppercase = (input, toLowerCase) => {
      LEADING_CAPITAL.lastIndex = 0;
      return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
    };
    var postProcess = (input, toUpperCase) => {
      SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
      NUMBERS_AND_IDENTIFIER.lastIndex = 0;
      return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m3) => toUpperCase(m3));
    };
    var camelCase2 = (input, options) => {
      if (!(typeof input === "string" || Array.isArray(input))) {
        throw new TypeError("Expected the input to be `string | string[]`");
      }
      options = {
        pascalCase: false,
        preserveConsecutiveUppercase: false,
        ...options
      };
      if (Array.isArray(input)) {
        input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-");
      } else {
        input = input.trim();
      }
      if (input.length === 0) {
        return "";
      }
      const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
      const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
      if (input.length === 1) {
        return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
      }
      const hasUpperCase = input !== toLowerCase(input);
      if (hasUpperCase) {
        input = preserveCamelCase(input, toLowerCase, toUpperCase);
      }
      input = input.replace(LEADING_SEPARATORS, "");
      if (options.preserveConsecutiveUppercase) {
        input = preserveConsecutiveUppercase(input, toLowerCase);
      } else {
        input = toLowerCase(input);
      }
      if (options.pascalCase) {
        input = toUpperCase(input.charAt(0)) + input.slice(1);
      }
      return postProcess(input, toUpperCase);
    };
    module2.exports = camelCase2;
    module2.exports.default = camelCase2;
  }
});

// node_modules/@langchain/core/dist/load/map_keys.js
function keyToJson(key, map) {
  return map?.[key] || (0, import_decamelize.default)(key);
}
function mapKeys(fields, mapper, map) {
  const mapped = {};
  for (const key in fields) {
    if (Object.hasOwn(fields, key)) {
      mapped[mapper(key, map)] = fields[key];
    }
  }
  return mapped;
}
var import_decamelize, import_camelcase;
var init_map_keys = __esm({
  "node_modules/@langchain/core/dist/load/map_keys.js"() {
    import_decamelize = __toESM(require_decamelize(), 1);
    import_camelcase = __toESM(require_camelcase(), 1);
  }
});

// node_modules/@langchain/core/dist/load/serializable.js
function shallowCopy(obj) {
  return Array.isArray(obj) ? [...obj] : { ...obj };
}
function replaceSecrets(root2, secretsMap) {
  const result = shallowCopy(root2);
  for (const [path, secretId] of Object.entries(secretsMap)) {
    const [last, ...partsReverse] = path.split(".").reverse();
    let current = result;
    for (const part of partsReverse.reverse()) {
      if (current[part] === void 0) {
        break;
      }
      current[part] = shallowCopy(current[part]);
      current = current[part];
    }
    if (current[last] !== void 0) {
      current[last] = {
        lc: 1,
        type: "secret",
        id: [secretId]
      };
    }
  }
  return result;
}
function get_lc_unique_name(serializableClass) {
  const parentClass = Object.getPrototypeOf(serializableClass);
  const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name());
  if (lcNameIsSubclassed) {
    return serializableClass.lc_name();
  } else {
    return serializableClass.name;
  }
}
var Serializable;
var init_serializable = __esm({
  "node_modules/@langchain/core/dist/load/serializable.js"() {
    init_map_keys();
    Serializable = class {
      /**
       * The name of the serializable. Override to provide an alias or
       * to preserve the serialized module name in minified environments.
       *
       * Implemented as a static method to support loading logic.
       */
      static lc_name() {
        return this.name;
      }
      /**
       * The final serialized identifier for the module.
       */
      get lc_id() {
        return [
          ...this.lc_namespace,
          get_lc_unique_name(this.constructor)
        ];
      }
      /**
       * A map of secrets, which will be omitted from serialization.
       * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
       * Values are the secret ids, which will be used when deserializing.
       */
      get lc_secrets() {
        return void 0;
      }
      /**
       * A map of additional attributes to merge with constructor args.
       * Keys are the attribute names, e.g. "foo".
       * Values are the attribute values, which will be serialized.
       * These attributes need to be accepted by the constructor as arguments.
       */
      get lc_attributes() {
        return void 0;
      }
      /**
       * A map of aliases for constructor args.
       * Keys are the attribute names, e.g. "foo".
       * Values are the alias that will replace the key in serialization.
       * This is used to eg. make argument names match Python.
       */
      get lc_aliases() {
        return void 0;
      }
      constructor(kwargs, ..._args) {
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "lc_kwargs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.lc_kwargs = kwargs || {};
      }
      toJSON() {
        if (!this.lc_serializable) {
          return this.toJSONNotImplemented();
        }
        if (
          // eslint-disable-next-line no-instanceof/no-instanceof
          this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)
        ) {
          return this.toJSONNotImplemented();
        }
        const aliases = {};
        const secrets = {};
        const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
          acc[key] = key in this ? this[key] : this.lc_kwargs[key];
          return acc;
        }, {});
        for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
          Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
          Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
          Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
        }
        Object.keys(secrets).forEach((keyPath) => {
          let read = this;
          let write = kwargs;
          const [last, ...partsReverse] = keyPath.split(".").reverse();
          for (const key of partsReverse.reverse()) {
            if (!(key in read) || read[key] === void 0)
              return;
            if (!(key in write) || write[key] === void 0) {
              if (typeof read[key] === "object" && read[key] != null) {
                write[key] = {};
              } else if (Array.isArray(read[key])) {
                write[key] = [];
              }
            }
            read = read[key];
            write = write[key];
          }
          if (last in read && read[last] !== void 0) {
            write[last] = write[last] || read[last];
          }
        });
        return {
          lc: 1,
          type: "constructor",
          id: this.lc_id,
          kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
        };
      }
      toJSONNotImplemented() {
        return {
          lc: 1,
          type: "not_implemented",
          id: this.lc_id
        };
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/env.js
async function getRuntimeEnvironment2() {
  if (runtimeEnvironment2 === void 0) {
    const env = getEnv2();
    runtimeEnvironment2 = {
      library: "langchain-js",
      runtime: env
    };
  }
  return runtimeEnvironment2;
}
function getEnvironmentVariable2(name) {
  try {
    if (typeof process !== "undefined") {
      return process.env?.[name];
    } else if (isDeno2()) {
      return Deno?.env.get(name);
    } else {
      return void 0;
    }
  } catch (e3) {
    return void 0;
  }
}
var isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2;
var init_env3 = __esm({
  "node_modules/@langchain/core/dist/utils/env.js"() {
    isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined";
    isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
    isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom"));
    isDeno2 = () => typeof Deno !== "undefined";
    isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2();
    getEnv2 = () => {
      let env;
      if (isBrowser2()) {
        env = "browser";
      } else if (isNode2()) {
        env = "node";
      } else if (isWebWorker2()) {
        env = "webworker";
      } else if (isJsDom2()) {
        env = "jsdom";
      } else if (isDeno2()) {
        env = "deno";
      } else {
        env = "other";
      }
      return env;
    };
  }
});

// node_modules/@langchain/core/dist/callbacks/base.js
function callbackHandlerPrefersStreaming(x2) {
  return "lc_prefer_streaming" in x2 && x2.lc_prefer_streaming;
}
var BaseCallbackHandlerMethodsClass, BaseCallbackHandler, isBaseCallbackHandler;
var init_base = __esm({
  "node_modules/@langchain/core/dist/callbacks/base.js"() {
    init_esm_browser();
    init_serializable();
    init_env3();
    BaseCallbackHandlerMethodsClass = class {
    };
    BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {
      get lc_namespace() {
        return ["langchain_core", "callbacks", this.name];
      }
      get lc_secrets() {
        return void 0;
      }
      get lc_attributes() {
        return void 0;
      }
      get lc_aliases() {
        return void 0;
      }
      /**
       * The name of the serializable. Override to provide an alias or
       * to preserve the serialized module name in minified environments.
       *
       * Implemented as a static method to support loading logic.
       */
      static lc_name() {
        return this.name;
      }
      /**
       * The final serialized identifier for the module.
       */
      get lc_id() {
        return [
          ...this.lc_namespace,
          get_lc_unique_name(this.constructor)
        ];
      }
      constructor(input) {
        super();
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "lc_kwargs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "ignoreLLM", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "ignoreChain", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "ignoreAgent", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "ignoreRetriever", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "ignoreCustomEvent", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "raiseError", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "awaitHandlers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"
        });
        this.lc_kwargs = input || {};
        if (input) {
          this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;
          this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
          this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
          this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
          this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent;
          this.raiseError = input.raiseError ?? this.raiseError;
          this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
        }
      }
      copy() {
        return new this.constructor(this);
      }
      toJSON() {
        return Serializable.prototype.toJSON.call(this);
      }
      toJSONNotImplemented() {
        return Serializable.prototype.toJSONNotImplemented.call(this);
      }
      static fromMethods(methods2) {
        class Handler extends BaseCallbackHandler {
          constructor() {
            super();
            Object.defineProperty(this, "name", {
              enumerable: true,
              configurable: true,
              writable: true,
              value: v4_default()
            });
            Object.assign(this, methods2);
          }
        }
        return new Handler();
      }
    };
    isBaseCallbackHandler = (x2) => {
      const callbackHandler = x2;
      return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean";
    };
  }
});

// node_modules/@langchain/core/dist/tracers/base.js
function _coerceToDict(value, defaultKey) {
  return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value };
}
function stripNonAlphanumeric2(input) {
  return input.replace(/[-:.]/g, "");
}
function convertToDottedOrderFormat2(epoch, runId, executionOrder) {
  const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
  return stripNonAlphanumeric2(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId;
}
function isBaseTracer(x2) {
  return typeof x2._addRunToRunMap === "function";
}
var BaseTracer;
var init_base2 = __esm({
  "node_modules/@langchain/core/dist/tracers/base.js"() {
    init_base();
    BaseTracer = class extends BaseCallbackHandler {
      constructor(_fields) {
        super(...arguments);
        Object.defineProperty(this, "runMap", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: /* @__PURE__ */ new Map()
        });
      }
      copy() {
        return this;
      }
      stringifyError(error) {
        if (error instanceof Error) {
          return error.message + (error?.stack ? `

${error.stack}` : "");
        }
        if (typeof error === "string") {
          return error;
        }
        return `${error}`;
      }
      _addChildRun(parentRun, childRun) {
        parentRun.child_runs.push(childRun);
      }
      _addRunToRunMap(run) {
        const currentDottedOrder = convertToDottedOrderFormat2(run.start_time, run.id, run.execution_order);
        const storedRun = { ...run };
        if (storedRun.parent_run_id !== void 0) {
          const parentRun = this.runMap.get(storedRun.parent_run_id);
          if (parentRun) {
            this._addChildRun(parentRun, storedRun);
            parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);
            storedRun.trace_id = parentRun.trace_id;
            if (parentRun.dotted_order !== void 0) {
              storedRun.dotted_order = [
                parentRun.dotted_order,
                currentDottedOrder
              ].join(".");
            } else {
            }
          } else {
          }
        } else {
          storedRun.trace_id = storedRun.id;
          storedRun.dotted_order = currentDottedOrder;
        }
        this.runMap.set(storedRun.id, storedRun);
        return storedRun;
      }
      async _endTrace(run) {
        const parentRun = run.parent_run_id !== void 0 && this.runMap.get(run.parent_run_id);
        if (parentRun) {
          parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order);
        } else {
          await this.persistRun(run);
        }
        this.runMap.delete(run.id);
        await this.onRunUpdate?.(run);
      }
      _getExecutionOrder(parentRunId) {
        const parentRun = parentRunId !== void 0 && this.runMap.get(parentRunId);
        if (!parentRun) {
          return 1;
        }
        return parentRun.child_execution_order + 1;
      }
      /**
       * Create and add a run to the run map for LLM start events.
       * This must sometimes be done synchronously to avoid race conditions
       * when callbacks are backgrounded, so we expose it as a separate method here.
       */
      _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {
        const execution_order = this._getExecutionOrder(parentRunId);
        const start_time = Date.now();
        const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams;
        const run = {
          id: runId,
          name: name ?? llm.id[llm.id.length - 1],
          parent_run_id: parentRunId,
          start_time,
          serialized: llm,
          events: [
            {
              name: "start",
              time: new Date(start_time).toISOString()
            }
          ],
          inputs: { prompts },
          execution_order,
          child_runs: [],
          child_execution_order: execution_order,
          run_type: "llm",
          extra: finalExtraParams ?? {},
          tags: tags || []
        };
        return this._addRunToRunMap(run);
      }
      async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {
        const run = this.runMap.get(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name);
        await this.onRunCreate?.(run);
        await this.onLLMStart?.(run);
        return run;
      }
      /**
       * Create and add a run to the run map for chat model start events.
       * This must sometimes be done synchronously to avoid race conditions
       * when callbacks are backgrounded, so we expose it as a separate method here.
       */
      _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
        const execution_order = this._getExecutionOrder(parentRunId);
        const start_time = Date.now();
        const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams;
        const run = {
          id: runId,
          name: name ?? llm.id[llm.id.length - 1],
          parent_run_id: parentRunId,
          start_time,
          serialized: llm,
          events: [
            {
              name: "start",
              time: new Date(start_time).toISOString()
            }
          ],
          inputs: { messages },
          execution_order,
          child_runs: [],
          child_execution_order: execution_order,
          run_type: "llm",
          extra: finalExtraParams ?? {},
          tags: tags || []
        };
        return this._addRunToRunMap(run);
      }
      async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
        const run = this.runMap.get(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name);
        await this.onRunCreate?.(run);
        await this.onLLMStart?.(run);
        return run;
      }
      async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "llm") {
          throw new Error("No LLM run to end.");
        }
        run.end_time = Date.now();
        run.outputs = output;
        run.events.push({
          name: "end",
          time: new Date(run.end_time).toISOString()
        });
        run.extra = { ...run.extra, ...extraParams };
        await this.onLLMEnd?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleLLMError(error, runId, _parentRunId, _tags, extraParams) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "llm") {
          throw new Error("No LLM run to end.");
        }
        run.end_time = Date.now();
        run.error = this.stringifyError(error);
        run.events.push({
          name: "error",
          time: new Date(run.end_time).toISOString()
        });
        run.extra = { ...run.extra, ...extraParams };
        await this.onLLMError?.(run);
        await this._endTrace(run);
        return run;
      }
      /**
       * Create and add a run to the run map for chain start events.
       * This must sometimes be done synchronously to avoid race conditions
       * when callbacks are backgrounded, so we expose it as a separate method here.
       */
      _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
        const execution_order = this._getExecutionOrder(parentRunId);
        const start_time = Date.now();
        const run = {
          id: runId,
          name: name ?? chain.id[chain.id.length - 1],
          parent_run_id: parentRunId,
          start_time,
          serialized: chain,
          events: [
            {
              name: "start",
              time: new Date(start_time).toISOString()
            }
          ],
          inputs,
          execution_order,
          child_execution_order: execution_order,
          run_type: runType ?? "chain",
          child_runs: [],
          extra: metadata ? { metadata } : {},
          tags: tags || []
        };
        return this._addRunToRunMap(run);
      }
      async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
        const run = this.runMap.get(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name);
        await this.onRunCreate?.(run);
        await this.onChainStart?.(run);
        return run;
      }
      async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) {
        const run = this.runMap.get(runId);
        if (!run) {
          throw new Error("No chain run to end.");
        }
        run.end_time = Date.now();
        run.outputs = _coerceToDict(outputs, "output");
        run.events.push({
          name: "end",
          time: new Date(run.end_time).toISOString()
        });
        if (kwargs?.inputs !== void 0) {
          run.inputs = _coerceToDict(kwargs.inputs, "input");
        }
        await this.onChainEnd?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleChainError(error, runId, _parentRunId, _tags, kwargs) {
        const run = this.runMap.get(runId);
        if (!run) {
          throw new Error("No chain run to end.");
        }
        run.end_time = Date.now();
        run.error = this.stringifyError(error);
        run.events.push({
          name: "error",
          time: new Date(run.end_time).toISOString()
        });
        if (kwargs?.inputs !== void 0) {
          run.inputs = _coerceToDict(kwargs.inputs, "input");
        }
        await this.onChainError?.(run);
        await this._endTrace(run);
        return run;
      }
      /**
       * Create and add a run to the run map for tool start events.
       * This must sometimes be done synchronously to avoid race conditions
       * when callbacks are backgrounded, so we expose it as a separate method here.
       */
      _createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name) {
        const execution_order = this._getExecutionOrder(parentRunId);
        const start_time = Date.now();
        const run = {
          id: runId,
          name: name ?? tool2.id[tool2.id.length - 1],
          parent_run_id: parentRunId,
          start_time,
          serialized: tool2,
          events: [
            {
              name: "start",
              time: new Date(start_time).toISOString()
            }
          ],
          inputs: { input },
          execution_order,
          child_execution_order: execution_order,
          run_type: "tool",
          child_runs: [],
          extra: metadata ? { metadata } : {},
          tags: tags || []
        };
        return this._addRunToRunMap(run);
      }
      async handleToolStart(tool2, input, runId, parentRunId, tags, metadata, name) {
        const run = this.runMap.get(runId) ?? this._createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name);
        await this.onRunCreate?.(run);
        await this.onToolStart?.(run);
        return run;
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async handleToolEnd(output, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "tool") {
          throw new Error("No tool run to end");
        }
        run.end_time = Date.now();
        run.outputs = { output };
        run.events.push({
          name: "end",
          time: new Date(run.end_time).toISOString()
        });
        await this.onToolEnd?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleToolError(error, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "tool") {
          throw new Error("No tool run to end");
        }
        run.end_time = Date.now();
        run.error = this.stringifyError(error);
        run.events.push({
          name: "error",
          time: new Date(run.end_time).toISOString()
        });
        await this.onToolError?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleAgentAction(action, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "chain") {
          return;
        }
        const agentRun = run;
        agentRun.actions = agentRun.actions || [];
        agentRun.actions.push(action);
        agentRun.events.push({
          name: "agent_action",
          time: new Date().toISOString(),
          kwargs: { action }
        });
        await this.onAgentAction?.(run);
      }
      async handleAgentEnd(action, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "chain") {
          return;
        }
        run.events.push({
          name: "agent_end",
          time: new Date().toISOString(),
          kwargs: { action }
        });
        await this.onAgentEnd?.(run);
      }
      /**
       * Create and add a run to the run map for retriever start events.
       * This must sometimes be done synchronously to avoid race conditions
       * when callbacks are backgrounded, so we expose it as a separate method here.
       */
      _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
        const execution_order = this._getExecutionOrder(parentRunId);
        const start_time = Date.now();
        const run = {
          id: runId,
          name: name ?? retriever.id[retriever.id.length - 1],
          parent_run_id: parentRunId,
          start_time,
          serialized: retriever,
          events: [
            {
              name: "start",
              time: new Date(start_time).toISOString()
            }
          ],
          inputs: { query },
          execution_order,
          child_execution_order: execution_order,
          run_type: "retriever",
          child_runs: [],
          extra: metadata ? { metadata } : {},
          tags: tags || []
        };
        return this._addRunToRunMap(run);
      }
      async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
        const run = this.runMap.get(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name);
        await this.onRunCreate?.(run);
        await this.onRetrieverStart?.(run);
        return run;
      }
      async handleRetrieverEnd(documents, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "retriever") {
          throw new Error("No retriever run to end");
        }
        run.end_time = Date.now();
        run.outputs = { documents };
        run.events.push({
          name: "end",
          time: new Date(run.end_time).toISOString()
        });
        await this.onRetrieverEnd?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleRetrieverError(error, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "retriever") {
          throw new Error("No retriever run to end");
        }
        run.end_time = Date.now();
        run.error = this.stringifyError(error);
        run.events.push({
          name: "error",
          time: new Date(run.end_time).toISOString()
        });
        await this.onRetrieverError?.(run);
        await this._endTrace(run);
        return run;
      }
      async handleText(text, runId) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "chain") {
          return;
        }
        run.events.push({
          name: "text",
          time: new Date().toISOString(),
          kwargs: { text }
        });
        await this.onText?.(run);
      }
      async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) {
        const run = this.runMap.get(runId);
        if (!run || run?.run_type !== "llm") {
          throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);
        }
        run.events.push({
          name: "new_token",
          time: new Date().toISOString(),
          kwargs: { token, idx, chunk: fields?.chunk }
        });
        await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk });
        return run;
      }
    };
  }
});

// node_modules/@langchain/core/node_modules/ansi-styles/index.js
var require_ansi_styles = __commonJS({
  "node_modules/@langchain/core/node_modules/ansi-styles/index.js"(exports, module2) {
    "use strict";
    var ANSI_BACKGROUND_OFFSET = 10;
    var wrapAnsi256 = (offset5 = 0) => (code) => `\x1B[${38 + offset5};5;${code}m`;
    var wrapAnsi16m = (offset5 = 0) => (red, green, blue) => `\x1B[${38 + offset5};2;${red};${green};${blue}m`;
    function assembleStyles() {
      const codes = /* @__PURE__ */ new Map();
      const styles2 = {
        modifier: {
          reset: [0, 0],
          // 21 isn't widely supported and 22 does the same thing
          bold: [1, 22],
          dim: [2, 22],
          italic: [3, 23],
          underline: [4, 24],
          overline: [53, 55],
          inverse: [7, 27],
          hidden: [8, 28],
          strikethrough: [9, 29]
        },
        color: {
          black: [30, 39],
          red: [31, 39],
          green: [32, 39],
          yellow: [33, 39],
          blue: [34, 39],
          magenta: [35, 39],
          cyan: [36, 39],
          white: [37, 39],
          // Bright color
          blackBright: [90, 39],
          redBright: [91, 39],
          greenBright: [92, 39],
          yellowBright: [93, 39],
          blueBright: [94, 39],
          magentaBright: [95, 39],
          cyanBright: [96, 39],
          whiteBright: [97, 39]
        },
        bgColor: {
          bgBlack: [40, 49],
          bgRed: [41, 49],
          bgGreen: [42, 49],
          bgYellow: [43, 49],
          bgBlue: [44, 49],
          bgMagenta: [45, 49],
          bgCyan: [46, 49],
          bgWhite: [47, 49],
          // Bright color
          bgBlackBright: [100, 49],
          bgRedBright: [101, 49],
          bgGreenBright: [102, 49],
          bgYellowBright: [103, 49],
          bgBlueBright: [104, 49],
          bgMagentaBright: [105, 49],
          bgCyanBright: [106, 49],
          bgWhiteBright: [107, 49]
        }
      };
      styles2.color.gray = styles2.color.blackBright;
      styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright;
      styles2.color.grey = styles2.color.blackBright;
      styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright;
      for (const [groupName, group] of Object.entries(styles2)) {
        for (const [styleName, style] of Object.entries(group)) {
          styles2[styleName] = {
            open: `\x1B[${style[0]}m`,
            close: `\x1B[${style[1]}m`
          };
          group[styleName] = styles2[styleName];
          codes.set(style[0], style[1]);
        }
        Object.defineProperty(styles2, groupName, {
          value: group,
          enumerable: false
        });
      }
      Object.defineProperty(styles2, "codes", {
        value: codes,
        enumerable: false
      });
      styles2.color.close = "\x1B[39m";
      styles2.bgColor.close = "\x1B[49m";
      styles2.color.ansi256 = wrapAnsi256();
      styles2.color.ansi16m = wrapAnsi16m();
      styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
      styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
      Object.defineProperties(styles2, {
        rgbToAnsi256: {
          value: (red, green, blue) => {
            if (red === green && green === blue) {
              if (red < 8) {
                return 16;
              }
              if (red > 248) {
                return 231;
              }
              return Math.round((red - 8) / 247 * 24) + 232;
            }
            return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
          },
          enumerable: false
        },
        hexToRgb: {
          value: (hex) => {
            const matches = /(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16));
            if (!matches) {
              return [0, 0, 0];
            }
            let { colorString } = matches.groups;
            if (colorString.length === 3) {
              colorString = colorString.split("").map((character) => character + character).join("");
            }
            const integer = Number.parseInt(colorString, 16);
            return [
              integer >> 16 & 255,
              integer >> 8 & 255,
              integer & 255
            ];
          },
          enumerable: false
        },
        hexToAnsi256: {
          value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)),
          enumerable: false
        }
      });
      return styles2;
    }
    Object.defineProperty(module2, "exports", {
      enumerable: true,
      get: assembleStyles
    });
  }
});

// node_modules/@langchain/core/dist/tracers/console.js
function wrap(style, text) {
  return `${style.open}${text}${style.close}`;
}
function tryJsonStringify(obj, fallback) {
  try {
    return JSON.stringify(obj, null, 2);
  } catch (err) {
    return fallback;
  }
}
function formatKVMapItem(value) {
  if (typeof value === "string") {
    return value.trim();
  }
  if (value === null || value === void 0) {
    return value;
  }
  return tryJsonStringify(value, value.toString());
}
function elapsed(run) {
  if (!run.end_time)
    return "";
  const elapsed2 = run.end_time - run.start_time;
  if (elapsed2 < 1e3) {
    return `${elapsed2}ms`;
  }
  return `${(elapsed2 / 1e3).toFixed(2)}s`;
}
var import_ansi_styles, color, ConsoleCallbackHandler;
var init_console = __esm({
  "node_modules/@langchain/core/dist/tracers/console.js"() {
    import_ansi_styles = __toESM(require_ansi_styles(), 1);
    init_base2();
    ({ color } = import_ansi_styles.default);
    ConsoleCallbackHandler = class extends BaseTracer {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "console_callback_handler"
        });
      }
      /**
       * Method used to persist the run. In this case, it simply returns a
       * resolved promise as there's no persistence logic.
       * @param _run The run to persist.
       * @returns A resolved promise.
       */
      persistRun(_run) {
        return Promise.resolve();
      }
      // utility methods
      /**
       * Method used to get all the parent runs of a given run.
       * @param run The run whose parents are to be retrieved.
       * @returns An array of parent runs.
       */
      getParents(run) {
        const parents = [];
        let currentRun = run;
        while (currentRun.parent_run_id) {
          const parent = this.runMap.get(currentRun.parent_run_id);
          if (parent) {
            parents.push(parent);
            currentRun = parent;
          } else {
            break;
          }
        }
        return parents;
      }
      /**
       * Method used to get a string representation of the run's lineage, which
       * is used in logging.
       * @param run The run whose lineage is to be retrieved.
       * @returns A string representation of the run's lineage.
       */
      getBreadcrumbs(run) {
        const parents = this.getParents(run).reverse();
        const string = [...parents, run].map((parent, i3, arr2) => {
          const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;
          return i3 === arr2.length - 1 ? wrap(import_ansi_styles.default.bold, name) : name;
        }).join(" > ");
        return wrap(color.grey, string);
      }
      // logging methods
      /**
       * Method used to log the start of a chain run.
       * @param run The chain run that has started.
       * @returns void
       */
      onChainStart(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`);
      }
      /**
       * Method used to log the end of a chain run.
       * @param run The chain run that has ended.
       * @returns void
       */
      onChainEnd(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`);
      }
      /**
       * Method used to log any errors of a chain run.
       * @param run The chain run that has errored.
       * @returns void
       */
      onChainError(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`);
      }
      /**
       * Method used to log the start of an LLM run.
       * @param run The LLM run that has started.
       * @returns void
       */
      onLLMStart(run) {
        const crumbs = this.getBreadcrumbs(run);
        const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p3) => p3.trim()) } : run.inputs;
        console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`);
      }
      /**
       * Method used to log the end of an LLM run.
       * @param run The LLM run that has ended.
       * @returns void
       */
      onLLMEnd(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`);
      }
      /**
       * Method used to log any errors of an LLM run.
       * @param run The LLM run that has errored.
       * @returns void
       */
      onLLMError(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`);
      }
      /**
       * Method used to log the start of a tool run.
       * @param run The tool run that has started.
       * @returns void
       */
      onToolStart(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`);
      }
      /**
       * Method used to log the end of a tool run.
       * @param run The tool run that has ended.
       * @returns void
       */
      onToolEnd(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`);
      }
      /**
       * Method used to log any errors of a tool run.
       * @param run The tool run that has errored.
       * @returns void
       */
      onToolError(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`);
      }
      /**
       * Method used to log the start of a retriever run.
       * @param run The retriever run that has started.
       * @returns void
       */
      onRetrieverStart(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`);
      }
      /**
       * Method used to log the end of a retriever run.
       * @param run The retriever run that has ended.
       * @returns void
       */
      onRetrieverEnd(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`);
      }
      /**
       * Method used to log any errors of a retriever run.
       * @param run The retriever run that has errored.
       * @returns void
       */
      onRetrieverError(run) {
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`);
      }
      /**
       * Method used to log the action selected by the agent.
       * @param run The run in which the agent action occurred.
       * @returns void
       */
      onAgentAction(run) {
        const agentRun = run;
        const crumbs = this.getBreadcrumbs(run);
        console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`);
      }
    };
  }
});

// node_modules/@langchain/core/dist/errors/index.js
function addLangChainErrorFields(error, lc_error_code) {
  error.lc_error_code = lc_error_code;
  error.message = `${error.message}

Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/
`;
  return error;
}
var init_errors = __esm({
  "node_modules/@langchain/core/dist/errors/index.js"() {
  }
});

// node_modules/@langchain/core/dist/tools/utils.js
function _isToolCall(toolCall) {
  return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call");
}
var ToolInputParsingException;
var init_utils = __esm({
  "node_modules/@langchain/core/dist/tools/utils.js"() {
    ToolInputParsingException = class extends Error {
      constructor(message, output) {
        super(message);
        Object.defineProperty(this, "output", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.output = output;
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/json.js
function parseJsonMarkdown(s4, parser = parsePartialJson) {
  s4 = s4.trim();
  const match2 = /```(json)?(.*)```/s.exec(s4);
  if (!match2) {
    return parser(s4);
  } else {
    return parser(match2[2]);
  }
}
function parsePartialJson(s4) {
  if (typeof s4 === "undefined") {
    return null;
  }
  try {
    return JSON.parse(s4);
  } catch (error) {
  }
  let new_s = "";
  const stack = [];
  let isInsideString = false;
  let escaped = false;
  for (let char of s4) {
    if (isInsideString) {
      if (char === '"' && !escaped) {
        isInsideString = false;
      } else if (char === "\n" && !escaped) {
        char = "\\n";
      } else if (char === "\\") {
        escaped = !escaped;
      } else {
        escaped = false;
      }
    } else {
      if (char === '"') {
        isInsideString = true;
        escaped = false;
      } else if (char === "{") {
        stack.push("}");
      } else if (char === "[") {
        stack.push("]");
      } else if (char === "}" || char === "]") {
        if (stack && stack[stack.length - 1] === char) {
          stack.pop();
        } else {
          return null;
        }
      }
    }
    new_s += char;
  }
  if (isInsideString) {
    new_s += '"';
  }
  for (let i3 = stack.length - 1; i3 >= 0; i3 -= 1) {
    new_s += stack[i3];
  }
  try {
    return JSON.parse(new_s);
  } catch (error) {
    return null;
  }
}
var init_json = __esm({
  "node_modules/@langchain/core/dist/utils/json.js"() {
  }
});

// node_modules/@langchain/core/dist/messages/base.js
function mergeContent(firstContent, secondContent) {
  if (typeof firstContent === "string") {
    if (typeof secondContent === "string") {
      return firstContent + secondContent;
    } else {
      return [{ type: "text", text: firstContent }, ...secondContent];
    }
  } else if (Array.isArray(secondContent)) {
    return _mergeLists(firstContent, secondContent) ?? [
      ...firstContent,
      ...secondContent
    ];
  } else {
    return [...firstContent, { type: "text", text: secondContent }];
  }
}
function _mergeStatus(left, right) {
  if (left === "error" || right === "error") {
    return "error";
  }
  return "success";
}
function stringifyWithDepthLimit(obj, depthLimit) {
  function helper(obj2, currentDepth) {
    if (typeof obj2 !== "object" || obj2 === null || obj2 === void 0) {
      return obj2;
    }
    if (currentDepth >= depthLimit) {
      if (Array.isArray(obj2)) {
        return "[Array]";
      }
      return "[Object]";
    }
    if (Array.isArray(obj2)) {
      return obj2.map((item) => helper(item, currentDepth + 1));
    }
    const result = {};
    for (const key of Object.keys(obj2)) {
      result[key] = helper(obj2[key], currentDepth + 1);
    }
    return result;
  }
  return JSON.stringify(helper(obj, 0), null, 2);
}
function _mergeDicts(left, right) {
  const merged = { ...left };
  for (const [key, value] of Object.entries(right)) {
    if (merged[key] == null) {
      merged[key] = value;
    } else if (value == null) {
      continue;
    } else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) {
      throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);
    } else if (typeof merged[key] === "string") {
      if (key === "type") {
        continue;
      }
      merged[key] += value;
    } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) {
      merged[key] = _mergeDicts(merged[key], value);
    } else if (Array.isArray(merged[key])) {
      merged[key] = _mergeLists(merged[key], value);
    } else if (merged[key] === value) {
      continue;
    } else {
      console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`);
    }
  }
  return merged;
}
function _mergeLists(left, right) {
  if (left === void 0 && right === void 0) {
    return void 0;
  } else if (left === void 0 || right === void 0) {
    return left || right;
  } else {
    const merged = [...left];
    for (const item of right) {
      if (typeof item === "object" && "index" in item && typeof item.index === "number") {
        const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index);
        if (toMerge !== -1) {
          merged[toMerge] = _mergeDicts(merged[toMerge], item);
        } else {
          merged.push(item);
        }
      } else if (typeof item === "object" && "text" in item && item.text === "") {
        continue;
      } else {
        merged.push(item);
      }
    }
    return merged;
  }
}
function _mergeObj(left, right) {
  if (!left && !right) {
    throw new Error("Cannot merge two undefined objects.");
  }
  if (!left || !right) {
    return left || right;
  } else if (typeof left !== typeof right) {
    throw new Error(`Cannot merge objects of different types.
Left ${typeof left}
Right ${typeof right}`);
  } else if (typeof left === "string" && typeof right === "string") {
    return left + right;
  } else if (Array.isArray(left) && Array.isArray(right)) {
    return _mergeLists(left, right);
  } else if (typeof left === "object" && typeof right === "object") {
    return _mergeDicts(left, right);
  } else if (left === right) {
    return left;
  } else {
    throw new Error(`Can not merge objects of different types.
Left ${left}
Right ${right}`);
  }
}
function _isMessageFieldWithRole(x2) {
  return typeof x2.role === "string";
}
function isBaseMessage(messageLike) {
  return typeof messageLike?._getType === "function";
}
function isBaseMessageChunk(messageLike) {
  return isBaseMessage(messageLike) && typeof messageLike.concat === "function";
}
var BaseMessage, BaseMessageChunk;
var init_base3 = __esm({
  "node_modules/@langchain/core/dist/messages/base.js"() {
    init_serializable();
    BaseMessage = class extends Serializable {
      get lc_aliases() {
        return {
          additional_kwargs: "additional_kwargs",
          response_metadata: "response_metadata"
        };
      }
      /**
       * @deprecated
       * Use {@link BaseMessage.content} instead.
       */
      get text() {
        return typeof this.content === "string" ? this.content : "";
      }
      /** The type of the message. */
      getType() {
        return this._getType();
      }
      constructor(fields, kwargs) {
        if (typeof fields === "string") {
          fields = {
            content: fields,
            additional_kwargs: kwargs,
            response_metadata: {}
          };
        }
        if (!fields.additional_kwargs) {
          fields.additional_kwargs = {};
        }
        if (!fields.response_metadata) {
          fields.response_metadata = {};
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "messages"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "content", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "additional_kwargs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "response_metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.name = fields.name;
        this.content = fields.content;
        this.additional_kwargs = fields.additional_kwargs;
        this.response_metadata = fields.response_metadata;
        this.id = fields.id;
      }
      toDict() {
        return {
          type: this._getType(),
          data: this.toJSON().kwargs
        };
      }
      static lc_name() {
        return "BaseMessage";
      }
      // Can't be protected for silly reasons
      get _printableFields() {
        return {
          id: this.id,
          content: this.content,
          name: this.name,
          additional_kwargs: this.additional_kwargs,
          response_metadata: this.response_metadata
        };
      }
      // this private method is used to update the ID for the runtime
      // value as well as in lc_kwargs for serialisation
      _updateId(value) {
        this.id = value;
        this.lc_kwargs.id = value;
      }
      get [Symbol.toStringTag]() {
        return this.constructor.lc_name();
      }
      // Override the default behavior of console.log
      [Symbol.for("nodejs.util.inspect.custom")](depth) {
        if (depth === null) {
          return this;
        }
        const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth));
        return `${this.constructor.lc_name()} ${printable}`;
      }
    };
    BaseMessageChunk = class extends BaseMessage {
    };
  }
});

// node_modules/@langchain/core/dist/messages/tool.js
function isDirectToolOutput(x2) {
  return x2 != null && typeof x2 === "object" && "lc_direct_tool_output" in x2 && x2.lc_direct_tool_output === true;
}
function defaultToolCallParser(rawToolCalls) {
  const toolCalls = [];
  const invalidToolCalls = [];
  for (const toolCall of rawToolCalls) {
    if (!toolCall.function) {
      continue;
    } else {
      const functionName = toolCall.function.name;
      try {
        const functionArgs = JSON.parse(toolCall.function.arguments);
        const parsed = {
          name: functionName || "",
          args: functionArgs || {},
          id: toolCall.id
        };
        toolCalls.push(parsed);
      } catch (error) {
        invalidToolCalls.push({
          name: functionName,
          args: toolCall.function.arguments,
          id: toolCall.id,
          error: "Malformed args."
        });
      }
    }
  }
  return [toolCalls, invalidToolCalls];
}
var ToolMessage, ToolMessageChunk;
var init_tool = __esm({
  "node_modules/@langchain/core/dist/messages/tool.js"() {
    init_base3();
    ToolMessage = class extends BaseMessage {
      static lc_name() {
        return "ToolMessage";
      }
      get lc_aliases() {
        return { tool_call_id: "tool_call_id" };
      }
      constructor(fields, tool_call_id, name) {
        if (typeof fields === "string") {
          fields = { content: fields, name, tool_call_id };
        }
        super(fields);
        Object.defineProperty(this, "lc_direct_tool_output", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "status", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tool_call_id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "artifact", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.tool_call_id = fields.tool_call_id;
        this.artifact = fields.artifact;
        this.status = fields.status;
      }
      _getType() {
        return "tool";
      }
      static isInstance(message) {
        return message._getType() === "tool";
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          tool_call_id: this.tool_call_id,
          artifact: this.artifact
        };
      }
    };
    ToolMessageChunk = class extends BaseMessageChunk {
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "tool_call_id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "status", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "artifact", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.tool_call_id = fields.tool_call_id;
        this.artifact = fields.artifact;
        this.status = fields.status;
      }
      static lc_name() {
        return "ToolMessageChunk";
      }
      _getType() {
        return "tool";
      }
      concat(chunk) {
        return new ToolMessageChunk({
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          artifact: _mergeObj(this.artifact, chunk.artifact),
          tool_call_id: this.tool_call_id,
          id: this.id ?? chunk.id,
          status: _mergeStatus(this.status, chunk.status)
        });
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          tool_call_id: this.tool_call_id,
          artifact: this.artifact
        };
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/ai.js
function isAIMessage(x2) {
  return x2._getType() === "ai";
}
function isAIMessageChunk(x2) {
  return x2._getType() === "ai";
}
var AIMessage, AIMessageChunk;
var init_ai = __esm({
  "node_modules/@langchain/core/dist/messages/ai.js"() {
    init_json();
    init_base3();
    init_tool();
    AIMessage = class extends BaseMessage {
      get lc_aliases() {
        return {
          ...super.lc_aliases,
          tool_calls: "tool_calls",
          invalid_tool_calls: "invalid_tool_calls"
        };
      }
      constructor(fields, kwargs) {
        let initParams;
        if (typeof fields === "string") {
          initParams = {
            content: fields,
            tool_calls: [],
            invalid_tool_calls: [],
            additional_kwargs: kwargs ?? {}
          };
        } else {
          initParams = fields;
          const rawToolCalls = initParams.additional_kwargs?.tool_calls;
          const toolCalls = initParams.tool_calls;
          if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) {
            console.warn([
              "New LangChain packages are available that more efficiently handle",
              "tool calling.\n\nPlease upgrade your packages to versions that set",
              "message tool calls. e.g., `yarn add @langchain/anthropic`,",
              "yarn add @langchain/openai`, etc."
            ].join(" "));
          }
          try {
            if (!(rawToolCalls == null) && toolCalls === void 0) {
              const [toolCalls2, invalidToolCalls] = defaultToolCallParser(rawToolCalls);
              initParams.tool_calls = toolCalls2 ?? [];
              initParams.invalid_tool_calls = invalidToolCalls ?? [];
            } else {
              initParams.tool_calls = initParams.tool_calls ?? [];
              initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? [];
            }
          } catch (e3) {
            initParams.tool_calls = [];
            initParams.invalid_tool_calls = [];
          }
        }
        super(initParams);
        Object.defineProperty(this, "tool_calls", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "invalid_tool_calls", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "usage_metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (typeof initParams !== "string") {
          this.tool_calls = initParams.tool_calls ?? this.tool_calls;
          this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
        }
        this.usage_metadata = initParams.usage_metadata;
      }
      static lc_name() {
        return "AIMessage";
      }
      _getType() {
        return "ai";
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          tool_calls: this.tool_calls,
          invalid_tool_calls: this.invalid_tool_calls,
          usage_metadata: this.usage_metadata
        };
      }
    };
    AIMessageChunk = class extends BaseMessageChunk {
      constructor(fields) {
        let initParams;
        if (typeof fields === "string") {
          initParams = {
            content: fields,
            tool_calls: [],
            invalid_tool_calls: [],
            tool_call_chunks: []
          };
        } else if (fields.tool_call_chunks === void 0) {
          initParams = {
            ...fields,
            tool_calls: fields.tool_calls ?? [],
            invalid_tool_calls: [],
            tool_call_chunks: [],
            usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0
          };
        } else {
          const toolCalls = [];
          const invalidToolCalls = [];
          for (const toolCallChunk of fields.tool_call_chunks) {
            let parsedArgs = {};
            try {
              parsedArgs = parsePartialJson(toolCallChunk.args || "{}");
              if (parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {
                throw new Error("Malformed tool call chunk args.");
              }
              toolCalls.push({
                name: toolCallChunk.name ?? "",
                args: parsedArgs,
                id: toolCallChunk.id,
                type: "tool_call"
              });
            } catch (e3) {
              invalidToolCalls.push({
                name: toolCallChunk.name,
                args: toolCallChunk.args,
                id: toolCallChunk.id,
                error: "Malformed args.",
                type: "invalid_tool_call"
              });
            }
          }
          initParams = {
            ...fields,
            tool_calls: toolCalls,
            invalid_tool_calls: invalidToolCalls,
            usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0
          };
        }
        super(initParams);
        Object.defineProperty(this, "tool_calls", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "invalid_tool_calls", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "tool_call_chunks", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "usage_metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks;
        this.tool_calls = initParams.tool_calls ?? this.tool_calls;
        this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
        this.usage_metadata = initParams.usage_metadata;
      }
      get lc_aliases() {
        return {
          ...super.lc_aliases,
          tool_calls: "tool_calls",
          invalid_tool_calls: "invalid_tool_calls",
          tool_call_chunks: "tool_call_chunks"
        };
      }
      static lc_name() {
        return "AIMessageChunk";
      }
      _getType() {
        return "ai";
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          tool_calls: this.tool_calls,
          tool_call_chunks: this.tool_call_chunks,
          invalid_tool_calls: this.invalid_tool_calls,
          usage_metadata: this.usage_metadata
        };
      }
      concat(chunk) {
        const combinedFields = {
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          tool_call_chunks: [],
          id: this.id ?? chunk.id
        };
        if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) {
          const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks);
          if (rawToolCalls !== void 0 && rawToolCalls.length > 0) {
            combinedFields.tool_call_chunks = rawToolCalls;
          }
        }
        if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) {
          const inputTokenDetails = {
            ...(this.usage_metadata?.input_token_details?.audio !== void 0 || chunk.usage_metadata?.input_token_details?.audio !== void 0) && {
              audio: (this.usage_metadata?.input_token_details?.audio ?? 0) + (chunk.usage_metadata?.input_token_details?.audio ?? 0)
            },
            ...(this.usage_metadata?.input_token_details?.cache_read !== void 0 || chunk.usage_metadata?.input_token_details?.cache_read !== void 0) && {
              cache_read: (this.usage_metadata?.input_token_details?.cache_read ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_read ?? 0)
            },
            ...(this.usage_metadata?.input_token_details?.cache_creation !== void 0 || chunk.usage_metadata?.input_token_details?.cache_creation !== void 0) && {
              cache_creation: (this.usage_metadata?.input_token_details?.cache_creation ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_creation ?? 0)
            }
          };
          const outputTokenDetails = {
            ...(this.usage_metadata?.output_token_details?.audio !== void 0 || chunk.usage_metadata?.output_token_details?.audio !== void 0) && {
              audio: (this.usage_metadata?.output_token_details?.audio ?? 0) + (chunk.usage_metadata?.output_token_details?.audio ?? 0)
            },
            ...(this.usage_metadata?.output_token_details?.reasoning !== void 0 || chunk.usage_metadata?.output_token_details?.reasoning !== void 0) && {
              reasoning: (this.usage_metadata?.output_token_details?.reasoning ?? 0) + (chunk.usage_metadata?.output_token_details?.reasoning ?? 0)
            }
          };
          const left = this.usage_metadata ?? {
            input_tokens: 0,
            output_tokens: 0,
            total_tokens: 0
          };
          const right = chunk.usage_metadata ?? {
            input_tokens: 0,
            output_tokens: 0,
            total_tokens: 0
          };
          const usage_metadata = {
            input_tokens: left.input_tokens + right.input_tokens,
            output_tokens: left.output_tokens + right.output_tokens,
            total_tokens: left.total_tokens + right.total_tokens,
            // Do not include `input_token_details` / `output_token_details` keys in combined fields
            // unless their values are defined.
            ...Object.keys(inputTokenDetails).length > 0 && {
              input_token_details: inputTokenDetails
            },
            ...Object.keys(outputTokenDetails).length > 0 && {
              output_token_details: outputTokenDetails
            }
          };
          combinedFields.usage_metadata = usage_metadata;
        }
        return new AIMessageChunk(combinedFields);
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/chat.js
var ChatMessage, ChatMessageChunk;
var init_chat = __esm({
  "node_modules/@langchain/core/dist/messages/chat.js"() {
    init_base3();
    ChatMessage = class extends BaseMessage {
      static lc_name() {
        return "ChatMessage";
      }
      static _chatMessageClass() {
        return ChatMessage;
      }
      constructor(fields, role) {
        if (typeof fields === "string") {
          fields = { content: fields, role };
        }
        super(fields);
        Object.defineProperty(this, "role", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.role = fields.role;
      }
      _getType() {
        return "generic";
      }
      static isInstance(message) {
        return message._getType() === "generic";
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          role: this.role
        };
      }
    };
    ChatMessageChunk = class extends BaseMessageChunk {
      static lc_name() {
        return "ChatMessageChunk";
      }
      constructor(fields, role) {
        if (typeof fields === "string") {
          fields = { content: fields, role };
        }
        super(fields);
        Object.defineProperty(this, "role", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.role = fields.role;
      }
      _getType() {
        return "generic";
      }
      concat(chunk) {
        return new ChatMessageChunk({
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          role: this.role,
          id: this.id ?? chunk.id
        });
      }
      get _printableFields() {
        return {
          ...super._printableFields,
          role: this.role
        };
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/function.js
var FunctionMessageChunk;
var init_function = __esm({
  "node_modules/@langchain/core/dist/messages/function.js"() {
    init_base3();
    FunctionMessageChunk = class extends BaseMessageChunk {
      static lc_name() {
        return "FunctionMessageChunk";
      }
      _getType() {
        return "function";
      }
      concat(chunk) {
        return new FunctionMessageChunk({
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          name: this.name ?? "",
          id: this.id ?? chunk.id
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/human.js
var HumanMessage, HumanMessageChunk;
var init_human = __esm({
  "node_modules/@langchain/core/dist/messages/human.js"() {
    init_base3();
    HumanMessage = class extends BaseMessage {
      static lc_name() {
        return "HumanMessage";
      }
      _getType() {
        return "human";
      }
    };
    HumanMessageChunk = class extends BaseMessageChunk {
      static lc_name() {
        return "HumanMessageChunk";
      }
      _getType() {
        return "human";
      }
      concat(chunk) {
        return new HumanMessageChunk({
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          id: this.id ?? chunk.id
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/system.js
var SystemMessage, SystemMessageChunk;
var init_system = __esm({
  "node_modules/@langchain/core/dist/messages/system.js"() {
    init_base3();
    SystemMessage = class extends BaseMessage {
      static lc_name() {
        return "SystemMessage";
      }
      _getType() {
        return "system";
      }
    };
    SystemMessageChunk = class extends BaseMessageChunk {
      static lc_name() {
        return "SystemMessageChunk";
      }
      _getType() {
        return "system";
      }
      concat(chunk) {
        return new SystemMessageChunk({
          content: mergeContent(this.content, chunk.content),
          additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
          response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
          id: this.id ?? chunk.id
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/messages/utils.js
function _coerceToolCall(toolCall) {
  if (_isToolCall(toolCall)) {
    return toolCall;
  } else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") {
    return {
      id: toolCall.id,
      args: JSON.parse(toolCall.function.arguments),
      name: toolCall.function.name,
      type: "tool_call"
    };
  } else {
    return toolCall;
  }
}
function isSerializedConstructor(x2) {
  return typeof x2 === "object" && x2 != null && x2.lc === 1 && Array.isArray(x2.id) && x2.kwargs != null && typeof x2.kwargs === "object";
}
function _constructMessageFromParams(params) {
  let type;
  let rest;
  if (isSerializedConstructor(params)) {
    const className = params.id.at(-1);
    if (className === "HumanMessage" || className === "HumanMessageChunk") {
      type = "user";
    } else if (className === "AIMessage" || className === "AIMessageChunk") {
      type = "assistant";
    } else if (className === "SystemMessage" || className === "SystemMessageChunk") {
      type = "system";
    } else {
      type = "unknown";
    }
    rest = params.kwargs;
  } else {
    const { type: extractedType, ...otherParams } = params;
    type = extractedType;
    rest = otherParams;
  }
  if (type === "human" || type === "user") {
    return new HumanMessage(rest);
  } else if (type === "ai" || type === "assistant") {
    const { tool_calls: rawToolCalls, ...other } = rest;
    if (!Array.isArray(rawToolCalls)) {
      return new AIMessage(rest);
    }
    const tool_calls = rawToolCalls.map(_coerceToolCall);
    return new AIMessage({ ...other, tool_calls });
  } else if (type === "system") {
    return new SystemMessage(rest);
  } else if (type === "developer") {
    return new SystemMessage({
      ...rest,
      additional_kwargs: {
        ...rest.additional_kwargs,
        __openai_role__: "developer"
      }
    });
  } else if (type === "tool" && "tool_call_id" in rest) {
    return new ToolMessage({
      ...rest,
      content: rest.content,
      tool_call_id: rest.tool_call_id,
      name: rest.name
    });
  } else {
    const error = addLangChainErrorFields(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.

Received: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE");
    throw error;
  }
}
function coerceMessageLikeToMessage(messageLike) {
  if (typeof messageLike === "string") {
    return new HumanMessage(messageLike);
  } else if (isBaseMessage(messageLike)) {
    return messageLike;
  }
  if (Array.isArray(messageLike)) {
    const [type, content] = messageLike;
    return _constructMessageFromParams({ type, content });
  } else if (_isMessageFieldWithRole(messageLike)) {
    const { role: type, ...rest } = messageLike;
    return _constructMessageFromParams({ ...rest, type });
  } else {
    return _constructMessageFromParams(messageLike);
  }
}
function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") {
  const string_messages = [];
  for (const m3 of messages) {
    let role;
    if (m3._getType() === "human") {
      role = humanPrefix;
    } else if (m3._getType() === "ai") {
      role = aiPrefix;
    } else if (m3._getType() === "system") {
      role = "System";
    } else if (m3._getType() === "function") {
      role = "Function";
    } else if (m3._getType() === "tool") {
      role = "Tool";
    } else if (m3._getType() === "generic") {
      role = m3.role;
    } else {
      throw new Error(`Got unsupported message type: ${m3._getType()}`);
    }
    const nameStr = m3.name ? `${m3.name}, ` : "";
    const readableContent = typeof m3.content === "string" ? m3.content : JSON.stringify(m3.content, null, 2);
    string_messages.push(`${role}: ${nameStr}${readableContent}`);
  }
  return string_messages.join("\n");
}
function convertToChunk(message) {
  const type = message._getType();
  if (type === "human") {
    return new HumanMessageChunk({ ...message });
  } else if (type === "ai") {
    let aiChunkFields = {
      ...message
    };
    if ("tool_calls" in aiChunkFields) {
      aiChunkFields = {
        ...aiChunkFields,
        tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
          ...tc,
          type: "tool_call_chunk",
          index: void 0,
          args: JSON.stringify(tc.args)
        }))
      };
    }
    return new AIMessageChunk({ ...aiChunkFields });
  } else if (type === "system") {
    return new SystemMessageChunk({ ...message });
  } else if (type === "function") {
    return new FunctionMessageChunk({ ...message });
  } else if (ChatMessage.isInstance(message)) {
    return new ChatMessageChunk({ ...message });
  } else {
    throw new Error("Unknown message type.");
  }
}
var init_utils2 = __esm({
  "node_modules/@langchain/core/dist/messages/utils.js"() {
    init_errors();
    init_utils();
    init_ai();
    init_base3();
    init_chat();
    init_function();
    init_human();
    init_system();
    init_tool();
  }
});

// node_modules/langsmith/run_trees.js
var init_run_trees2 = __esm({
  "node_modules/langsmith/run_trees.js"() {
    init_run_trees();
  }
});

// node_modules/langsmith/index.js
var init_langsmith = __esm({
  "node_modules/langsmith/index.js"() {
    init_dist();
  }
});

// node_modules/@langchain/core/dist/singletons/tracer.js
var client, getDefaultLangChainClientSingleton;
var init_tracer = __esm({
  "node_modules/@langchain/core/dist/singletons/tracer.js"() {
    init_langsmith();
    init_env3();
    getDefaultLangChainClientSingleton = () => {
      if (client === void 0) {
        const clientParams = getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? {
          // LangSmith has its own backgrounding system
          blockOnRootRunFinalization: true
        } : {};
        client = new Client(clientParams);
      }
      return client;
    };
  }
});

// node_modules/@langchain/core/dist/tracers/tracer_langchain.js
var LangChainTracer;
var init_tracer_langchain = __esm({
  "node_modules/@langchain/core/dist/tracers/tracer_langchain.js"() {
    init_run_trees2();
    init_traceable2();
    init_env3();
    init_base2();
    init_tracer();
    LangChainTracer = class extends BaseTracer {
      constructor(fields = {}) {
        super(fields);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "langchain_tracer"
        });
        Object.defineProperty(this, "projectName", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "exampleId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "client", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        const { exampleId, projectName, client: client2 } = fields;
        this.projectName = projectName ?? getEnvironmentVariable2("LANGCHAIN_PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION");
        this.exampleId = exampleId;
        this.client = client2 ?? getDefaultLangChainClientSingleton();
        const traceableTree = LangChainTracer.getTraceableRunTree();
        if (traceableTree) {
          this.updateFromRunTree(traceableTree);
        }
      }
      async _convertToCreate(run, example_id = void 0) {
        return {
          ...run,
          extra: {
            ...run.extra,
            runtime: await getRuntimeEnvironment2()
          },
          child_runs: void 0,
          session_name: this.projectName,
          reference_example_id: run.parent_run_id ? void 0 : example_id
        };
      }
      async persistRun(_run) {
      }
      async onRunCreate(run) {
        const persistedRun = await this._convertToCreate(run, this.exampleId);
        await this.client.createRun(persistedRun);
      }
      async onRunUpdate(run) {
        const runUpdate = {
          end_time: run.end_time,
          error: run.error,
          outputs: run.outputs,
          events: run.events,
          inputs: run.inputs,
          trace_id: run.trace_id,
          dotted_order: run.dotted_order,
          parent_run_id: run.parent_run_id,
          extra: run.extra
        };
        await this.client.updateRun(run.id, runUpdate);
      }
      getRun(id) {
        return this.runMap.get(id);
      }
      updateFromRunTree(runTree) {
        let rootRun = runTree;
        const visited = /* @__PURE__ */ new Set();
        while (rootRun.parent_run) {
          if (visited.has(rootRun.id))
            break;
          visited.add(rootRun.id);
          if (!rootRun.parent_run)
            break;
          rootRun = rootRun.parent_run;
        }
        visited.clear();
        const queue2 = [rootRun];
        while (queue2.length > 0) {
          const current = queue2.shift();
          if (!current || visited.has(current.id))
            continue;
          visited.add(current.id);
          this.runMap.set(current.id, current);
          if (current.child_runs) {
            queue2.push(...current.child_runs);
          }
        }
        this.client = runTree.client ?? this.client;
        this.projectName = runTree.project_name ?? this.projectName;
        this.exampleId = runTree.reference_example_id ?? this.exampleId;
      }
      convertToRunTree(id) {
        const runTreeMap = {};
        const runTreeList = [];
        for (const [id2, run] of this.runMap) {
          const runTree = new RunTree({
            ...run,
            child_runs: [],
            parent_run: void 0,
            // inherited properties
            client: this.client,
            project_name: this.projectName,
            reference_example_id: this.exampleId,
            tracingEnabled: true
          });
          runTreeMap[id2] = runTree;
          runTreeList.push([id2, run.dotted_order]);
        }
        runTreeList.sort((a3, b3) => {
          if (!a3[1] || !b3[1])
            return 0;
          return a3[1].localeCompare(b3[1]);
        });
        for (const [id2] of runTreeList) {
          const run = this.runMap.get(id2);
          const runTree = runTreeMap[id2];
          if (!run || !runTree)
            continue;
          if (run.parent_run_id) {
            const parentRunTree = runTreeMap[run.parent_run_id];
            if (parentRunTree) {
              parentRunTree.child_runs.push(runTree);
              runTree.parent_run = parentRunTree;
            }
          }
        }
        return runTreeMap[id];
      }
      static getTraceableRunTree() {
        try {
          return getCurrentRunTree();
        } catch {
          return void 0;
        }
      }
    };
  }
});

// node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js
var TRACING_ALS_KEY2, _CONTEXT_VARIABLES_KEY, setGlobalAsyncLocalStorageInstance, getGlobalAsyncLocalStorageInstance;
var init_globals = __esm({
  "node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js"() {
    TRACING_ALS_KEY2 = Symbol.for("ls:tracing_async_local_storage");
    _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
    setGlobalAsyncLocalStorageInstance = (instance) => {
      globalThis[TRACING_ALS_KEY2] = instance;
    };
    getGlobalAsyncLocalStorageInstance = () => {
      return globalThis[TRACING_ALS_KEY2];
    };
  }
});

// node_modules/@langchain/core/dist/singletons/callbacks.js
function createQueue() {
  const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default;
  return new PQueue({
    autoStart: true,
    concurrency: 1
  });
}
function getQueue() {
  if (typeof queue === "undefined") {
    queue = createQueue();
  }
  return queue;
}
async function consumeCallback(promiseFn, wait) {
  if (wait === true) {
    const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
    if (asyncLocalStorageInstance !== void 0) {
      await asyncLocalStorageInstance.run(void 0, async () => promiseFn());
    } else {
      await promiseFn();
    }
  } else {
    queue = getQueue();
    void queue.add(async () => {
      const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
      if (asyncLocalStorageInstance !== void 0) {
        await asyncLocalStorageInstance.run(void 0, async () => promiseFn());
      } else {
        await promiseFn();
      }
    });
  }
}
var import_p_queue2, queue;
var init_callbacks = __esm({
  "node_modules/@langchain/core/dist/singletons/callbacks.js"() {
    import_p_queue2 = __toESM(require_dist(), 1);
    init_globals();
  }
});

// node_modules/@langchain/core/dist/callbacks/promises.js
var init_promises = __esm({
  "node_modules/@langchain/core/dist/callbacks/promises.js"() {
    init_callbacks();
  }
});

// node_modules/@langchain/core/dist/utils/callbacks.js
var isTracingEnabled2;
var init_callbacks2 = __esm({
  "node_modules/@langchain/core/dist/utils/callbacks.js"() {
    init_env3();
    isTracingEnabled2 = (tracingEnabled) => {
      if (tracingEnabled !== void 0) {
        return tracingEnabled;
      }
      const envVars = [
        "LANGSMITH_TRACING_V2",
        "LANGCHAIN_TRACING_V2",
        "LANGSMITH_TRACING",
        "LANGCHAIN_TRACING"
      ];
      return !!envVars.find((envVar) => getEnvironmentVariable2(envVar) === "true");
    };
  }
});

// node_modules/@langchain/core/dist/singletons/async_local_storage/context.js
function getContextVariable(name) {
  const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
  if (asyncLocalStorageInstance === void 0) {
    return void 0;
  }
  const runTree = asyncLocalStorageInstance.getStore();
  return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name];
}
var LC_CONFIGURE_HOOKS_KEY, _getConfigureHooks;
var init_context = __esm({
  "node_modules/@langchain/core/dist/singletons/async_local_storage/context.js"() {
    init_run_trees2();
    init_globals();
    LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks");
    _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || [];
  }
});

// node_modules/@langchain/core/dist/callbacks/manager.js
function parseCallbackConfigArg(arg) {
  if (!arg) {
    return {};
  } else if (Array.isArray(arg) || "name" in arg) {
    return { callbacks: arg };
  } else {
    return arg;
  }
}
function ensureHandler(handler) {
  if ("name" in handler) {
    return handler;
  }
  return BaseCallbackHandler.fromMethods(handler);
}
var BaseCallbackManager, BaseRunManager, CallbackManagerForRetrieverRun, CallbackManagerForLLMRun, CallbackManagerForChainRun, CallbackManagerForToolRun, CallbackManager;
var init_manager = __esm({
  "node_modules/@langchain/core/dist/callbacks/manager.js"() {
    init_esm_browser();
    init_base();
    init_console();
    init_utils2();
    init_env3();
    init_tracer_langchain();
    init_promises();
    init_callbacks2();
    init_base2();
    init_context();
    BaseCallbackManager = class {
      setHandler(handler) {
        return this.setHandlers([handler]);
      }
    };
    BaseRunManager = class {
      constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) {
        Object.defineProperty(this, "runId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: runId
        });
        Object.defineProperty(this, "handlers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: handlers
        });
        Object.defineProperty(this, "inheritableHandlers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: inheritableHandlers
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: tags
        });
        Object.defineProperty(this, "inheritableTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: inheritableTags
        });
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: metadata
        });
        Object.defineProperty(this, "inheritableMetadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: inheritableMetadata
        });
        Object.defineProperty(this, "_parentRunId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: _parentRunId
        });
      }
      get parentRunId() {
        return this._parentRunId;
      }
      async handleText(text) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          try {
            await handler.handleText?.(text, this.runId, this._parentRunId, this.tags);
          } catch (err) {
            const logFunction = handler.raiseError ? console.error : console.warn;
            logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`);
            if (handler.raiseError) {
              throw err;
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleCustomEvent(eventName, data, _runId, _tags, _metadata) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          try {
            await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata);
          } catch (err) {
            const logFunction = handler.raiseError ? console.error : console.warn;
            logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);
            if (handler.raiseError) {
              throw err;
            }
          }
        }, handler.awaitHandlers)));
      }
    };
    CallbackManagerForRetrieverRun = class extends BaseRunManager {
      getChild(tag) {
        const manager = new CallbackManager(this.runId);
        manager.setHandlers(this.inheritableHandlers);
        manager.addTags(this.inheritableTags);
        manager.addMetadata(this.inheritableMetadata);
        if (tag) {
          manager.addTags([tag], false);
        }
        return manager;
      }
      async handleRetrieverEnd(documents) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreRetriever) {
            try {
              await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleRetrieverError(err) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreRetriever) {
            try {
              await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags);
            } catch (error) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
    };
    CallbackManagerForLLMRun = class extends BaseRunManager {
      async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreLLM) {
            try {
              await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreLLM) {
            try {
              await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams);
            } catch (err2) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`);
              if (handler.raiseError) {
                throw err2;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreLLM) {
            try {
              await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
    };
    CallbackManagerForChainRun = class extends BaseRunManager {
      getChild(tag) {
        const manager = new CallbackManager(this.runId);
        manager.setHandlers(this.inheritableHandlers);
        manager.addTags(this.inheritableTags);
        manager.addMetadata(this.inheritableMetadata);
        if (tag) {
          manager.addTags([tag], false);
        }
        return manager;
      }
      async handleChainError(err, _runId, _parentRunId, _tags, kwargs) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreChain) {
            try {
              await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs);
            } catch (err2) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`);
              if (handler.raiseError) {
                throw err2;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreChain) {
            try {
              await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleAgentAction(action) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreAgent) {
            try {
              await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      async handleAgentEnd(action) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreAgent) {
            try {
              await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
    };
    CallbackManagerForToolRun = class extends BaseRunManager {
      getChild(tag) {
        const manager = new CallbackManager(this.runId);
        manager.setHandlers(this.inheritableHandlers);
        manager.addTags(this.inheritableTags);
        manager.addMetadata(this.inheritableMetadata);
        if (tag) {
          manager.addTags([tag], false);
        }
        return manager;
      }
      async handleToolError(err) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreAgent) {
            try {
              await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags);
            } catch (err2) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`);
              if (handler.raiseError) {
                throw err2;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async handleToolEnd(output) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreAgent) {
            try {
              await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
    };
    CallbackManager = class extends BaseCallbackManager {
      constructor(parentRunId, options) {
        super();
        Object.defineProperty(this, "handlers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "inheritableHandlers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "inheritableTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "inheritableMetadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "callback_manager"
        });
        Object.defineProperty(this, "_parentRunId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.handlers = options?.handlers ?? this.handlers;
        this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers;
        this.tags = options?.tags ?? this.tags;
        this.inheritableTags = options?.inheritableTags ?? this.inheritableTags;
        this.metadata = options?.metadata ?? this.metadata;
        this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata;
        this._parentRunId = parentRunId;
      }
      /**
       * Gets the parent run ID, if any.
       *
       * @returns The parent run ID.
       */
      getParentRunId() {
        return this._parentRunId;
      }
      async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {
        return Promise.all(prompts.map(async (prompt, idx) => {
          const runId_ = idx === 0 && runId ? runId : v4_default();
          await Promise.all(this.handlers.map((handler) => {
            if (handler.ignoreLLM) {
              return;
            }
            if (isBaseTracer(handler)) {
              handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
            }
            return consumeCallback(async () => {
              try {
                await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
              } catch (err) {
                const logFunction = handler.raiseError ? console.error : console.warn;
                logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);
                if (handler.raiseError) {
                  throw err;
                }
              }
            }, handler.awaitHandlers);
          }));
          return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
        }));
      }
      async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {
        return Promise.all(messages.map(async (messageGroup, idx) => {
          const runId_ = idx === 0 && runId ? runId : v4_default();
          await Promise.all(this.handlers.map((handler) => {
            if (handler.ignoreLLM) {
              return;
            }
            if (isBaseTracer(handler)) {
              handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
            }
            return consumeCallback(async () => {
              try {
                if (handler.handleChatModelStart) {
                  await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
                } else if (handler.handleLLMStart) {
                  const messageString = getBufferString(messageGroup);
                  await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
                }
              } catch (err) {
                const logFunction = handler.raiseError ? console.error : console.warn;
                logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);
                if (handler.raiseError) {
                  throw err;
                }
              }
            }, handler.awaitHandlers);
          }));
          return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
        }));
      }
      async handleChainStart(chain, inputs, runId = v4_default(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {
        await Promise.all(this.handlers.map((handler) => {
          if (handler.ignoreChain) {
            return;
          }
          if (isBaseTracer(handler)) {
            handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
          }
          return consumeCallback(async () => {
            try {
              await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }, handler.awaitHandlers);
        }));
        return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
      }
      async handleToolStart(tool2, input, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {
        await Promise.all(this.handlers.map((handler) => {
          if (handler.ignoreAgent) {
            return;
          }
          if (isBaseTracer(handler)) {
            handler._createRunForToolStart(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName);
          }
          return consumeCallback(async () => {
            try {
              await handler.handleToolStart?.(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }, handler.awaitHandlers);
        }));
        return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
      }
      async handleRetrieverStart(retriever, query, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) {
        await Promise.all(this.handlers.map((handler) => {
          if (handler.ignoreRetriever) {
            return;
          }
          if (isBaseTracer(handler)) {
            handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
          }
          return consumeCallback(async () => {
            try {
              await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }, handler.awaitHandlers);
        }));
        return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
      }
      async handleCustomEvent(eventName, data, runId, _tags, _metadata) {
        await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
          if (!handler.ignoreCustomEvent) {
            try {
              await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata);
            } catch (err) {
              const logFunction = handler.raiseError ? console.error : console.warn;
              logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);
              if (handler.raiseError) {
                throw err;
              }
            }
          }
        }, handler.awaitHandlers)));
      }
      addHandler(handler, inherit = true) {
        this.handlers.push(handler);
        if (inherit) {
          this.inheritableHandlers.push(handler);
        }
      }
      removeHandler(handler) {
        this.handlers = this.handlers.filter((_handler) => _handler !== handler);
        this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler);
      }
      setHandlers(handlers, inherit = true) {
        this.handlers = [];
        this.inheritableHandlers = [];
        for (const handler of handlers) {
          this.addHandler(handler, inherit);
        }
      }
      addTags(tags, inherit = true) {
        this.removeTags(tags);
        this.tags.push(...tags);
        if (inherit) {
          this.inheritableTags.push(...tags);
        }
      }
      removeTags(tags) {
        this.tags = this.tags.filter((tag) => !tags.includes(tag));
        this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag));
      }
      addMetadata(metadata, inherit = true) {
        this.metadata = { ...this.metadata, ...metadata };
        if (inherit) {
          this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata };
        }
      }
      removeMetadata(metadata) {
        for (const key of Object.keys(metadata)) {
          delete this.metadata[key];
          delete this.inheritableMetadata[key];
        }
      }
      copy(additionalHandlers = [], inherit = true) {
        const manager = new CallbackManager(this._parentRunId);
        for (const handler of this.handlers) {
          const inheritable = this.inheritableHandlers.includes(handler);
          manager.addHandler(handler, inheritable);
        }
        for (const tag of this.tags) {
          const inheritable = this.inheritableTags.includes(tag);
          manager.addTags([tag], inheritable);
        }
        for (const key of Object.keys(this.metadata)) {
          const inheritable = Object.keys(this.inheritableMetadata).includes(key);
          manager.addMetadata({ [key]: this.metadata[key] }, inheritable);
        }
        for (const handler of additionalHandlers) {
          if (
            // Prevent multiple copies of console_callback_handler
            manager.handlers.filter((h3) => h3.name === "console_callback_handler").some((h3) => h3.name === handler.name)
          ) {
            continue;
          }
          manager.addHandler(handler, inherit);
        }
        return manager;
      }
      static fromHandlers(handlers) {
        class Handler extends BaseCallbackHandler {
          constructor() {
            super();
            Object.defineProperty(this, "name", {
              enumerable: true,
              configurable: true,
              writable: true,
              value: v4_default()
            });
            Object.assign(this, handlers);
          }
        }
        const manager = new this();
        manager.addHandler(new Handler());
        return manager;
      }
      static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) {
        return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options);
      }
      // TODO: Deprecate async method in favor of this one.
      static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) {
        let callbackManager;
        if (inheritableHandlers || localHandlers) {
          if (Array.isArray(inheritableHandlers) || !inheritableHandlers) {
            callbackManager = new CallbackManager();
            callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true);
          } else {
            callbackManager = inheritableHandlers;
          }
          callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false);
        }
        const verboseEnabled = getEnvironmentVariable2("LANGCHAIN_VERBOSE") === "true" || options?.verbose;
        const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled2();
        const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable2("LANGCHAIN_TRACING") ?? false);
        if (verboseEnabled || tracingEnabled) {
          if (!callbackManager) {
            callbackManager = new CallbackManager();
          }
          if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) {
            const consoleHandler = new ConsoleCallbackHandler();
            callbackManager.addHandler(consoleHandler, true);
          }
          if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) {
            if (tracingV2Enabled) {
              const tracerV2 = new LangChainTracer();
              callbackManager.addHandler(tracerV2, true);
              callbackManager._parentRunId = LangChainTracer.getTraceableRunTree()?.id ?? callbackManager._parentRunId;
            }
          }
        }
        for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) {
          const createIfNotInContext = envVar && getEnvironmentVariable2(envVar) === "true" && handlerClass;
          let handler;
          const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0;
          if (contextVarValue && isBaseCallbackHandler(contextVarValue)) {
            handler = contextVarValue;
          } else if (createIfNotInContext) {
            handler = new handlerClass({});
          }
          if (handler !== void 0) {
            if (!callbackManager) {
              callbackManager = new CallbackManager();
            }
            if (!callbackManager.handlers.some((h3) => h3.name === handler.name)) {
              callbackManager.addHandler(handler, inheritable);
            }
          }
        }
        if (inheritableTags || localTags) {
          if (callbackManager) {
            callbackManager.addTags(inheritableTags ?? []);
            callbackManager.addTags(localTags ?? [], false);
          }
        }
        if (inheritableMetadata || localMetadata) {
          if (callbackManager) {
            callbackManager.addMetadata(inheritableMetadata ?? {});
            callbackManager.addMetadata(localMetadata ?? {}, false);
          }
        }
        return callbackManager;
      }
    };
  }
});

// node_modules/@langchain/core/dist/singletons/async_local_storage/index.js
var MockAsyncLocalStorage2, mockAsyncLocalStorage2, LC_CHILD_KEY, AsyncLocalStorageProvider2, AsyncLocalStorageProviderSingleton2;
var init_async_local_storage = __esm({
  "node_modules/@langchain/core/dist/singletons/async_local_storage/index.js"() {
    init_langsmith();
    init_globals();
    init_manager();
    MockAsyncLocalStorage2 = class {
      getStore() {
        return void 0;
      }
      run(_store, callback) {
        return callback();
      }
      enterWith(_store) {
        return void 0;
      }
    };
    mockAsyncLocalStorage2 = new MockAsyncLocalStorage2();
    LC_CHILD_KEY = Symbol.for("lc:child_config");
    AsyncLocalStorageProvider2 = class {
      getInstance() {
        return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage2;
      }
      getRunnableConfig() {
        const storage = this.getInstance();
        return storage.getStore()?.extra?.[LC_CHILD_KEY];
      }
      runWithConfig(config, callback, avoidCreatingRootRunTree) {
        const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata);
        const storage = this.getInstance();
        const previousValue = storage.getStore();
        const parentRunId = callbackManager?.getParentRunId();
        const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer");
        let runTree;
        if (langChainTracer && parentRunId) {
          runTree = langChainTracer.convertToRunTree(parentRunId);
        } else if (!avoidCreatingRootRunTree) {
          runTree = new RunTree({
            name: "<runnable_lambda>",
            tracingEnabled: false
          });
        }
        if (runTree) {
          runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config };
        }
        if (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) {
          runTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY];
        }
        return storage.run(runTree, callback);
      }
      initializeGlobalInstance(instance) {
        if (getGlobalAsyncLocalStorageInstance() === void 0) {
          setGlobalAsyncLocalStorageInstance(instance);
        }
      }
    };
    AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2();
  }
});

// node_modules/@langchain/core/dist/singletons/index.js
var init_singletons = __esm({
  "node_modules/@langchain/core/dist/singletons/index.js"() {
    init_async_local_storage();
    init_globals();
  }
});

// node_modules/@langchain/core/dist/runnables/config.js
async function getCallbackManagerForConfig(config) {
  return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata);
}
function mergeConfigs(...configs) {
  const copy = {};
  for (const options of configs.filter((c4) => !!c4)) {
    for (const key of Object.keys(options)) {
      if (key === "metadata") {
        copy[key] = { ...copy[key], ...options[key] };
      } else if (key === "tags") {
        const baseKeys = copy[key] ?? [];
        copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))];
      } else if (key === "configurable") {
        copy[key] = { ...copy[key], ...options[key] };
      } else if (key === "timeout") {
        if (copy.timeout === void 0) {
          copy.timeout = options.timeout;
        } else if (options.timeout !== void 0) {
          copy.timeout = Math.min(copy.timeout, options.timeout);
        }
      } else if (key === "signal") {
        if (copy.signal === void 0) {
          copy.signal = options.signal;
        } else if (options.signal !== void 0) {
          if ("any" in AbortSignal) {
            copy.signal = AbortSignal.any([
              copy.signal,
              options.signal
            ]);
          } else {
            copy.signal = options.signal;
          }
        }
      } else if (key === "callbacks") {
        const baseCallbacks = copy.callbacks;
        const providedCallbacks = options.callbacks;
        if (Array.isArray(providedCallbacks)) {
          if (!baseCallbacks) {
            copy.callbacks = providedCallbacks;
          } else if (Array.isArray(baseCallbacks)) {
            copy.callbacks = baseCallbacks.concat(providedCallbacks);
          } else {
            const manager = baseCallbacks.copy();
            for (const callback of providedCallbacks) {
              manager.addHandler(ensureHandler(callback), true);
            }
            copy.callbacks = manager;
          }
        } else if (providedCallbacks) {
          if (!baseCallbacks) {
            copy.callbacks = providedCallbacks;
          } else if (Array.isArray(baseCallbacks)) {
            const manager = providedCallbacks.copy();
            for (const callback of baseCallbacks) {
              manager.addHandler(ensureHandler(callback), true);
            }
            copy.callbacks = manager;
          } else {
            copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, {
              handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers),
              inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers),
              tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))),
              inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))),
              metadata: {
                ...baseCallbacks.metadata,
                ...providedCallbacks.metadata
              }
            });
          }
        }
      } else {
        const typedKey = key;
        copy[typedKey] = options[typedKey] ?? copy[typedKey];
      }
    }
  }
  return copy;
}
function ensureConfig(config) {
  const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig();
  let empty = {
    tags: [],
    metadata: {},
    recursionLimit: 25,
    runId: void 0
  };
  if (implicitConfig) {
    const { runId, runName, ...rest } = implicitConfig;
    empty = Object.entries(rest).reduce(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (currentConfig, [key, value]) => {
        if (value !== void 0) {
          currentConfig[key] = value;
        }
        return currentConfig;
      },
      empty
    );
  }
  if (config) {
    empty = Object.entries(config).reduce(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (currentConfig, [key, value]) => {
        if (value !== void 0) {
          currentConfig[key] = value;
        }
        return currentConfig;
      },
      empty
    );
  }
  if (empty?.configurable) {
    for (const key of Object.keys(empty.configurable)) {
      if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) {
        if (!empty.metadata) {
          empty.metadata = {};
        }
        empty.metadata[key] = empty.configurable[key];
      }
    }
  }
  if (empty.timeout !== void 0) {
    if (empty.timeout <= 0) {
      throw new Error("Timeout must be a positive number");
    }
    const timeoutSignal = AbortSignal.timeout(empty.timeout);
    if (empty.signal !== void 0) {
      if ("any" in AbortSignal) {
        empty.signal = AbortSignal.any([empty.signal, timeoutSignal]);
      }
    } else {
      empty.signal = timeoutSignal;
    }
    delete empty.timeout;
  }
  return empty;
}
function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) {
  const newConfig = ensureConfig(config);
  if (callbacks !== void 0) {
    delete newConfig.runName;
    newConfig.callbacks = callbacks;
  }
  if (recursionLimit !== void 0) {
    newConfig.recursionLimit = recursionLimit;
  }
  if (maxConcurrency !== void 0) {
    newConfig.maxConcurrency = maxConcurrency;
  }
  if (runName !== void 0) {
    newConfig.runName = runName;
  }
  if (configurable !== void 0) {
    newConfig.configurable = { ...newConfig.configurable, ...configurable };
  }
  if (runId !== void 0) {
    delete newConfig.runId;
  }
  return newConfig;
}
function pickRunnableConfigKeys(config) {
  return config ? {
    configurable: config.configurable,
    recursionLimit: config.recursionLimit,
    callbacks: config.callbacks,
    tags: config.tags,
    metadata: config.metadata,
    maxConcurrency: config.maxConcurrency,
    timeout: config.timeout,
    signal: config.signal
  } : void 0;
}
var DEFAULT_RECURSION_LIMIT, PRIMITIVES;
var init_config = __esm({
  "node_modules/@langchain/core/dist/runnables/config.js"() {
    init_manager();
    init_singletons();
    DEFAULT_RECURSION_LIMIT = 25;
    PRIMITIVES = /* @__PURE__ */ new Set(["string", "number", "boolean"]);
  }
});

// node_modules/@langchain/core/dist/utils/signal.js
async function raceWithSignal(promise, signal) {
  if (signal === void 0) {
    return promise;
  }
  let listener;
  return Promise.race([
    promise.catch((err) => {
      if (!signal?.aborted) {
        throw err;
      } else {
        return void 0;
      }
    }),
    new Promise((_2, reject) => {
      listener = () => {
        reject(new Error("Aborted"));
      };
      signal.addEventListener("abort", listener);
      if (signal.aborted) {
        reject(new Error("Aborted"));
      }
    })
  ]).finally(() => signal.removeEventListener("abort", listener));
}
var init_signal = __esm({
  "node_modules/@langchain/core/dist/utils/signal.js"() {
  }
});

// node_modules/@langchain/core/dist/utils/stream.js
function atee(iter, length = 2) {
  const buffers = Array.from({ length }, () => []);
  return buffers.map(async function* makeIter(buffer) {
    while (true) {
      if (buffer.length === 0) {
        const result = await iter.next();
        for (const buffer2 of buffers) {
          buffer2.push(result);
        }
      } else if (buffer[0].done) {
        return;
      } else {
        yield buffer.shift().value;
      }
    }
  });
}
function concat(first, second2) {
  if (Array.isArray(first) && Array.isArray(second2)) {
    return first.concat(second2);
  } else if (typeof first === "string" && typeof second2 === "string") {
    return first + second2;
  } else if (typeof first === "number" && typeof second2 === "number") {
    return first + second2;
  } else if (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "concat" in first && // eslint-disable-next-line @typescript-eslint/no-explicit-any
    typeof first.concat === "function"
  ) {
    return first.concat(second2);
  } else if (typeof first === "object" && typeof second2 === "object") {
    const chunk = { ...first };
    for (const [key, value] of Object.entries(second2)) {
      if (key in chunk && !Array.isArray(chunk[key])) {
        chunk[key] = concat(chunk[key], value);
      } else {
        chunk[key] = value;
      }
    }
    return chunk;
  } else {
    throw new Error(`Cannot concat ${typeof first} and ${typeof second2}`);
  }
}
async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) {
  const gen = new AsyncGeneratorWithSetup({
    generator,
    startSetup,
    signal
  });
  const setup = await gen.setup;
  return { output: to(gen, setup, ...args), setup };
}
var IterableReadableStream, AsyncGeneratorWithSetup;
var init_stream = __esm({
  "node_modules/@langchain/core/dist/utils/stream.js"() {
    init_config();
    init_singletons();
    init_signal();
    IterableReadableStream = class extends ReadableStream {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "reader", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
      }
      ensureReader() {
        if (!this.reader) {
          this.reader = this.getReader();
        }
      }
      async next() {
        this.ensureReader();
        try {
          const result = await this.reader.read();
          if (result.done) {
            this.reader.releaseLock();
            return {
              done: true,
              value: void 0
            };
          } else {
            return {
              done: false,
              value: result.value
            };
          }
        } catch (e3) {
          this.reader.releaseLock();
          throw e3;
        }
      }
      async return() {
        this.ensureReader();
        if (this.locked) {
          const cancelPromise2 = this.reader.cancel();
          this.reader.releaseLock();
          await cancelPromise2;
        }
        return { done: true, value: void 0 };
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async throw(e3) {
        this.ensureReader();
        if (this.locked) {
          const cancelPromise2 = this.reader.cancel();
          this.reader.releaseLock();
          await cancelPromise2;
        }
        throw e3;
      }
      [Symbol.asyncIterator]() {
        return this;
      }
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore Not present in Node 18 types, required in latest Node 22
      async [Symbol.asyncDispose]() {
        await this.return();
      }
      static fromReadableStream(stream) {
        const reader = stream.getReader();
        return new IterableReadableStream({
          start(controller) {
            return pump();
            function pump() {
              return reader.read().then(({ done, value }) => {
                if (done) {
                  controller.close();
                  return;
                }
                controller.enqueue(value);
                return pump();
              });
            }
          },
          cancel() {
            reader.releaseLock();
          }
        });
      }
      static fromAsyncGenerator(generator) {
        return new IterableReadableStream({
          async pull(controller) {
            const { value, done } = await generator.next();
            if (done) {
              controller.close();
            }
            controller.enqueue(value);
          },
          async cancel(reason) {
            await generator.return(reason);
          }
        });
      }
    };
    AsyncGeneratorWithSetup = class {
      constructor(params) {
        Object.defineProperty(this, "generator", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "setup", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "config", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "signal", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "firstResult", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "firstResultUsed", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        this.generator = params.generator;
        this.config = params.config;
        this.signal = params.signal ?? this.config?.signal;
        this.setup = new Promise((resolve, reject) => {
          void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(params.config), async () => {
            this.firstResult = params.generator.next();
            if (params.startSetup) {
              this.firstResult.then(params.startSetup).then(resolve, reject);
            } else {
              this.firstResult.then((_result) => resolve(void 0), reject);
            }
          }, true);
        });
      }
      async next(...args) {
        this.signal?.throwIfAborted();
        if (!this.firstResultUsed) {
          this.firstResultUsed = true;
          return this.firstResult;
        }
        return AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(this.config), this.signal ? async () => {
          return raceWithSignal(this.generator.next(...args), this.signal);
        } : async () => {
          return this.generator.next(...args);
        }, true);
      }
      async return(value) {
        return this.generator.return(value);
      }
      async throw(e3) {
        return this.generator.throw(e3);
      }
      [Symbol.asyncIterator]() {
        return this;
      }
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore Not present in Node 18 types, required in latest Node 22
      async [Symbol.asyncDispose]() {
        await this.return();
      }
    };
  }
});

// node_modules/@langchain/core/dist/tracers/log_stream.js
async function _getStandardizedInputs(run, schemaFormat) {
  if (schemaFormat === "original") {
    throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");
  }
  const { inputs } = run;
  if (["retriever", "llm", "prompt"].includes(run.run_type)) {
    return inputs;
  }
  if (Object.keys(inputs).length === 1 && inputs?.input === "") {
    return void 0;
  }
  return inputs.input;
}
async function _getStandardizedOutputs(run, schemaFormat) {
  const { outputs } = run;
  if (schemaFormat === "original") {
    return outputs;
  }
  if (["retriever", "llm", "prompt"].includes(run.run_type)) {
    return outputs;
  }
  if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) {
    return outputs.output;
  }
  return outputs;
}
function isChatGenerationChunk(x2) {
  return x2 !== void 0 && x2.message !== void 0;
}
var RunLogPatch, RunLog, isLogStreamHandler, LogStreamCallbackHandler;
var init_log_stream = __esm({
  "node_modules/@langchain/core/dist/tracers/log_stream.js"() {
    init_fast_json_patch();
    init_base2();
    init_stream();
    init_ai();
    RunLogPatch = class {
      constructor(fields) {
        Object.defineProperty(this, "ops", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.ops = fields.ops ?? [];
      }
      concat(other) {
        const ops = this.ops.concat(other.ops);
        const states = applyPatch({}, ops);
        return new RunLog({
          ops,
          state: states[states.length - 1].newDocument
        });
      }
    };
    RunLog = class extends RunLogPatch {
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "state", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.state = fields.state;
      }
      concat(other) {
        const ops = this.ops.concat(other.ops);
        const states = applyPatch(this.state, other.ops);
        return new RunLog({ ops, state: states[states.length - 1].newDocument });
      }
      static fromRunLogPatch(patch) {
        const states = applyPatch({}, patch.ops);
        return new RunLog({
          ops: patch.ops,
          state: states[states.length - 1].newDocument
        });
      }
    };
    isLogStreamHandler = (handler) => handler.name === "log_stream_tracer";
    LogStreamCallbackHandler = class extends BaseTracer {
      constructor(fields) {
        super({ _awaitHandler: true, ...fields });
        Object.defineProperty(this, "autoClose", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "includeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "_schemaFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "original"
        });
        Object.defineProperty(this, "rootId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "keyMapByRunId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "counterMapByRunName", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "transformStream", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "writer", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "receiveStream", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "log_stream_tracer"
        });
        Object.defineProperty(this, "lc_prefer_streaming", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        this.autoClose = fields?.autoClose ?? true;
        this.includeNames = fields?.includeNames;
        this.includeTypes = fields?.includeTypes;
        this.includeTags = fields?.includeTags;
        this.excludeNames = fields?.excludeNames;
        this.excludeTypes = fields?.excludeTypes;
        this.excludeTags = fields?.excludeTags;
        this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;
        this.transformStream = new TransformStream();
        this.writer = this.transformStream.writable.getWriter();
        this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
      }
      [Symbol.asyncIterator]() {
        return this.receiveStream;
      }
      async persistRun(_run) {
      }
      _includeRun(run) {
        if (run.id === this.rootId) {
          return false;
        }
        const runTags = run.tags ?? [];
        let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0;
        if (this.includeNames !== void 0) {
          include = include || this.includeNames.includes(run.name);
        }
        if (this.includeTypes !== void 0) {
          include = include || this.includeTypes.includes(run.run_type);
        }
        if (this.includeTags !== void 0) {
          include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0;
        }
        if (this.excludeNames !== void 0) {
          include = include && !this.excludeNames.includes(run.name);
        }
        if (this.excludeTypes !== void 0) {
          include = include && !this.excludeTypes.includes(run.run_type);
        }
        if (this.excludeTags !== void 0) {
          include = include && runTags.every((tag) => !this.excludeTags?.includes(tag));
        }
        return include;
      }
      async *tapOutputIterable(runId, output) {
        for await (const chunk of output) {
          if (runId !== this.rootId) {
            const key = this.keyMapByRunId[runId];
            if (key) {
              await this.writer.write(new RunLogPatch({
                ops: [
                  {
                    op: "add",
                    path: `/logs/${key}/streamed_output/-`,
                    value: chunk
                  }
                ]
              }));
            }
          }
          yield chunk;
        }
      }
      async onRunCreate(run) {
        if (this.rootId === void 0) {
          this.rootId = run.id;
          await this.writer.write(new RunLogPatch({
            ops: [
              {
                op: "replace",
                path: "",
                value: {
                  id: run.id,
                  name: run.name,
                  type: run.run_type,
                  streamed_output: [],
                  final_output: void 0,
                  logs: {}
                }
              }
            ]
          }));
        }
        if (!this._includeRun(run)) {
          return;
        }
        if (this.counterMapByRunName[run.name] === void 0) {
          this.counterMapByRunName[run.name] = 0;
        }
        this.counterMapByRunName[run.name] += 1;
        const count5 = this.counterMapByRunName[run.name];
        this.keyMapByRunId[run.id] = count5 === 1 ? run.name : `${run.name}:${count5}`;
        const logEntry = {
          id: run.id,
          name: run.name,
          type: run.run_type,
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {},
          start_time: new Date(run.start_time).toISOString(),
          streamed_output: [],
          streamed_output_str: [],
          final_output: void 0,
          end_time: void 0
        };
        if (this._schemaFormat === "streaming_events") {
          logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);
        }
        await this.writer.write(new RunLogPatch({
          ops: [
            {
              op: "add",
              path: `/logs/${this.keyMapByRunId[run.id]}`,
              value: logEntry
            }
          ]
        }));
      }
      async onRunUpdate(run) {
        try {
          const runName = this.keyMapByRunId[run.id];
          if (runName === void 0) {
            return;
          }
          const ops = [];
          if (this._schemaFormat === "streaming_events") {
            ops.push({
              op: "replace",
              path: `/logs/${runName}/inputs`,
              value: await _getStandardizedInputs(run, this._schemaFormat)
            });
          }
          ops.push({
            op: "add",
            path: `/logs/${runName}/final_output`,
            value: await _getStandardizedOutputs(run, this._schemaFormat)
          });
          if (run.end_time !== void 0) {
            ops.push({
              op: "add",
              path: `/logs/${runName}/end_time`,
              value: new Date(run.end_time).toISOString()
            });
          }
          const patch = new RunLogPatch({ ops });
          await this.writer.write(patch);
        } finally {
          if (run.id === this.rootId) {
            const patch = new RunLogPatch({
              ops: [
                {
                  op: "replace",
                  path: "/final_output",
                  value: await _getStandardizedOutputs(run, this._schemaFormat)
                }
              ]
            });
            await this.writer.write(patch);
            if (this.autoClose) {
              await this.writer.close();
            }
          }
        }
      }
      async onLLMNewToken(run, token, kwargs) {
        const runName = this.keyMapByRunId[run.id];
        if (runName === void 0) {
          return;
        }
        const isChatModel = run.inputs.messages !== void 0;
        let streamedOutputValue;
        if (isChatModel) {
          if (isChatGenerationChunk(kwargs?.chunk)) {
            streamedOutputValue = kwargs?.chunk;
          } else {
            streamedOutputValue = new AIMessageChunk({
              id: `run-${run.id}`,
              content: token
            });
          }
        } else {
          streamedOutputValue = token;
        }
        const patch = new RunLogPatch({
          ops: [
            {
              op: "add",
              path: `/logs/${runName}/streamed_output_str/-`,
              value: token
            },
            {
              op: "add",
              path: `/logs/${runName}/streamed_output/-`,
              value: streamedOutputValue
            }
          ]
        });
        await this.writer.write(patch);
      }
    };
  }
});

// node_modules/@langchain/core/dist/outputs.js
var RUN_KEY, GenerationChunk, ChatGenerationChunk;
var init_outputs = __esm({
  "node_modules/@langchain/core/dist/outputs.js"() {
    RUN_KEY = "__run";
    GenerationChunk = class {
      constructor(fields) {
        Object.defineProperty(this, "text", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "generationInfo", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.text = fields.text;
        this.generationInfo = fields.generationInfo;
      }
      concat(chunk) {
        return new GenerationChunk({
          text: this.text + chunk.text,
          generationInfo: {
            ...this.generationInfo,
            ...chunk.generationInfo
          }
        });
      }
    };
    ChatGenerationChunk = class extends GenerationChunk {
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "message", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.message = fields.message;
      }
      concat(chunk) {
        return new ChatGenerationChunk({
          text: this.text + chunk.text,
          generationInfo: {
            ...this.generationInfo,
            ...chunk.generationInfo
          },
          message: this.message.concat(chunk.message)
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/tracers/event_stream.js
function assignName({ name, serialized }) {
  if (name !== void 0) {
    return name;
  }
  if (serialized?.name !== void 0) {
    return serialized.name;
  } else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) {
    return serialized.id[serialized.id.length - 1];
  }
  return "Unnamed";
}
var isStreamEventsHandler, EventStreamCallbackHandler;
var init_event_stream = __esm({
  "node_modules/@langchain/core/dist/tracers/event_stream.js"() {
    init_base2();
    init_stream();
    init_ai();
    init_outputs();
    isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer";
    EventStreamCallbackHandler = class extends BaseTracer {
      constructor(fields) {
        super({ _awaitHandler: true, ...fields });
        Object.defineProperty(this, "autoClose", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "includeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "runInfoMap", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: /* @__PURE__ */ new Map()
        });
        Object.defineProperty(this, "tappedPromises", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: /* @__PURE__ */ new Map()
        });
        Object.defineProperty(this, "transformStream", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "writer", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "receiveStream", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "event_stream_tracer"
        });
        Object.defineProperty(this, "lc_prefer_streaming", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        this.autoClose = fields?.autoClose ?? true;
        this.includeNames = fields?.includeNames;
        this.includeTypes = fields?.includeTypes;
        this.includeTags = fields?.includeTags;
        this.excludeNames = fields?.excludeNames;
        this.excludeTypes = fields?.excludeTypes;
        this.excludeTags = fields?.excludeTags;
        this.transformStream = new TransformStream();
        this.writer = this.transformStream.writable.getWriter();
        this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
      }
      [Symbol.asyncIterator]() {
        return this.receiveStream;
      }
      async persistRun(_run) {
      }
      _includeRun(run) {
        const runTags = run.tags ?? [];
        let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0;
        if (this.includeNames !== void 0) {
          include = include || this.includeNames.includes(run.name);
        }
        if (this.includeTypes !== void 0) {
          include = include || this.includeTypes.includes(run.runType);
        }
        if (this.includeTags !== void 0) {
          include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0;
        }
        if (this.excludeNames !== void 0) {
          include = include && !this.excludeNames.includes(run.name);
        }
        if (this.excludeTypes !== void 0) {
          include = include && !this.excludeTypes.includes(run.runType);
        }
        if (this.excludeTags !== void 0) {
          include = include && runTags.every((tag) => !this.excludeTags?.includes(tag));
        }
        return include;
      }
      async *tapOutputIterable(runId, outputStream) {
        const firstChunk = await outputStream.next();
        if (firstChunk.done) {
          return;
        }
        const runInfo = this.runInfoMap.get(runId);
        if (runInfo === void 0) {
          yield firstChunk.value;
          return;
        }
        function _formatOutputChunk(eventType, data) {
          if (eventType === "llm" && typeof data === "string") {
            return new GenerationChunk({ text: data });
          }
          return data;
        }
        let tappedPromise = this.tappedPromises.get(runId);
        if (tappedPromise === void 0) {
          let tappedPromiseResolver;
          tappedPromise = new Promise((resolve) => {
            tappedPromiseResolver = resolve;
          });
          this.tappedPromises.set(runId, tappedPromise);
          try {
            const event = {
              event: `on_${runInfo.runType}_stream`,
              run_id: runId,
              name: runInfo.name,
              tags: runInfo.tags,
              metadata: runInfo.metadata,
              data: {}
            };
            await this.send({
              ...event,
              data: {
                chunk: _formatOutputChunk(runInfo.runType, firstChunk.value)
              }
            }, runInfo);
            yield firstChunk.value;
            for await (const chunk of outputStream) {
              if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") {
                await this.send({
                  ...event,
                  data: {
                    chunk: _formatOutputChunk(runInfo.runType, chunk)
                  }
                }, runInfo);
              }
              yield chunk;
            }
          } finally {
            tappedPromiseResolver();
          }
        } else {
          yield firstChunk.value;
          for await (const chunk of outputStream) {
            yield chunk;
          }
        }
      }
      async send(payload, run) {
        if (this._includeRun(run)) {
          await this.writer.write(payload);
        }
      }
      async sendEndEvent(payload, run) {
        const tappedPromise = this.tappedPromises.get(payload.run_id);
        if (tappedPromise !== void 0) {
          void tappedPromise.then(() => {
            void this.send(payload, run);
          });
        } else {
          await this.send(payload, run);
        }
      }
      async onLLMStart(run) {
        const runName = assignName(run);
        const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm";
        const runInfo = {
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {},
          name: runName,
          runType,
          inputs: run.inputs
        };
        this.runInfoMap.set(run.id, runInfo);
        const eventName = `on_${runType}_start`;
        await this.send({
          event: eventName,
          data: {
            input: run.inputs
          },
          name: runName,
          tags: run.tags ?? [],
          run_id: run.id,
          metadata: run.extra?.metadata ?? {}
        }, runInfo);
      }
      async onLLMNewToken(run, token, kwargs) {
        const runInfo = this.runInfoMap.get(run.id);
        let chunk;
        let eventName;
        if (runInfo === void 0) {
          throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);
        }
        if (this.runInfoMap.size === 1) {
          return;
        }
        if (runInfo.runType === "chat_model") {
          eventName = "on_chat_model_stream";
          if (kwargs?.chunk === void 0) {
            chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });
          } else {
            chunk = kwargs.chunk.message;
          }
        } else if (runInfo.runType === "llm") {
          eventName = "on_llm_stream";
          if (kwargs?.chunk === void 0) {
            chunk = new GenerationChunk({ text: token });
          } else {
            chunk = kwargs.chunk;
          }
        } else {
          throw new Error(`Unexpected run type ${runInfo.runType}`);
        }
        await this.send({
          event: eventName,
          data: {
            chunk
          },
          run_id: run.id,
          name: runInfo.name,
          tags: runInfo.tags,
          metadata: runInfo.metadata
        }, runInfo);
      }
      async onLLMEnd(run) {
        const runInfo = this.runInfoMap.get(run.id);
        this.runInfoMap.delete(run.id);
        let eventName;
        if (runInfo === void 0) {
          throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);
        }
        const generations = run.outputs?.generations;
        let output;
        if (runInfo.runType === "chat_model") {
          for (const generation of generations ?? []) {
            if (output !== void 0) {
              break;
            }
            output = generation[0]?.message;
          }
          eventName = "on_chat_model_end";
        } else if (runInfo.runType === "llm") {
          output = {
            generations: generations?.map((generation) => {
              return generation.map((chunk) => {
                return {
                  text: chunk.text,
                  generationInfo: chunk.generationInfo
                };
              });
            }),
            llmOutput: run.outputs?.llmOutput ?? {}
          };
          eventName = "on_llm_end";
        } else {
          throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);
        }
        await this.sendEndEvent({
          event: eventName,
          data: {
            output,
            input: runInfo.inputs
          },
          run_id: run.id,
          name: runInfo.name,
          tags: runInfo.tags,
          metadata: runInfo.metadata
        }, runInfo);
      }
      async onChainStart(run) {
        const runName = assignName(run);
        const runType = run.run_type ?? "chain";
        const runInfo = {
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {},
          name: runName,
          runType: run.run_type
        };
        let eventData = {};
        if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) {
          eventData = {};
          runInfo.inputs = {};
        } else if (run.inputs.input !== void 0) {
          eventData.input = run.inputs.input;
          runInfo.inputs = run.inputs.input;
        } else {
          eventData.input = run.inputs;
          runInfo.inputs = run.inputs;
        }
        this.runInfoMap.set(run.id, runInfo);
        await this.send({
          event: `on_${runType}_start`,
          data: eventData,
          name: runName,
          tags: run.tags ?? [],
          run_id: run.id,
          metadata: run.extra?.metadata ?? {}
        }, runInfo);
      }
      async onChainEnd(run) {
        const runInfo = this.runInfoMap.get(run.id);
        this.runInfoMap.delete(run.id);
        if (runInfo === void 0) {
          throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);
        }
        const eventName = `on_${run.run_type}_end`;
        const inputs = run.inputs ?? runInfo.inputs ?? {};
        const outputs = run.outputs?.output ?? run.outputs;
        const data = {
          output: outputs,
          input: inputs
        };
        if (inputs.input && Object.keys(inputs).length === 1) {
          data.input = inputs.input;
          runInfo.inputs = inputs.input;
        }
        await this.sendEndEvent({
          event: eventName,
          data,
          run_id: run.id,
          name: runInfo.name,
          tags: runInfo.tags,
          metadata: runInfo.metadata ?? {}
        }, runInfo);
      }
      async onToolStart(run) {
        const runName = assignName(run);
        const runInfo = {
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {},
          name: runName,
          runType: "tool",
          inputs: run.inputs ?? {}
        };
        this.runInfoMap.set(run.id, runInfo);
        await this.send({
          event: "on_tool_start",
          data: {
            input: run.inputs ?? {}
          },
          name: runName,
          run_id: run.id,
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {}
        }, runInfo);
      }
      async onToolEnd(run) {
        const runInfo = this.runInfoMap.get(run.id);
        this.runInfoMap.delete(run.id);
        if (runInfo === void 0) {
          throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);
        }
        if (runInfo.inputs === void 0) {
          throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`);
        }
        const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output;
        await this.sendEndEvent({
          event: "on_tool_end",
          data: {
            output,
            input: runInfo.inputs
          },
          run_id: run.id,
          name: runInfo.name,
          tags: runInfo.tags,
          metadata: runInfo.metadata
        }, runInfo);
      }
      async onRetrieverStart(run) {
        const runName = assignName(run);
        const runType = "retriever";
        const runInfo = {
          tags: run.tags ?? [],
          metadata: run.extra?.metadata ?? {},
          name: runName,
          runType,
          inputs: {
            query: run.inputs.query
          }
        };
        this.runInfoMap.set(run.id, runInfo);
        await this.send({
          event: "on_retriever_start",
          data: {
            input: {
              query: run.inputs.query
            }
          },
          name: runName,
          tags: run.tags ?? [],
          run_id: run.id,
          metadata: run.extra?.metadata ?? {}
        }, runInfo);
      }
      async onRetrieverEnd(run) {
        const runInfo = this.runInfoMap.get(run.id);
        this.runInfoMap.delete(run.id);
        if (runInfo === void 0) {
          throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);
        }
        await this.sendEndEvent({
          event: "on_retriever_end",
          data: {
            output: run.outputs?.documents ?? run.outputs,
            input: runInfo.inputs
          },
          run_id: run.id,
          name: runInfo.name,
          tags: runInfo.tags,
          metadata: runInfo.metadata
        }, runInfo);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      async handleCustomEvent(eventName, data, runId) {
        const runInfo = this.runInfoMap.get(runId);
        if (runInfo === void 0) {
          throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);
        }
        await this.send({
          event: "on_custom_event",
          run_id: runId,
          name: eventName,
          tags: runInfo.tags,
          metadata: runInfo.metadata,
          data
        }, runInfo);
      }
      async finish() {
        const pendingPromises = [...this.tappedPromises.values()];
        void Promise.all(pendingPromises).finally(() => {
          void this.writer.close();
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/async_caller.js
var import_p_retry2, import_p_queue3, STATUS_NO_RETRY2, defaultFailedAttemptHandler, AsyncCaller2;
var init_async_caller2 = __esm({
  "node_modules/@langchain/core/dist/utils/async_caller.js"() {
    import_p_retry2 = __toESM(require_p_retry(), 1);
    import_p_queue3 = __toESM(require_dist(), 1);
    STATUS_NO_RETRY2 = [
      400,
      401,
      402,
      403,
      404,
      405,
      406,
      407,
      409
      // Conflict
    ];
    defaultFailedAttemptHandler = (error) => {
      if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") {
        throw error;
      }
      if (error?.code === "ECONNABORTED") {
        throw error;
      }
      const status = (
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        error?.response?.status ?? error?.status
      );
      if (status && STATUS_NO_RETRY2.includes(+status)) {
        throw error;
      }
      if (error?.error?.code === "insufficient_quota") {
        const err = new Error(error?.message);
        err.name = "InsufficientQuotaError";
        throw err;
      }
    };
    AsyncCaller2 = class {
      constructor(params) {
        Object.defineProperty(this, "maxConcurrency", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "maxRetries", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "onFailedAttempt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "queue", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.maxConcurrency = params.maxConcurrency ?? Infinity;
        this.maxRetries = params.maxRetries ?? 6;
        this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler;
        const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default;
        this.queue = new PQueue({ concurrency: this.maxConcurrency });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      call(callable, ...args) {
        return this.queue.add(() => (0, import_p_retry2.default)(() => callable(...args).catch((error) => {
          if (error instanceof Error) {
            throw error;
          } else {
            throw new Error(error);
          }
        }), {
          onFailedAttempt: this.onFailedAttempt,
          retries: this.maxRetries,
          randomize: true
          // If needed we can change some of the defaults here,
          // but they're quite sensible.
        }), { throwOnTimeout: true });
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      callWithOptions(options, callable, ...args) {
        if (options.signal) {
          return Promise.race([
            this.call(callable, ...args),
            new Promise((_2, reject) => {
              options.signal?.addEventListener("abort", () => {
                reject(new Error("AbortError"));
              });
            })
          ]);
        }
        return this.call(callable, ...args);
      }
      fetch(...args) {
        return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res)));
      }
    };
  }
});

// node_modules/@langchain/core/dist/tracers/root_listener.js
var RootListenersTracer;
var init_root_listener = __esm({
  "node_modules/@langchain/core/dist/tracers/root_listener.js"() {
    init_base2();
    RootListenersTracer = class extends BaseTracer {
      constructor({ config, onStart, onEnd, onError }) {
        super({ _awaitHandler: true });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "RootListenersTracer"
        });
        Object.defineProperty(this, "rootId", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "config", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "argOnStart", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "argOnEnd", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "argOnError", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.config = config;
        this.argOnStart = onStart;
        this.argOnEnd = onEnd;
        this.argOnError = onError;
      }
      /**
       * This is a legacy method only called once for an entire run tree
       * therefore not useful here
       * @param {Run} _ Not used
       */
      persistRun(_2) {
        return Promise.resolve();
      }
      async onRunCreate(run) {
        if (this.rootId) {
          return;
        }
        this.rootId = run.id;
        if (this.argOnStart) {
          await this.argOnStart(run, this.config);
        }
      }
      async onRunUpdate(run) {
        if (run.id !== this.rootId) {
          return;
        }
        if (!run.error) {
          if (this.argOnEnd) {
            await this.argOnEnd(run, this.config);
          }
        } else if (this.argOnError) {
          await this.argOnError(run, this.config);
        }
      }
    };
  }
});

// node_modules/@langchain/core/dist/runnables/utils.js
function isRunnableInterface(thing) {
  return thing ? thing.lc_runnable : false;
}
var _RootEventFilter;
var init_utils3 = __esm({
  "node_modules/@langchain/core/dist/runnables/utils.js"() {
    _RootEventFilter = class {
      constructor(fields) {
        Object.defineProperty(this, "includeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "includeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeNames", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTypes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "excludeTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.includeNames = fields.includeNames;
        this.includeTypes = fields.includeTypes;
        this.includeTags = fields.includeTags;
        this.excludeNames = fields.excludeNames;
        this.excludeTypes = fields.excludeTypes;
        this.excludeTags = fields.excludeTags;
      }
      includeEvent(event, rootType) {
        let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0;
        const eventTags = event.tags ?? [];
        if (this.includeNames !== void 0) {
          include = include || this.includeNames.includes(event.name);
        }
        if (this.includeTypes !== void 0) {
          include = include || this.includeTypes.includes(rootType);
        }
        if (this.includeTags !== void 0) {
          include = include || eventTags.some((tag) => this.includeTags?.includes(tag));
        }
        if (this.excludeNames !== void 0) {
          include = include && !this.excludeNames.includes(event.name);
        }
        if (this.excludeTypes !== void 0) {
          include = include && !this.excludeTypes.includes(rootType);
        }
        if (this.excludeTags !== void 0) {
          include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag));
        }
        return include;
      }
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/Options.js
var ignoreOverride, defaultOptions2, getDefaultOptions;
var init_Options = __esm({
  "node_modules/zod-to-json-schema/dist/esm/Options.js"() {
    ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
    defaultOptions2 = {
      name: void 0,
      $refStrategy: "root",
      basePath: ["#"],
      effectStrategy: "input",
      pipeStrategy: "all",
      dateStrategy: "format:date-time",
      mapStrategy: "entries",
      removeAdditionalStrategy: "passthrough",
      definitionPath: "definitions",
      target: "jsonSchema7",
      strictUnions: false,
      definitions: {},
      errorMessages: false,
      markdownDescription: false,
      patternStrategy: "escape",
      applyRegexFlags: false,
      emailStrategy: "format:email",
      base64Strategy: "contentEncoding:base64",
      nameStrategy: "ref"
    };
    getDefaultOptions = (options) => typeof options === "string" ? {
      ...defaultOptions2,
      name: options
    } : {
      ...defaultOptions2,
      ...options
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/Refs.js
var getRefs;
var init_Refs = __esm({
  "node_modules/zod-to-json-schema/dist/esm/Refs.js"() {
    init_Options();
    getRefs = (options) => {
      const _options = getDefaultOptions(options);
      const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
      return {
        ..._options,
        currentPath,
        propertyPath: void 0,
        seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
          def._def,
          {
            def: def._def,
            path: [..._options.basePath, _options.definitionPath, name],
            // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
            jsonSchema: void 0
          }
        ]))
      };
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/errorMessages.js
function addErrorMessage(res, key, errorMessage, refs) {
  if (!refs?.errorMessages)
    return;
  if (errorMessage) {
    res.errorMessage = {
      ...res.errorMessage,
      [key]: errorMessage
    };
  }
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
  res[key] = value;
  addErrorMessage(res, key, errorMessage, refs);
}
var init_errorMessages = __esm({
  "node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/any.js
function parseAnyDef() {
  return {};
}
var init_any = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/array.js
function parseArrayDef(def, refs) {
  const res = {
    type: "array"
  };
  if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
    res.items = parseDef(def.type._def, {
      ...refs,
      currentPath: [...refs.currentPath, "items"]
    });
  }
  if (def.minLength) {
    setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
  }
  if (def.maxLength) {
    setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
  }
  if (def.exactLength) {
    setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
    setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
  }
  return res;
}
var init_array = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() {
    init_lib();
    init_errorMessages();
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
function parseBigintDef(def, refs) {
  const res = {
    type: "integer",
    format: "int64"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}
var init_bigint = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() {
    init_errorMessages();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
function parseBooleanDef() {
  return {
    type: "boolean"
  };
}
var init_boolean = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
function parseBrandedDef(_def, refs) {
  return parseDef(_def.type._def, refs);
}
var init_branded = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() {
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
var parseCatchDef;
var init_catch = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() {
    init_parseDef();
    parseCatchDef = (def, refs) => {
      return parseDef(def.innerType._def, refs);
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/date.js
function parseDateDef(def, refs, overrideDateStrategy) {
  const strategy = overrideDateStrategy ?? refs.dateStrategy;
  if (Array.isArray(strategy)) {
    return {
      anyOf: strategy.map((item, i3) => parseDateDef(def, refs, item))
    };
  }
  switch (strategy) {
    case "string":
    case "format:date-time":
      return {
        type: "string",
        format: "date-time"
      };
    case "format:date":
      return {
        type: "string",
        format: "date"
      };
    case "integer":
      return integerDateParser(def, refs);
  }
}
var integerDateParser;
var init_date = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() {
    init_errorMessages();
    integerDateParser = (def, refs) => {
      const res = {
        type: "integer",
        format: "unix-time"
      };
      if (refs.target === "openApi3") {
        return res;
      }
      for (const check of def.checks) {
        switch (check.kind) {
          case "min":
            setResponseValueAndErrors(
              res,
              "minimum",
              check.value,
              // This is in milliseconds
              check.message,
              refs
            );
            break;
          case "max":
            setResponseValueAndErrors(
              res,
              "maximum",
              check.value,
              // This is in milliseconds
              check.message,
              refs
            );
            break;
        }
      }
      return res;
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/default.js
function parseDefaultDef(_def, refs) {
  return {
    ...parseDef(_def.innerType._def, refs),
    default: _def.defaultValue()
  };
}
var init_default = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() {
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
function parseEffectsDef(_def, refs) {
  return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
}
var init_effects = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() {
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
function parseEnumDef(def) {
  return {
    type: "string",
    enum: Array.from(def.values)
  };
}
var init_enum = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
function parseIntersectionDef(def, refs) {
  const allOf = [
    parseDef(def.left._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "0"]
    }),
    parseDef(def.right._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "1"]
    })
  ].filter((x2) => !!x2);
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
  const mergedAllOf = [];
  allOf.forEach((schema) => {
    if (isJsonSchema7AllOfType(schema)) {
      mergedAllOf.push(...schema.allOf);
      if (schema.unevaluatedProperties === void 0) {
        unevaluatedProperties = void 0;
      }
    } else {
      let nestedSchema = schema;
      if ("additionalProperties" in schema && schema.additionalProperties === false) {
        const { additionalProperties, ...rest } = schema;
        nestedSchema = rest;
      } else {
        unevaluatedProperties = void 0;
      }
      mergedAllOf.push(nestedSchema);
    }
  });
  return mergedAllOf.length ? {
    allOf: mergedAllOf,
    ...unevaluatedProperties
  } : void 0;
}
var isJsonSchema7AllOfType;
var init_intersection = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() {
    init_parseDef();
    isJsonSchema7AllOfType = (type) => {
      if ("type" in type && type.type === "string")
        return false;
      return "allOf" in type;
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
function parseLiteralDef(def, refs) {
  const parsedType = typeof def.value;
  if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
    return {
      type: Array.isArray(def.value) ? "array" : "object"
    };
  }
  if (refs.target === "openApi3") {
    return {
      type: parsedType === "bigint" ? "integer" : parsedType,
      enum: [def.value]
    };
  }
  return {
    type: parsedType === "bigint" ? "integer" : parsedType,
    const: def.value
  };
}
var init_literal = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
function parseStringDef(def, refs) {
  const res = {
    type: "string"
  };
  if (def.checks) {
    for (const check of def.checks) {
      switch (check.kind) {
        case "min":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          break;
        case "max":
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "email":
          switch (refs.emailStrategy) {
            case "format:email":
              addFormat(res, "email", check.message, refs);
              break;
            case "format:idn-email":
              addFormat(res, "idn-email", check.message, refs);
              break;
            case "pattern:zod":
              addPattern(res, zodPatterns.email, check.message, refs);
              break;
          }
          break;
        case "url":
          addFormat(res, "uri", check.message, refs);
          break;
        case "uuid":
          addFormat(res, "uuid", check.message, refs);
          break;
        case "regex":
          addPattern(res, check.regex, check.message, refs);
          break;
        case "cuid":
          addPattern(res, zodPatterns.cuid, check.message, refs);
          break;
        case "cuid2":
          addPattern(res, zodPatterns.cuid2, check.message, refs);
          break;
        case "startsWith":
          addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
          break;
        case "endsWith":
          addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
          break;
        case "datetime":
          addFormat(res, "date-time", check.message, refs);
          break;
        case "date":
          addFormat(res, "date", check.message, refs);
          break;
        case "time":
          addFormat(res, "time", check.message, refs);
          break;
        case "duration":
          addFormat(res, "duration", check.message, refs);
          break;
        case "length":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "includes": {
          addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
          break;
        }
        case "ip": {
          if (check.version !== "v6") {
            addFormat(res, "ipv4", check.message, refs);
          }
          if (check.version !== "v4") {
            addFormat(res, "ipv6", check.message, refs);
          }
          break;
        }
        case "base64url":
          addPattern(res, zodPatterns.base64url, check.message, refs);
          break;
        case "jwt":
          addPattern(res, zodPatterns.jwt, check.message, refs);
          break;
        case "cidr": {
          if (check.version !== "v6") {
            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
          }
          if (check.version !== "v4") {
            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
          }
          break;
        }
        case "emoji":
          addPattern(res, zodPatterns.emoji(), check.message, refs);
          break;
        case "ulid": {
          addPattern(res, zodPatterns.ulid, check.message, refs);
          break;
        }
        case "base64": {
          switch (refs.base64Strategy) {
            case "format:binary": {
              addFormat(res, "binary", check.message, refs);
              break;
            }
            case "contentEncoding:base64": {
              setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
              break;
            }
            case "pattern:zod": {
              addPattern(res, zodPatterns.base64, check.message, refs);
              break;
            }
          }
          break;
        }
        case "nanoid": {
          addPattern(res, zodPatterns.nanoid, check.message, refs);
        }
        case "toLowerCase":
        case "toUpperCase":
        case "trim":
          break;
        default:
          ((_2) => {
          })(check);
      }
    }
  }
  return res;
}
function escapeLiteralCheckValue(literal, refs) {
  return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
}
function escapeNonAlphaNumeric(source) {
  let result = "";
  for (let i3 = 0; i3 < source.length; i3++) {
    if (!ALPHA_NUMERIC.has(source[i3])) {
      result += "\\";
    }
    result += source[i3];
  }
  return result;
}
function addFormat(schema, value, message, refs) {
  if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
    if (!schema.anyOf) {
      schema.anyOf = [];
    }
    if (schema.format) {
      schema.anyOf.push({
        format: schema.format,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { format: schema.errorMessage.format }
        }
      });
      delete schema.format;
      if (schema.errorMessage) {
        delete schema.errorMessage.format;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.anyOf.push({
      format: value,
      ...message && refs.errorMessages && { errorMessage: { format: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "format", value, message, refs);
  }
}
function addPattern(schema, regex2, message, refs) {
  if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
    if (!schema.allOf) {
      schema.allOf = [];
    }
    if (schema.pattern) {
      schema.allOf.push({
        pattern: schema.pattern,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { pattern: schema.errorMessage.pattern }
        }
      });
      delete schema.pattern;
      if (schema.errorMessage) {
        delete schema.errorMessage.pattern;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.allOf.push({
      pattern: stringifyRegExpWithFlags(regex2, refs),
      ...message && refs.errorMessages && { errorMessage: { pattern: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex2, refs), message, refs);
  }
}
function stringifyRegExpWithFlags(regex2, refs) {
  if (!refs.applyRegexFlags || !regex2.flags) {
    return regex2.source;
  }
  const flags = {
    i: regex2.flags.includes("i"),
    m: regex2.flags.includes("m"),
    s: regex2.flags.includes("s")
    // `.` matches newlines
  };
  const source = flags.i ? regex2.source.toLowerCase() : regex2.source;
  let pattern = "";
  let isEscaped = false;
  let inCharGroup = false;
  let inCharRange = false;
  for (let i3 = 0; i3 < source.length; i3++) {
    if (isEscaped) {
      pattern += source[i3];
      isEscaped = false;
      continue;
    }
    if (flags.i) {
      if (inCharGroup) {
        if (source[i3].match(/[a-z]/)) {
          if (inCharRange) {
            pattern += source[i3];
            pattern += `${source[i3 - 2]}-${source[i3]}`.toUpperCase();
            inCharRange = false;
          } else if (source[i3 + 1] === "-" && source[i3 + 2]?.match(/[a-z]/)) {
            pattern += source[i3];
            inCharRange = true;
          } else {
            pattern += `${source[i3]}${source[i3].toUpperCase()}`;
          }
          continue;
        }
      } else if (source[i3].match(/[a-z]/)) {
        pattern += `[${source[i3]}${source[i3].toUpperCase()}]`;
        continue;
      }
    }
    if (flags.m) {
      if (source[i3] === "^") {
        pattern += `(^|(?<=[\r
]))`;
        continue;
      } else if (source[i3] === "$") {
        pattern += `($|(?=[\r
]))`;
        continue;
      }
    }
    if (flags.s && source[i3] === ".") {
      pattern += inCharGroup ? `${source[i3]}\r
` : `[${source[i3]}\r
]`;
      continue;
    }
    pattern += source[i3];
    if (source[i3] === "\\") {
      isEscaped = true;
    } else if (inCharGroup && source[i3] === "]") {
      inCharGroup = false;
    } else if (!inCharGroup && source[i3] === "[") {
      inCharGroup = true;
    }
  }
  try {
    new RegExp(pattern);
  } catch {
    console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
    return regex2.source;
  }
  return pattern;
}
var emojiRegex2, zodPatterns, ALPHA_NUMERIC;
var init_string = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() {
    init_errorMessages();
    emojiRegex2 = void 0;
    zodPatterns = {
      /**
       * `c` was changed to `[cC]` to replicate /i flag
       */
      cuid: /^[cC][^\s-]{8,}$/,
      cuid2: /^[0-9a-z]+$/,
      ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
      /**
       * `a-z` was added to replicate /i flag
       */
      email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
      /**
       * Constructed a valid Unicode RegExp
       *
       * Lazily instantiate since this type of regex isn't supported
       * in all envs (e.g. React Native).
       *
       * See:
       * https://github.com/colinhacks/zod/issues/2433
       * Fix in Zod:
       * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
       */
      emoji: () => {
        if (emojiRegex2 === void 0) {
          emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
        }
        return emojiRegex2;
      },
      /**
       * Unused
       */
      uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
      /**
       * Unused
       */
      ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
      ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
      /**
       * Unused
       */
      ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
      ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
      base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
      base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
      nanoid: /^[a-zA-Z0-9_-]{21}$/,
      jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
    };
    ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(def, refs) {
  if (refs.target === "openAi") {
    console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
  }
  if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      type: "object",
      required: def.keyType._def.values,
      properties: def.keyType._def.values.reduce((acc, key) => ({
        ...acc,
        [key]: parseDef(def.valueType._def, {
          ...refs,
          currentPath: [...refs.currentPath, "properties", key]
        }) ?? {}
      }), {}),
      additionalProperties: false
    };
  }
  const schema = {
    type: "object",
    additionalProperties: parseDef(def.valueType._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? {}
  };
  if (refs.target === "openApi3") {
    return schema;
  }
  if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      ...schema,
      propertyNames: {
        enum: def.keyType._def.values
      }
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
    const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  }
  return schema;
}
var init_record = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() {
    init_lib();
    init_parseDef();
    init_string();
    init_branded();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/map.js
function parseMapDef(def, refs) {
  if (refs.mapStrategy === "record") {
    return parseRecordDef(def, refs);
  }
  const keys = parseDef(def.keyType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "0"]
  }) || {};
  const values = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "1"]
  }) || {};
  return {
    type: "array",
    maxItems: 125,
    items: {
      type: "array",
      items: [keys, values],
      minItems: 2,
      maxItems: 2
    }
  };
}
var init_map = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() {
    init_parseDef();
    init_record();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
function parseNativeEnumDef(def) {
  const object = def.values;
  const actualKeys = Object.keys(def.values).filter((key) => {
    return typeof object[object[key]] !== "number";
  });
  const actualValues = actualKeys.map((key) => object[key]);
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
  return {
    type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
    enum: actualValues
  };
}
var init_nativeEnum = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/never.js
function parseNeverDef() {
  return {
    not: {}
  };
}
var init_never = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/null.js
function parseNullDef(refs) {
  return refs.target === "openApi3" ? {
    enum: ["null"],
    nullable: true
  } : {
    type: "null"
  };
}
var init_null = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/union.js
function parseUnionDef(def, refs) {
  if (refs.target === "openApi3")
    return asAnyOf(def, refs);
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
  if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
    const types = options.reduce((types2, x2) => {
      const type = primitiveMappings[x2._def.typeName];
      return type && !types2.includes(type) ? [...types2, type] : types2;
    }, []);
    return {
      type: types.length > 1 ? types : types[0]
    };
  } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
    const types = options.reduce((acc, x2) => {
      const type = typeof x2._def.value;
      switch (type) {
        case "string":
        case "number":
        case "boolean":
          return [...acc, type];
        case "bigint":
          return [...acc, "integer"];
        case "object":
          if (x2._def.value === null)
            return [...acc, "null"];
        case "symbol":
        case "undefined":
        case "function":
        default:
          return acc;
      }
    }, []);
    if (types.length === options.length) {
      const uniqueTypes = types.filter((x2, i3, a3) => a3.indexOf(x2) === i3);
      return {
        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
        enum: options.reduce((acc, x2) => {
          return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
        }, [])
      };
    }
  } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
    return {
      type: "string",
      enum: options.reduce((acc, x2) => [
        ...acc,
        ...x2._def.values.filter((x3) => !acc.includes(x3))
      ], [])
    };
  }
  return asAnyOf(def, refs);
}
var primitiveMappings, asAnyOf;
var init_union = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() {
    init_parseDef();
    primitiveMappings = {
      ZodString: "string",
      ZodNumber: "number",
      ZodBigInt: "integer",
      ZodBoolean: "boolean",
      ZodNull: "null"
    };
    asAnyOf = (def, refs) => {
      const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i3) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", `${i3}`]
      })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
      return anyOf.length ? { anyOf } : void 0;
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
function parseNullableDef(def, refs) {
  if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
    if (refs.target === "openApi3") {
      return {
        type: primitiveMappings[def.innerType._def.typeName],
        nullable: true
      };
    }
    return {
      type: [
        primitiveMappings[def.innerType._def.typeName],
        "null"
      ]
    };
  }
  if (refs.target === "openApi3") {
    const base2 = parseDef(def.innerType._def, {
      ...refs,
      currentPath: [...refs.currentPath]
    });
    if (base2 && "$ref" in base2)
      return { allOf: [base2], nullable: true };
    return base2 && { ...base2, nullable: true };
  }
  const base = parseDef(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "0"]
  });
  return base && { anyOf: [base, { type: "null" }] };
}
var init_nullable = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() {
    init_parseDef();
    init_union();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/number.js
function parseNumberDef(def, refs) {
  const res = {
    type: "number"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "int":
        res.type = "integer";
        addErrorMessage(res, "type", check.message, refs);
        break;
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}
var init_number = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() {
    init_errorMessages();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/object.js
function decideAdditionalProperties(def, refs) {
  if (refs.removeAdditionalStrategy === "strict") {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  } else {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  }
}
function parseObjectDef(def, refs) {
  const forceOptionalIntoNullable = refs.target === "openAi";
  const result = {
    type: "object",
    ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
      if (propDef === void 0 || propDef._def === void 0)
        return acc;
      let propOptional = propDef.isOptional();
      if (propOptional && forceOptionalIntoNullable) {
        if (propDef instanceof ZodOptional) {
          propDef = propDef._def.innerType;
        }
        if (!propDef.isNullable()) {
          propDef = propDef.nullable();
        }
        propOptional = false;
      }
      const parsedDef = parseDef(propDef._def, {
        ...refs,
        currentPath: [...refs.currentPath, "properties", propName],
        propertyPath: [...refs.currentPath, "properties", propName]
      });
      if (parsedDef === void 0)
        return acc;
      return {
        properties: { ...acc.properties, [propName]: parsedDef },
        required: propOptional ? acc.required : [...acc.required, propName]
      };
    }, { properties: {}, required: [] }),
    additionalProperties: decideAdditionalProperties(def, refs)
  };
  if (!result.required.length)
    delete result.required;
  return result;
}
var init_object = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() {
    init_lib();
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
var parseOptionalDef;
var init_optional = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() {
    init_parseDef();
    parseOptionalDef = (def, refs) => {
      if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
        return parseDef(def.innerType._def, refs);
      }
      const innerSchema = parseDef(def.innerType._def, {
        ...refs,
        currentPath: [...refs.currentPath, "anyOf", "1"]
      });
      return innerSchema ? {
        anyOf: [
          {
            not: {}
          },
          innerSchema
        ]
      } : {};
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
var parsePipelineDef;
var init_pipeline = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() {
    init_parseDef();
    parsePipelineDef = (def, refs) => {
      if (refs.pipeStrategy === "input") {
        return parseDef(def.in._def, refs);
      } else if (refs.pipeStrategy === "output") {
        return parseDef(def.out._def, refs);
      }
      const a3 = parseDef(def.in._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", "0"]
      });
      const b3 = parseDef(def.out._def, {
        ...refs,
        currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"]
      });
      return {
        allOf: [a3, b3].filter((x2) => x2 !== void 0)
      };
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
function parsePromiseDef(def, refs) {
  return parseDef(def.type._def, refs);
}
var init_promise = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() {
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/set.js
function parseSetDef(def, refs) {
  const items = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items"]
  });
  const schema = {
    type: "array",
    uniqueItems: true,
    items
  };
  if (def.minSize) {
    setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
  }
  if (def.maxSize) {
    setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
  }
  return schema;
}
var init_set = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() {
    init_errorMessages();
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
function parseTupleDef(def, refs) {
  if (def.rest) {
    return {
      type: "array",
      minItems: def.items.length,
      items: def.items.map((x2, i3) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i3}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
      additionalItems: parseDef(def.rest._def, {
        ...refs,
        currentPath: [...refs.currentPath, "additionalItems"]
      })
    };
  } else {
    return {
      type: "array",
      minItems: def.items.length,
      maxItems: def.items.length,
      items: def.items.map((x2, i3) => parseDef(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i3}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
    };
  }
}
var init_tuple = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() {
    init_parseDef();
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
function parseUndefinedDef() {
  return {
    not: {}
  };
}
var init_undefined = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
function parseUnknownDef() {
  return {};
}
var init_unknown = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() {
  }
});

// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
var parseReadonlyDef;
var init_readonly = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() {
    init_parseDef();
    parseReadonlyDef = (def, refs) => {
      return parseDef(def.innerType._def, refs);
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/parseDef.js
function parseDef(def, refs, forceResolution = false) {
  const seenItem = refs.seen.get(def);
  if (refs.override) {
    const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
    if (overrideResult !== ignoreOverride) {
      return overrideResult;
    }
  }
  if (seenItem && !forceResolution) {
    const seenSchema = get$ref(seenItem, refs);
    if (seenSchema !== void 0) {
      return seenSchema;
    }
  }
  const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
  refs.seen.set(def, newItem);
  const jsonSchema = selectParser(def, def.typeName, refs);
  if (jsonSchema) {
    addMeta(def, refs, jsonSchema);
  }
  newItem.jsonSchema = jsonSchema;
  return jsonSchema;
}
var get$ref, getRelativePath, selectParser, addMeta;
var init_parseDef = __esm({
  "node_modules/zod-to-json-schema/dist/esm/parseDef.js"() {
    init_lib();
    init_any();
    init_array();
    init_bigint();
    init_boolean();
    init_branded();
    init_catch();
    init_date();
    init_default();
    init_effects();
    init_enum();
    init_intersection();
    init_literal();
    init_map();
    init_nativeEnum();
    init_never();
    init_null();
    init_nullable();
    init_number();
    init_object();
    init_optional();
    init_pipeline();
    init_promise();
    init_record();
    init_set();
    init_string();
    init_tuple();
    init_undefined();
    init_union();
    init_unknown();
    init_readonly();
    init_Options();
    get$ref = (item, refs) => {
      switch (refs.$refStrategy) {
        case "root":
          return { $ref: item.path.join("/") };
        case "relative":
          return { $ref: getRelativePath(refs.currentPath, item.path) };
        case "none":
        case "seen": {
          if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) {
            console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
            return {};
          }
          return refs.$refStrategy === "seen" ? {} : void 0;
        }
      }
    };
    getRelativePath = (pathA, pathB) => {
      let i3 = 0;
      for (; i3 < pathA.length && i3 < pathB.length; i3++) {
        if (pathA[i3] !== pathB[i3])
          break;
      }
      return [(pathA.length - i3).toString(), ...pathB.slice(i3)].join("/");
    };
    selectParser = (def, typeName, refs) => {
      switch (typeName) {
        case ZodFirstPartyTypeKind.ZodString:
          return parseStringDef(def, refs);
        case ZodFirstPartyTypeKind.ZodNumber:
          return parseNumberDef(def, refs);
        case ZodFirstPartyTypeKind.ZodObject:
          return parseObjectDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBigInt:
          return parseBigintDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBoolean:
          return parseBooleanDef();
        case ZodFirstPartyTypeKind.ZodDate:
          return parseDateDef(def, refs);
        case ZodFirstPartyTypeKind.ZodUndefined:
          return parseUndefinedDef();
        case ZodFirstPartyTypeKind.ZodNull:
          return parseNullDef(refs);
        case ZodFirstPartyTypeKind.ZodArray:
          return parseArrayDef(def, refs);
        case ZodFirstPartyTypeKind.ZodUnion:
        case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
          return parseUnionDef(def, refs);
        case ZodFirstPartyTypeKind.ZodIntersection:
          return parseIntersectionDef(def, refs);
        case ZodFirstPartyTypeKind.ZodTuple:
          return parseTupleDef(def, refs);
        case ZodFirstPartyTypeKind.ZodRecord:
          return parseRecordDef(def, refs);
        case ZodFirstPartyTypeKind.ZodLiteral:
          return parseLiteralDef(def, refs);
        case ZodFirstPartyTypeKind.ZodEnum:
          return parseEnumDef(def);
        case ZodFirstPartyTypeKind.ZodNativeEnum:
          return parseNativeEnumDef(def);
        case ZodFirstPartyTypeKind.ZodNullable:
          return parseNullableDef(def, refs);
        case ZodFirstPartyTypeKind.ZodOptional:
          return parseOptionalDef(def, refs);
        case ZodFirstPartyTypeKind.ZodMap:
          return parseMapDef(def, refs);
        case ZodFirstPartyTypeKind.ZodSet:
          return parseSetDef(def, refs);
        case ZodFirstPartyTypeKind.ZodLazy:
          return parseDef(def.getter()._def, refs);
        case ZodFirstPartyTypeKind.ZodPromise:
          return parsePromiseDef(def, refs);
        case ZodFirstPartyTypeKind.ZodNaN:
        case ZodFirstPartyTypeKind.ZodNever:
          return parseNeverDef();
        case ZodFirstPartyTypeKind.ZodEffects:
          return parseEffectsDef(def, refs);
        case ZodFirstPartyTypeKind.ZodAny:
          return parseAnyDef();
        case ZodFirstPartyTypeKind.ZodUnknown:
          return parseUnknownDef();
        case ZodFirstPartyTypeKind.ZodDefault:
          return parseDefaultDef(def, refs);
        case ZodFirstPartyTypeKind.ZodBranded:
          return parseBrandedDef(def, refs);
        case ZodFirstPartyTypeKind.ZodReadonly:
          return parseReadonlyDef(def, refs);
        case ZodFirstPartyTypeKind.ZodCatch:
          return parseCatchDef(def, refs);
        case ZodFirstPartyTypeKind.ZodPipeline:
          return parsePipelineDef(def, refs);
        case ZodFirstPartyTypeKind.ZodFunction:
        case ZodFirstPartyTypeKind.ZodVoid:
        case ZodFirstPartyTypeKind.ZodSymbol:
          return void 0;
        default:
          return ((_2) => void 0)(typeName);
      }
    };
    addMeta = (def, refs, jsonSchema) => {
      if (def.description) {
        jsonSchema.description = def.description;
        if (refs.markdownDescription) {
          jsonSchema.markdownDescription = def.description;
        }
      }
      return jsonSchema;
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
var zodToJsonSchema;
var init_zodToJsonSchema = __esm({
  "node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() {
    init_parseDef();
    init_Refs();
    zodToJsonSchema = (schema, options) => {
      const refs = getRefs(options);
      const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
        ...acc,
        [name2]: parseDef(schema2._def, {
          ...refs,
          currentPath: [...refs.basePath, refs.definitionPath, name2]
        }, true) ?? {}
      }), {}) : void 0;
      const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
      const main = parseDef(schema._def, name === void 0 ? refs : {
        ...refs,
        currentPath: [...refs.basePath, refs.definitionPath, name]
      }, false) ?? {};
      const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
      if (title !== void 0) {
        main.title = title;
      }
      const combined = name === void 0 ? definitions ? {
        ...main,
        [refs.definitionPath]: definitions
      } : main : {
        $ref: [
          ...refs.$refStrategy === "relative" ? [] : refs.basePath,
          refs.definitionPath,
          name
        ].join("/"),
        [refs.definitionPath]: {
          ...definitions,
          [name]: main
        }
      };
      if (refs.target === "jsonSchema7") {
        combined.$schema = "http://json-schema.org/draft-07/schema#";
      } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
        combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
      }
      if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
        console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
      }
      return combined;
    };
  }
});

// node_modules/zod-to-json-schema/dist/esm/index.js
var init_esm = __esm({
  "node_modules/zod-to-json-schema/dist/esm/index.js"() {
    init_Options();
    init_Refs();
    init_errorMessages();
    init_parseDef();
    init_any();
    init_array();
    init_bigint();
    init_boolean();
    init_branded();
    init_catch();
    init_date();
    init_default();
    init_effects();
    init_enum();
    init_intersection();
    init_literal();
    init_map();
    init_nativeEnum();
    init_never();
    init_null();
    init_nullable();
    init_number();
    init_object();
    init_optional();
    init_pipeline();
    init_promise();
    init_readonly();
    init_record();
    init_set();
    init_string();
    init_tuple();
    init_undefined();
    init_union();
    init_unknown();
    init_zodToJsonSchema();
    init_zodToJsonSchema();
  }
});

// node_modules/@langchain/core/dist/runnables/graph_mermaid.js
function _escapeNodeLabel(nodeLabel) {
  return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_");
}
function _generateMermaidGraphStyles(nodeColors) {
  let styles2 = "";
  for (const [className, color2] of Object.entries(nodeColors)) {
    styles2 += `	classDef ${className} ${color2};
`;
  }
  return styles2;
}
function drawMermaid(nodes, edges, config) {
  const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {};
  let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%
graph TD;
` : "graph TD;\n";
  if (withStyles) {
    const defaultClassLabel = "default";
    const formatDict = {
      [defaultClassLabel]: "{0}({1})"
    };
    if (firstNode !== void 0) {
      formatDict[firstNode] = "{0}([{1}]):::first";
    }
    if (lastNode !== void 0) {
      formatDict[lastNode] = "{0}([{1}]):::last";
    }
    for (const [key, node] of Object.entries(nodes)) {
      const nodeName = node.name.split(":").pop() ?? "";
      const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `<p>${nodeName}</p>` : nodeName;
      let finalLabel = label;
      if (Object.keys(node.metadata ?? {}).length) {
        finalLabel += `<hr/><small><em>${Object.entries(node.metadata ?? {}).map(([k3, v5]) => `${k3} = ${v5}`).join("\n")}</em></small>`;
      }
      const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel);
      mermaidGraph += `	${nodeLabel}
`;
    }
  }
  const edgeGroups = {};
  for (const edge of edges) {
    const srcParts = edge.source.split(":");
    const tgtParts = edge.target.split(":");
    const commonPrefix = srcParts.filter((src, i3) => src === tgtParts[i3]).join(":");
    if (!edgeGroups[commonPrefix]) {
      edgeGroups[commonPrefix] = [];
    }
    edgeGroups[commonPrefix].push(edge);
  }
  const seenSubgraphs = /* @__PURE__ */ new Set();
  function addSubgraph(edges2, prefix) {
    const selfLoop = edges2.length === 1 && edges2[0].source === edges2[0].target;
    if (prefix && !selfLoop) {
      const subgraph = prefix.split(":").pop();
      if (seenSubgraphs.has(subgraph)) {
        throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
      }
      seenSubgraphs.add(subgraph);
      mermaidGraph += `	subgraph ${subgraph}
`;
    }
    for (const edge of edges2) {
      const { source, target, data, conditional } = edge;
      let edgeLabel = "";
      if (data !== void 0) {
        let edgeData = data;
        const words = edgeData.split(" ");
        if (words.length > wrapLabelNWords) {
          edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_2, i3) => words.slice(i3 * wrapLabelNWords, (i3 + 1) * wrapLabelNWords).join(" ")).join("&nbsp;<br>&nbsp;");
        }
        edgeLabel = conditional ? ` -. &nbsp;${edgeData}&nbsp; .-> ` : ` -- &nbsp;${edgeData}&nbsp; --> `;
      } else {
        edgeLabel = conditional ? " -.-> " : " --> ";
      }
      mermaidGraph += `	${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};
`;
    }
    for (const nestedPrefix in edgeGroups) {
      if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) {
        addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
      }
    }
    if (prefix && !selfLoop) {
      mermaidGraph += "	end\n";
    }
  }
  addSubgraph(edgeGroups[""] ?? [], "");
  for (const prefix in edgeGroups) {
    if (!prefix.includes(":") && prefix !== "") {
      addSubgraph(edgeGroups[prefix], prefix);
    }
  }
  if (withStyles) {
    mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {});
  }
  return mermaidGraph;
}
async function drawMermaidPng(mermaidSyntax, config) {
  let { backgroundColor = "white" } = config ?? {};
  const mermaidSyntaxEncoded = btoa(mermaidSyntax);
  if (backgroundColor !== void 0) {
    const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
    if (!hexColorPattern.test(backgroundColor)) {
      backgroundColor = `!${backgroundColor}`;
    }
  }
  const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`;
  const res = await fetch(imageUrl);
  if (!res.ok) {
    throw new Error([
      `Failed to render the graph using the Mermaid.INK API.`,
      `Status code: ${res.status}`,
      `Status text: ${res.statusText}`
    ].join("\n"));
  }
  const content = await res.blob();
  return content;
}
var MARKDOWN_SPECIAL_CHARS;
var init_graph_mermaid = __esm({
  "node_modules/@langchain/core/dist/runnables/graph_mermaid.js"() {
    MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"];
  }
});

// node_modules/@langchain/core/dist/runnables/graph.js
function nodeDataStr(id, data) {
  if (id !== void 0 && !validate_default(id)) {
    return id;
  } else if (isRunnableInterface(data)) {
    try {
      let dataStr = data.getName();
      dataStr = dataStr.startsWith("Runnable") ? dataStr.slice("Runnable".length) : dataStr;
      return dataStr;
    } catch (error) {
      return data.getName();
    }
  } else {
    return data.name ?? "UnknownSchema";
  }
}
function nodeDataJson(node) {
  if (isRunnableInterface(node.data)) {
    return {
      type: "runnable",
      data: {
        id: node.data.lc_id,
        name: node.data.getName()
      }
    };
  } else {
    return {
      type: "schema",
      data: { ...zodToJsonSchema(node.data.schema), title: node.data.name }
    };
  }
}
function _firstNode(graph, exclude = []) {
  const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target));
  const found = [];
  for (const node of Object.values(graph.nodes)) {
    if (!exclude.includes(node.id) && !targets.has(node.id)) {
      found.push(node);
    }
  }
  return found.length === 1 ? found[0] : void 0;
}
function _lastNode(graph, exclude = []) {
  const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source));
  const found = [];
  for (const node of Object.values(graph.nodes)) {
    if (!exclude.includes(node.id) && !sources.has(node.id)) {
      found.push(node);
    }
  }
  return found.length === 1 ? found[0] : void 0;
}
var Graph;
var init_graph = __esm({
  "node_modules/@langchain/core/dist/runnables/graph.js"() {
    init_esm();
    init_esm_browser();
    init_utils3();
    init_graph_mermaid();
    Graph = class {
      constructor(params) {
        Object.defineProperty(this, "nodes", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "edges", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        this.nodes = params?.nodes ?? this.nodes;
        this.edges = params?.edges ?? this.edges;
      }
      // Convert the graph to a JSON-serializable format.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      toJSON() {
        const stableNodeIds = {};
        Object.values(this.nodes).forEach((node, i3) => {
          stableNodeIds[node.id] = validate_default(node.id) ? i3 : node.id;
        });
        return {
          nodes: Object.values(this.nodes).map((node) => ({
            id: stableNodeIds[node.id],
            ...nodeDataJson(node)
          })),
          edges: this.edges.map((edge) => {
            const item = {
              source: stableNodeIds[edge.source],
              target: stableNodeIds[edge.target]
            };
            if (typeof edge.data !== "undefined") {
              item.data = edge.data;
            }
            if (typeof edge.conditional !== "undefined") {
              item.conditional = edge.conditional;
            }
            return item;
          })
        };
      }
      addNode(data, id, metadata) {
        if (id !== void 0 && this.nodes[id] !== void 0) {
          throw new Error(`Node with id ${id} already exists`);
        }
        const nodeId = id ?? v4_default();
        const node = {
          id: nodeId,
          data,
          name: nodeDataStr(id, data),
          metadata
        };
        this.nodes[nodeId] = node;
        return node;
      }
      removeNode(node) {
        delete this.nodes[node.id];
        this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id);
      }
      addEdge(source, target, data, conditional) {
        if (this.nodes[source.id] === void 0) {
          throw new Error(`Source node ${source.id} not in graph`);
        }
        if (this.nodes[target.id] === void 0) {
          throw new Error(`Target node ${target.id} not in graph`);
        }
        const edge = {
          source: source.id,
          target: target.id,
          data,
          conditional
        };
        this.edges.push(edge);
        return edge;
      }
      firstNode() {
        return _firstNode(this);
      }
      lastNode() {
        return _lastNode(this);
      }
      /**
       * Add all nodes and edges from another graph.
       * Note this doesn't check for duplicates, nor does it connect the graphs.
       */
      extend(graph, prefix = "") {
        let finalPrefix = prefix;
        const nodeIds = Object.values(graph.nodes).map((node) => node.id);
        if (nodeIds.every(validate_default)) {
          finalPrefix = "";
        }
        const prefixed = (id) => {
          return finalPrefix ? `${finalPrefix}:${id}` : id;
        };
        Object.entries(graph.nodes).forEach(([key, value]) => {
          this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };
        });
        const newEdges = graph.edges.map((edge) => {
          return {
            ...edge,
            source: prefixed(edge.source),
            target: prefixed(edge.target)
          };
        });
        this.edges = [...this.edges, ...newEdges];
        const first = graph.firstNode();
        const last = graph.lastNode();
        return [
          first ? { id: prefixed(first.id), data: first.data } : void 0,
          last ? { id: prefixed(last.id), data: last.data } : void 0
        ];
      }
      trimFirstNode() {
        const firstNode = this.firstNode();
        if (firstNode && _firstNode(this, [firstNode.id])) {
          this.removeNode(firstNode);
        }
      }
      trimLastNode() {
        const lastNode = this.lastNode();
        if (lastNode && _lastNode(this, [lastNode.id])) {
          this.removeNode(lastNode);
        }
      }
      /**
       * Return a new graph with all nodes re-identified,
       * using their unique, readable names where possible.
       */
      reid() {
        const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name]));
        const nodeLabelCounts = /* @__PURE__ */ new Map();
        Object.values(nodeLabels).forEach((label) => {
          nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);
        });
        const getNodeId = (nodeId) => {
          const label = nodeLabels[nodeId];
          if (validate_default(nodeId) && nodeLabelCounts.get(label) === 1) {
            return label;
          } else {
            return nodeId;
          }
        };
        return new Graph({
          nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [
            getNodeId(id),
            { ...node, id: getNodeId(id) }
          ])),
          edges: this.edges.map((edge) => ({
            ...edge,
            source: getNodeId(edge.source),
            target: getNodeId(edge.target)
          }))
        });
      }
      drawMermaid(params) {
        const { withStyles, curveStyle, nodeColors = {
          default: "fill:#f2f0ff,line-height:1.2",
          first: "fill-opacity:0",
          last: "fill:#bfb6fc"
        }, wrapLabelNWords } = params ?? {};
        const graph = this.reid();
        const firstNode = graph.firstNode();
        const lastNode = graph.lastNode();
        return drawMermaid(graph.nodes, graph.edges, {
          firstNode: firstNode?.id,
          lastNode: lastNode?.id,
          withStyles,
          curveStyle,
          nodeColors,
          wrapLabelNWords
        });
      }
      async drawMermaidPng(params) {
        const mermaidSyntax = this.drawMermaid(params);
        return drawMermaidPng(mermaidSyntax, {
          backgroundColor: params?.backgroundColor
        });
      }
    };
  }
});

// node_modules/@langchain/core/dist/runnables/wrappers.js
function convertToHttpEventStream(stream) {
  const encoder = new TextEncoder();
  const finalStream = new ReadableStream({
    async start(controller) {
      for await (const chunk of stream) {
        controller.enqueue(encoder.encode(`event: data
data: ${JSON.stringify(chunk)}

`));
      }
      controller.enqueue(encoder.encode("event: end\n\n"));
      controller.close();
    }
  });
  return IterableReadableStream.fromReadableStream(finalStream);
}
var init_wrappers = __esm({
  "node_modules/@langchain/core/dist/runnables/wrappers.js"() {
    init_stream();
  }
});

// node_modules/@langchain/core/dist/runnables/iter.js
function isIterableIterator(thing) {
  return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && // avoid detecting array/set as iterator
  typeof thing.next === "function";
}
function isAsyncIterable(thing) {
  return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function";
}
function* consumeIteratorInContext(context, iter) {
  while (true) {
    const { value, done } = AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true);
    if (done) {
      break;
    } else {
      yield value;
    }
  }
}
async function* consumeAsyncIterableInContext(context, iter) {
  const iterator = iter[Symbol.asyncIterator]();
  while (true) {
    const { value, done } = await AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true);
    if (done) {
      break;
    } else {
      yield value;
    }
  }
}
var isIterator;
var init_iter = __esm({
  "node_modules/@langchain/core/dist/runnables/iter.js"() {
    init_singletons();
    init_config();
    isIterator = (x2) => x2 != null && typeof x2 === "object" && "next" in x2 && typeof x2.next === "function";
  }
});

// node_modules/@langchain/core/dist/runnables/base.js
function _coerceToDict2(value, defaultKey) {
  return value && !Array.isArray(value) && // eslint-disable-next-line no-instanceof/no-instanceof
  !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value };
}
function assertNonTraceableFunction(func) {
  if (isTraceableFunction(func)) {
    throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.");
  }
}
function _coerceToRunnable(coerceable) {
  if (typeof coerceable === "function") {
    return new RunnableLambda({ func: coerceable });
  } else if (Runnable.isRunnable(coerceable)) {
    return coerceable;
  } else if (!Array.isArray(coerceable) && typeof coerceable === "object") {
    const runnables = {};
    for (const [key, value] of Object.entries(coerceable)) {
      runnables[key] = _coerceToRunnable(value);
    }
    return new RunnableMap({
      steps: runnables
    });
  } else {
    throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`);
  }
}
function convertRunnableToTool(runnable, fields) {
  const name = fields.name ?? runnable.getName();
  const description = fields.description ?? fields.schema?.description;
  if (fields.schema.constructor === z.ZodString) {
    return new RunnableToolLike({
      name,
      description,
      schema: z.object({
        input: z.string()
      }).transform((input) => input.input),
      bound: runnable
    });
  }
  return new RunnableToolLike({
    name,
    description,
    schema: fields.schema,
    bound: runnable
  });
}
var import_p_retry3, Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableTraceable, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, RunnableToolLike;
var init_base4 = __esm({
  "node_modules/@langchain/core/dist/runnables/base.js"() {
    init_lib();
    import_p_retry3 = __toESM(require_p_retry(), 1);
    init_esm_browser();
    init_traceable2();
    init_log_stream();
    init_event_stream();
    init_serializable();
    init_stream();
    init_signal();
    init_config();
    init_async_caller2();
    init_root_listener();
    init_utils3();
    init_singletons();
    init_graph();
    init_wrappers();
    init_iter();
    init_utils();
    Runnable = class extends Serializable {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "lc_runnable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
      }
      getName(suffix) {
        const name = (
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          this.name ?? this.constructor.lc_name() ?? this.constructor.name
        );
        return suffix ? `${name}${suffix}` : name;
      }
      /**
       * Bind arguments to a Runnable, returning a new Runnable.
       * @param kwargs
       * @returns A new RunnableBinding that, when invoked, will apply the bound args.
       */
      bind(kwargs) {
        return new RunnableBinding({ bound: this, kwargs, config: {} });
      }
      /**
       * Return a new Runnable that maps a list of inputs to a list of outputs,
       * by calling invoke() with each input.
       */
      map() {
        return new RunnableEach({ bound: this });
      }
      /**
       * Add retry logic to an existing runnable.
       * @param kwargs
       * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.
       */
      withRetry(fields) {
        return new RunnableRetry({
          bound: this,
          kwargs: {},
          config: {},
          maxAttemptNumber: fields?.stopAfterAttempt,
          ...fields
        });
      }
      /**
       * Bind config to a Runnable, returning a new Runnable.
       * @param config New configuration parameters to attach to the new runnable.
       * @returns A new RunnableBinding with a config matching what's passed.
       */
      withConfig(config) {
        return new RunnableBinding({
          bound: this,
          config,
          kwargs: {}
        });
      }
      /**
       * Create a new runnable from the current one that will try invoking
       * other passed fallback runnables if the initial invocation fails.
       * @param fields.fallbacks Other runnables to call if the runnable errors.
       * @returns A new RunnableWithFallbacks.
       */
      withFallbacks(fields) {
        const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;
        return new RunnableWithFallbacks({
          runnable: this,
          fallbacks
        });
      }
      _getOptionsList(options, length = 0) {
        if (Array.isArray(options) && options.length !== length) {
          throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);
        }
        if (Array.isArray(options)) {
          return options.map(ensureConfig);
        }
        if (length > 1 && !Array.isArray(options) && options.runId) {
          console.warn("Provided runId will be used only for the first element of the batch.");
          const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId"));
          return Array.from({ length }, (_2, i3) => ensureConfig(i3 === 0 ? options : subsequent));
        }
        return Array.from({ length }, () => ensureConfig(options));
      }
      async batch(inputs, options, batchOptions) {
        const configList = this._getOptionsList(options ?? {}, inputs.length);
        const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;
        const caller2 = new AsyncCaller2({
          maxConcurrency,
          onFailedAttempt: (e3) => {
            throw e3;
          }
        });
        const batchCalls = inputs.map((input, i3) => caller2.call(async () => {
          try {
            const result = await this.invoke(input, configList[i3]);
            return result;
          } catch (e3) {
            if (batchOptions?.returnExceptions) {
              return e3;
            }
            throw e3;
          }
        }));
        return Promise.all(batchCalls);
      }
      /**
       * Default streaming implementation.
       * Subclasses should override this method if they support streaming output.
       * @param input
       * @param options
       */
      async *_streamIterator(input, options) {
        yield this.invoke(input, options);
      }
      /**
       * Stream output in chunks.
       * @param input
       * @param options
       * @returns A readable stream that is also an iterable.
       */
      async stream(input, options) {
        const config = ensureConfig(options);
        const wrappedGenerator = new AsyncGeneratorWithSetup({
          generator: this._streamIterator(input, config),
          config
        });
        await wrappedGenerator.setup;
        return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
      }
      _separateRunnableConfigFromCallOptions(options) {
        let runnableConfig;
        if (options === void 0) {
          runnableConfig = ensureConfig(options);
        } else {
          runnableConfig = ensureConfig({
            callbacks: options.callbacks,
            tags: options.tags,
            metadata: options.metadata,
            runName: options.runName,
            configurable: options.configurable,
            recursionLimit: options.recursionLimit,
            maxConcurrency: options.maxConcurrency,
            runId: options.runId,
            timeout: options.timeout,
            signal: options.signal
          });
        }
        const callOptions = { ...options };
        delete callOptions.callbacks;
        delete callOptions.tags;
        delete callOptions.metadata;
        delete callOptions.runName;
        delete callOptions.configurable;
        delete callOptions.recursionLimit;
        delete callOptions.maxConcurrency;
        delete callOptions.runId;
        delete callOptions.timeout;
        delete callOptions.signal;
        return [runnableConfig, callOptions];
      }
      async _callWithConfig(func, input, options) {
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName());
        delete config.runId;
        let output;
        try {
          const promise = func.call(this, input, config, runManager);
          output = await raceWithSignal(promise, options?.signal);
        } catch (e3) {
          await runManager?.handleChainError(e3);
          throw e3;
        }
        await runManager?.handleChainEnd(_coerceToDict2(output, "output"));
        return output;
      }
      /**
       * Internal method that handles batching and configuration for a runnable
       * It takes a function, input values, and optional configuration, and
       * returns a promise that resolves to the output values.
       * @param func The function to be executed for each input value.
       * @param input The input values to be processed.
       * @param config Optional configuration for the function execution.
       * @returns A promise that resolves to the output values.
       */
      async _batchWithConfig(func, inputs, options, batchOptions) {
        const optionsList = this._getOptionsList(options ?? {}, inputs.length);
        const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig));
        const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => {
          const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), optionsList[i3].runId, optionsList[i3].runType, void 0, void 0, optionsList[i3].runName ?? this.getName());
          delete optionsList[i3].runId;
          return handleStartRes;
        }));
        let outputs;
        try {
          const promise = func.call(this, inputs, optionsList, runManagers, batchOptions);
          outputs = await raceWithSignal(promise, optionsList?.[0]?.signal);
        } catch (e3) {
          await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e3)));
          throw e3;
        }
        await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(outputs, "output"))));
        return outputs;
      }
      /**
       * Helper method to transform an Iterator of Input values into an Iterator of
       * Output values, with callbacks.
       * Use this to implement `stream()` or `transform()` in Runnable subclasses.
       */
      async *_transformStreamWithConfig(inputGenerator, transformer, options) {
        let finalInput;
        let finalInputSupported = true;
        let finalOutput;
        let finalOutputSupported = true;
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        async function* wrapInputForTracing() {
          for await (const chunk of inputGenerator) {
            if (finalInputSupported) {
              if (finalInput === void 0) {
                finalInput = chunk;
              } else {
                try {
                  finalInput = concat(finalInput, chunk);
                } catch {
                  finalInput = void 0;
                  finalInputSupported = false;
                }
              }
            }
            yield chunk;
          }
        }
        let runManager;
        try {
          const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName()), options?.signal, config);
          delete config.runId;
          runManager = pipe.setup;
          const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler);
          let iterator = pipe.output;
          if (streamEventsHandler !== void 0 && runManager !== void 0) {
            iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator);
          }
          const streamLogHandler = runManager?.handlers.find(isLogStreamHandler);
          if (streamLogHandler !== void 0 && runManager !== void 0) {
            iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator);
          }
          for await (const chunk of iterator) {
            yield chunk;
            if (finalOutputSupported) {
              if (finalOutput === void 0) {
                finalOutput = chunk;
              } else {
                try {
                  finalOutput = concat(finalOutput, chunk);
                } catch {
                  finalOutput = void 0;
                  finalOutputSupported = false;
                }
              }
            }
          }
        } catch (e3) {
          await runManager?.handleChainError(e3, void 0, void 0, void 0, {
            inputs: _coerceToDict2(finalInput, "input")
          });
          throw e3;
        }
        await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict2(finalInput, "input") });
      }
      getGraph(_2) {
        const graph = new Graph();
        const inputNode = graph.addNode({
          name: `${this.getName()}Input`,
          schema: z.any()
        });
        const runnableNode = graph.addNode(this);
        const outputNode = graph.addNode({
          name: `${this.getName()}Output`,
          schema: z.any()
        });
        graph.addEdge(inputNode, runnableNode);
        graph.addEdge(runnableNode, outputNode);
        return graph;
      }
      /**
       * Create a new runnable sequence that runs each individual runnable in series,
       * piping the output of one runnable into another runnable or runnable-like.
       * @param coerceable A runnable, function, or object whose values are functions or runnables.
       * @returns A new runnable sequence.
       */
      pipe(coerceable) {
        return new RunnableSequence({
          first: this,
          last: _coerceToRunnable(coerceable)
        });
      }
      /**
       * Pick keys from the dict output of this runnable. Returns a new runnable.
       */
      pick(keys) {
        return this.pipe(new RunnablePick(keys));
      }
      /**
       * Assigns new fields to the dict output of this runnable. Returns a new runnable.
       */
      assign(mapping) {
        return this.pipe(
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          new RunnableAssign(
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            new RunnableMap({ steps: mapping })
          )
        );
      }
      /**
       * Default implementation of transform, which buffers input and then calls stream.
       * Subclasses should override this method if they can start producing output while
       * input is still being generated.
       * @param generator
       * @param options
       */
      async *transform(generator, options) {
        let finalChunk;
        for await (const chunk of generator) {
          if (finalChunk === void 0) {
            finalChunk = chunk;
          } else {
            finalChunk = concat(finalChunk, chunk);
          }
        }
        yield* this._streamIterator(finalChunk, ensureConfig(options));
      }
      /**
       * Stream all output from a runnable, as reported to the callback system.
       * This includes all inner runs of LLMs, Retrievers, Tools, etc.
       * Output is streamed as Log objects, which include a list of
       * jsonpatch ops that describe how the state of the run has changed in each
       * step, and the final state of the run.
       * The jsonpatch ops can be applied in order to construct state.
       * @param input
       * @param options
       * @param streamOptions
       */
      async *streamLog(input, options, streamOptions) {
        const logStreamCallbackHandler = new LogStreamCallbackHandler({
          ...streamOptions,
          autoClose: false,
          _schemaFormat: "original"
        });
        const config = ensureConfig(options);
        yield* this._streamLog(input, logStreamCallbackHandler, config);
      }
      async *_streamLog(input, logStreamCallbackHandler, config) {
        const { callbacks } = config;
        if (callbacks === void 0) {
          config.callbacks = [logStreamCallbackHandler];
        } else if (Array.isArray(callbacks)) {
          config.callbacks = callbacks.concat([logStreamCallbackHandler]);
        } else {
          const copiedCallbacks = callbacks.copy();
          copiedCallbacks.addHandler(logStreamCallbackHandler, true);
          config.callbacks = copiedCallbacks;
        }
        const runnableStreamPromise = this.stream(input, config);
        async function consumeRunnableStream() {
          try {
            const runnableStream = await runnableStreamPromise;
            for await (const chunk of runnableStream) {
              const patch = new RunLogPatch({
                ops: [
                  {
                    op: "add",
                    path: "/streamed_output/-",
                    value: chunk
                  }
                ]
              });
              await logStreamCallbackHandler.writer.write(patch);
            }
          } finally {
            await logStreamCallbackHandler.writer.close();
          }
        }
        const runnableStreamConsumePromise = consumeRunnableStream();
        try {
          for await (const log of logStreamCallbackHandler) {
            yield log;
          }
        } finally {
          await runnableStreamConsumePromise;
        }
      }
      streamEvents(input, options, streamOptions) {
        let stream;
        if (options.version === "v1") {
          stream = this._streamEventsV1(input, options, streamOptions);
        } else if (options.version === "v2") {
          stream = this._streamEventsV2(input, options, streamOptions);
        } else {
          throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`);
        }
        if (options.encoding === "text/event-stream") {
          return convertToHttpEventStream(stream);
        } else {
          return IterableReadableStream.fromAsyncGenerator(stream);
        }
      }
      async *_streamEventsV2(input, options, streamOptions) {
        const eventStreamer = new EventStreamCallbackHandler({
          ...streamOptions,
          autoClose: false
        });
        const config = ensureConfig(options);
        const runId = config.runId ?? v4_default();
        config.runId = runId;
        const callbacks = config.callbacks;
        if (callbacks === void 0) {
          config.callbacks = [eventStreamer];
        } else if (Array.isArray(callbacks)) {
          config.callbacks = callbacks.concat(eventStreamer);
        } else {
          const copiedCallbacks = callbacks.copy();
          copiedCallbacks.addHandler(eventStreamer, true);
          config.callbacks = copiedCallbacks;
        }
        const abortController = new AbortController();
        const outerThis = this;
        async function consumeRunnableStream() {
          try {
            let signal;
            if (options?.signal) {
              if ("any" in AbortSignal) {
                signal = AbortSignal.any([
                  abortController.signal,
                  options.signal
                ]);
              } else {
                signal = options.signal;
                options.signal.addEventListener("abort", () => {
                  abortController.abort();
                }, { once: true });
              }
            } else {
              signal = abortController.signal;
            }
            const runnableStream = await outerThis.stream(input, {
              ...config,
              signal
            });
            const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);
            for await (const _2 of tappedStream) {
              if (abortController.signal.aborted)
                break;
            }
          } finally {
            await eventStreamer.finish();
          }
        }
        const runnableStreamConsumePromise = consumeRunnableStream();
        let firstEventSent = false;
        let firstEventRunId;
        try {
          for await (const event of eventStreamer) {
            if (!firstEventSent) {
              event.data.input = input;
              firstEventSent = true;
              firstEventRunId = event.run_id;
              yield event;
              continue;
            }
            if (event.run_id === firstEventRunId && event.event.endsWith("_end")) {
              if (event.data?.input) {
                delete event.data.input;
              }
            }
            yield event;
          }
        } finally {
          abortController.abort();
          await runnableStreamConsumePromise;
        }
      }
      async *_streamEventsV1(input, options, streamOptions) {
        let runLog;
        let hasEncounteredStartEvent = false;
        const config = ensureConfig(options);
        const rootTags = config.tags ?? [];
        const rootMetadata = config.metadata ?? {};
        const rootName = config.runName ?? this.getName();
        const logStreamCallbackHandler = new LogStreamCallbackHandler({
          ...streamOptions,
          autoClose: false,
          _schemaFormat: "streaming_events"
        });
        const rootEventFilter = new _RootEventFilter({
          ...streamOptions
        });
        const logStream = this._streamLog(input, logStreamCallbackHandler, config);
        for await (const log of logStream) {
          if (!runLog) {
            runLog = RunLog.fromRunLogPatch(log);
          } else {
            runLog = runLog.concat(log);
          }
          if (runLog.state === void 0) {
            throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);
          }
          if (!hasEncounteredStartEvent) {
            hasEncounteredStartEvent = true;
            const state3 = { ...runLog.state };
            const event = {
              run_id: state3.id,
              event: `on_${state3.type}_start`,
              name: rootName,
              tags: rootTags,
              metadata: rootMetadata,
              data: {
                input
              }
            };
            if (rootEventFilter.includeEvent(event, state3.type)) {
              yield event;
            }
          }
          const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]);
          const dedupedPaths = [...new Set(paths)];
          for (const path of dedupedPaths) {
            let eventType;
            let data = {};
            const logEntry = runLog.state.logs[path];
            if (logEntry.end_time === void 0) {
              if (logEntry.streamed_output.length > 0) {
                eventType = "stream";
              } else {
                eventType = "start";
              }
            } else {
              eventType = "end";
            }
            if (eventType === "start") {
              if (logEntry.inputs !== void 0) {
                data.input = logEntry.inputs;
              }
            } else if (eventType === "end") {
              if (logEntry.inputs !== void 0) {
                data.input = logEntry.inputs;
              }
              data.output = logEntry.final_output;
            } else if (eventType === "stream") {
              const chunkCount = logEntry.streamed_output.length;
              if (chunkCount !== 1) {
                throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`);
              }
              data = { chunk: logEntry.streamed_output[0] };
              logEntry.streamed_output = [];
            }
            yield {
              event: `on_${logEntry.type}_${eventType}`,
              name: logEntry.name,
              run_id: logEntry.id,
              tags: logEntry.tags,
              metadata: logEntry.metadata,
              data
            };
          }
          const { state: state2 } = runLog;
          if (state2.streamed_output.length > 0) {
            const chunkCount = state2.streamed_output.length;
            if (chunkCount !== 1) {
              throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`);
            }
            const data = { chunk: state2.streamed_output[0] };
            state2.streamed_output = [];
            const event = {
              event: `on_${state2.type}_stream`,
              run_id: state2.id,
              tags: rootTags,
              metadata: rootMetadata,
              name: rootName,
              data
            };
            if (rootEventFilter.includeEvent(event, state2.type)) {
              yield event;
            }
          }
        }
        const state = runLog?.state;
        if (state !== void 0) {
          const event = {
            event: `on_${state.type}_end`,
            name: rootName,
            run_id: state.id,
            tags: rootTags,
            metadata: rootMetadata,
            data: {
              output: state.final_output
            }
          };
          if (rootEventFilter.includeEvent(event, state.type))
            yield event;
        }
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static isRunnable(thing) {
        return isRunnableInterface(thing);
      }
      /**
       * Bind lifecycle listeners to a Runnable, returning a new Runnable.
       * The Run object contains information about the run, including its id,
       * type, input, output, error, startTime, endTime, and any tags or metadata
       * added to the run.
       *
       * @param {Object} params - The object containing the callback functions.
       * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
       * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
       * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
       */
      withListeners({ onStart, onEnd, onError }) {
        return new RunnableBinding({
          bound: this,
          config: {},
          configFactories: [
            (config) => ({
              callbacks: [
                new RootListenersTracer({
                  config,
                  onStart,
                  onEnd,
                  onError
                })
              ]
            })
          ]
        });
      }
      /**
       * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
       * which contains the runnable, name, description and schema.
       *
       * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
       *
       * @param fields
       * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
       * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
       * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
       * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
       */
      asTool(fields) {
        return convertRunnableToTool(this, fields);
      }
    };
    RunnableBinding = class extends Runnable {
      static lc_name() {
        return "RunnableBinding";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "bound", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "config", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "kwargs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "configFactories", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.bound = fields.bound;
        this.kwargs = fields.kwargs;
        this.config = fields.config;
        this.configFactories = fields.configFactories;
      }
      getName(suffix) {
        return this.bound.getName(suffix);
      }
      async _mergeConfig(...options) {
        const config = mergeConfigs(this.config, ...options);
        return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []);
      }
      bind(kwargs) {
        return new this.constructor({
          bound: this.bound,
          kwargs: { ...this.kwargs, ...kwargs },
          config: this.config
        });
      }
      withConfig(config) {
        return new this.constructor({
          bound: this.bound,
          kwargs: this.kwargs,
          config: { ...this.config, ...config }
        });
      }
      withRetry(fields) {
        return new this.constructor({
          bound: this.bound.withRetry(fields),
          kwargs: this.kwargs,
          config: this.config
        });
      }
      async invoke(input, options) {
        return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs));
      }
      async batch(inputs, options, batchOptions) {
        const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs);
        return this.bound.batch(inputs, mergedOptions, batchOptions);
      }
      async *_streamIterator(input, options) {
        yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs));
      }
      async stream(input, options) {
        return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs));
      }
      async *transform(generator, options) {
        yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs));
      }
      streamEvents(input, options, streamOptions) {
        const outerThis = this;
        const generator = async function* () {
          yield* outerThis.bound.streamEvents(input, {
            ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs),
            version: options.version
          }, streamOptions);
        };
        return IterableReadableStream.fromAsyncGenerator(generator());
      }
      static isRunnableBinding(thing) {
        return thing.bound && Runnable.isRunnable(thing.bound);
      }
      /**
       * Bind lifecycle listeners to a Runnable, returning a new Runnable.
       * The Run object contains information about the run, including its id,
       * type, input, output, error, startTime, endTime, and any tags or metadata
       * added to the run.
       *
       * @param {Object} params - The object containing the callback functions.
       * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
       * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
       * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
       */
      withListeners({ onStart, onEnd, onError }) {
        return new RunnableBinding({
          bound: this.bound,
          kwargs: this.kwargs,
          config: this.config,
          configFactories: [
            (config) => ({
              callbacks: [
                new RootListenersTracer({
                  config,
                  onStart,
                  onEnd,
                  onError
                })
              ]
            })
          ]
        });
      }
    };
    RunnableEach = class extends Runnable {
      static lc_name() {
        return "RunnableEach";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "bound", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.bound = fields.bound;
      }
      /**
       * Binds the runnable with the specified arguments.
       * @param kwargs The arguments to bind the runnable with.
       * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.
       */
      bind(kwargs) {
        return new RunnableEach({
          bound: this.bound.bind(kwargs)
        });
      }
      /**
       * Invokes the runnable with the specified input and configuration.
       * @param input The input to invoke the runnable with.
       * @param config The configuration to invoke the runnable with.
       * @returns A promise that resolves to the output of the runnable.
       */
      async invoke(inputs, config) {
        return this._callWithConfig(this._invoke.bind(this), inputs, config);
      }
      /**
       * A helper method that is used to invoke the runnable with the specified input and configuration.
       * @param input The input to invoke the runnable with.
       * @param config The configuration to invoke the runnable with.
       * @returns A promise that resolves to the output of the runnable.
       */
      async _invoke(inputs, config, runManager) {
        return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() }));
      }
      /**
       * Bind lifecycle listeners to a Runnable, returning a new Runnable.
       * The Run object contains information about the run, including its id,
       * type, input, output, error, startTime, endTime, and any tags or metadata
       * added to the run.
       *
       * @param {Object} params - The object containing the callback functions.
       * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
       * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
       * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
       */
      withListeners({ onStart, onEnd, onError }) {
        return new RunnableEach({
          bound: this.bound.withListeners({ onStart, onEnd, onError })
        });
      }
    };
    RunnableRetry = class extends RunnableBinding {
      static lc_name() {
        return "RunnableRetry";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "maxAttemptNumber", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: 3
        });
        Object.defineProperty(this, "onFailedAttempt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: () => {
          }
        });
        this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
        this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
      }
      _patchConfigForRetry(attempt, config, runManager) {
        const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0;
        return patchConfig(config, { callbacks: runManager?.getChild(tag) });
      }
      async _invoke(input, config, runManager) {
        return (0, import_p_retry3.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onFailedAttempt: (error) => this.onFailedAttempt(error, input),
          retries: Math.max(this.maxAttemptNumber - 1, 0),
          randomize: true
        });
      }
      /**
       * Method that invokes the runnable with the specified input, run manager,
       * and config. It handles the retry logic by catching any errors and
       * recursively invoking itself with the updated config for the next retry
       * attempt.
       * @param input The input for the runnable.
       * @param runManager The run manager for the runnable.
       * @param config The config for the runnable.
       * @returns A promise that resolves to the output of the runnable.
       */
      async invoke(input, config) {
        return this._callWithConfig(this._invoke.bind(this), input, config);
      }
      async _batch(inputs, configs, runManagers, batchOptions) {
        const resultsMap = {};
        try {
          await (0, import_p_retry3.default)(async (attemptNumber) => {
            const remainingIndexes = inputs.map((_2, i3) => i3).filter((i3) => resultsMap[i3.toString()] === void 0 || // eslint-disable-next-line no-instanceof/no-instanceof
            resultsMap[i3.toString()] instanceof Error);
            const remainingInputs = remainingIndexes.map((i3) => inputs[i3]);
            const patchedConfigs = remainingIndexes.map((i3) => this._patchConfigForRetry(attemptNumber, configs?.[i3], runManagers?.[i3]));
            const results = await super.batch(remainingInputs, patchedConfigs, {
              ...batchOptions,
              returnExceptions: true
            });
            let firstException;
            for (let i3 = 0; i3 < results.length; i3 += 1) {
              const result = results[i3];
              const resultMapIndex = remainingIndexes[i3];
              if (result instanceof Error) {
                if (firstException === void 0) {
                  firstException = result;
                  firstException.input = remainingInputs[i3];
                }
              }
              resultsMap[resultMapIndex.toString()] = result;
            }
            if (firstException) {
              throw firstException;
            }
            return results;
          }, {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            onFailedAttempt: (error) => this.onFailedAttempt(error, error.input),
            retries: Math.max(this.maxAttemptNumber - 1, 0),
            randomize: true
          });
        } catch (e3) {
          if (batchOptions?.returnExceptions !== true) {
            throw e3;
          }
        }
        return Object.keys(resultsMap).sort((a3, b3) => parseInt(a3, 10) - parseInt(b3, 10)).map((key) => resultsMap[parseInt(key, 10)]);
      }
      async batch(inputs, options, batchOptions) {
        return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
      }
    };
    RunnableSequence = class extends Runnable {
      static lc_name() {
        return "RunnableSequence";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "first", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "middle", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "last", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "omitSequenceTags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        this.first = fields.first;
        this.middle = fields.middle ?? this.middle;
        this.last = fields.last;
        this.name = fields.name;
        this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags;
      }
      get steps() {
        return [this.first, ...this.middle, this.last];
      }
      async invoke(input, options) {
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config.runId, void 0, void 0, void 0, config?.runName);
        delete config.runId;
        let nextStepInput = input;
        let finalOutput;
        try {
          const initialSteps = [this.first, ...this.middle];
          for (let i3 = 0; i3 < initialSteps.length; i3 += 1) {
            const step = initialSteps[i3];
            const promise = step.invoke(nextStepInput, patchConfig(config, {
              callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`)
            }));
            nextStepInput = await raceWithSignal(promise, options?.signal);
          }
          if (options?.signal?.aborted) {
            throw new Error("Aborted");
          }
          finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, {
            callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`)
          }));
        } catch (e3) {
          await runManager?.handleChainError(e3);
          throw e3;
        }
        await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output"));
        return finalOutput;
      }
      async batch(inputs, options, batchOptions) {
        const configList = this._getOptionsList(options ?? {}, inputs.length);
        const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig));
        const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => {
          const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), configList[i3].runId, void 0, void 0, void 0, configList[i3].runName);
          delete configList[i3].runId;
          return handleStartRes;
        }));
        let nextStepInputs = inputs;
        try {
          for (let i3 = 0; i3 < this.steps.length; i3 += 1) {
            const step = this.steps[i3];
            const promise = step.batch(nextStepInputs, runManagers.map((runManager, j3) => {
              const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`);
              return patchConfig(configList[j3], { callbacks: childRunManager });
            }), batchOptions);
            nextStepInputs = await raceWithSignal(promise, configList[0]?.signal);
          }
        } catch (e3) {
          await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e3)));
          throw e3;
        }
        await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(nextStepInputs, "output"))));
        return nextStepInputs;
      }
      async *_streamIterator(input, options) {
        const callbackManager_ = await getCallbackManagerForConfig(options);
        const { runId, ...otherOptions } = options ?? {};
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName);
        const steps = [this.first, ...this.middle, this.last];
        let concatSupported = true;
        let finalOutput;
        async function* inputGenerator() {
          yield input;
        }
        try {
          let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, {
            callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`)
          }));
          for (let i3 = 1; i3 < steps.length; i3 += 1) {
            const step = steps[i3];
            finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, {
              callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`)
            }));
          }
          for await (const chunk of finalGenerator) {
            options?.signal?.throwIfAborted();
            yield chunk;
            if (concatSupported) {
              if (finalOutput === void 0) {
                finalOutput = chunk;
              } else {
                try {
                  finalOutput = concat(finalOutput, chunk);
                } catch (e3) {
                  finalOutput = void 0;
                  concatSupported = false;
                }
              }
            }
          }
        } catch (e3) {
          await runManager?.handleChainError(e3);
          throw e3;
        }
        await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output"));
      }
      getGraph(config) {
        const graph = new Graph();
        let currentLastNode = null;
        this.steps.forEach((step, index2) => {
          const stepGraph = step.getGraph(config);
          if (index2 !== 0) {
            stepGraph.trimFirstNode();
          }
          if (index2 !== this.steps.length - 1) {
            stepGraph.trimLastNode();
          }
          graph.extend(stepGraph);
          const stepFirstNode = stepGraph.firstNode();
          if (!stepFirstNode) {
            throw new Error(`Runnable ${step} has no first node`);
          }
          if (currentLastNode) {
            graph.addEdge(currentLastNode, stepFirstNode);
          }
          currentLastNode = stepGraph.lastNode();
        });
        return graph;
      }
      pipe(coerceable) {
        if (RunnableSequence.isRunnableSequence(coerceable)) {
          return new RunnableSequence({
            first: this.first,
            middle: this.middle.concat([
              this.last,
              coerceable.first,
              ...coerceable.middle
            ]),
            last: coerceable.last,
            name: this.name ?? coerceable.name
          });
        } else {
          return new RunnableSequence({
            first: this.first,
            middle: [...this.middle, this.last],
            last: _coerceToRunnable(coerceable),
            name: this.name
          });
        }
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static isRunnableSequence(thing) {
        return Array.isArray(thing.middle) && Runnable.isRunnable(thing);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static from([first, ...runnables], nameOrFields) {
        let extra = {};
        if (typeof nameOrFields === "string") {
          extra.name = nameOrFields;
        } else if (nameOrFields !== void 0) {
          extra = nameOrFields;
        }
        return new RunnableSequence({
          ...extra,
          first: _coerceToRunnable(first),
          middle: runnables.slice(0, -1).map(_coerceToRunnable),
          last: _coerceToRunnable(runnables[runnables.length - 1])
        });
      }
    };
    RunnableMap = class extends Runnable {
      static lc_name() {
        return "RunnableMap";
      }
      getStepsKeys() {
        return Object.keys(this.steps);
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "steps", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.steps = {};
        for (const [key, value] of Object.entries(fields.steps)) {
          this.steps[key] = _coerceToRunnable(value);
        }
      }
      static from(steps) {
        return new RunnableMap({ steps });
      }
      async invoke(input, options) {
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
          input
        }, config.runId, void 0, void 0, void 0, config?.runName);
        delete config.runId;
        const output = {};
        try {
          const promises = Object.entries(this.steps).map(async ([key, runnable]) => {
            output[key] = await runnable.invoke(input, patchConfig(config, {
              callbacks: runManager?.getChild(`map:key:${key}`)
            }));
          });
          await raceWithSignal(Promise.all(promises), options?.signal);
        } catch (e3) {
          await runManager?.handleChainError(e3);
          throw e3;
        }
        await runManager?.handleChainEnd(output);
        return output;
      }
      async *_transform(generator, runManager, options) {
        const steps = { ...this.steps };
        const inputCopies = atee(generator, Object.keys(steps).length);
        const tasks = new Map(Object.entries(steps).map(([key, runnable], i3) => {
          const gen = runnable.transform(inputCopies[i3], patchConfig(options, {
            callbacks: runManager?.getChild(`map:key:${key}`)
          }));
          return [key, gen.next().then((result) => ({ key, gen, result }))];
        }));
        while (tasks.size) {
          const promise = Promise.race(tasks.values());
          const { key, result, gen } = await raceWithSignal(promise, options?.signal);
          tasks.delete(key);
          if (!result.done) {
            yield { [key]: result.value };
            tasks.set(key, gen.next().then((result2) => ({ key, gen, result: result2 })));
          }
        }
      }
      transform(generator, options) {
        return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
      }
      async stream(input, options) {
        async function* generator() {
          yield input;
        }
        const config = ensureConfig(options);
        const wrappedGenerator = new AsyncGeneratorWithSetup({
          generator: this.transform(generator(), config),
          config
        });
        await wrappedGenerator.setup;
        return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
      }
    };
    RunnableTraceable = class extends Runnable {
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "func", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (!isTraceableFunction(fields.func)) {
          throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");
        }
        this.func = fields.func;
      }
      async invoke(input, options) {
        const [config] = this._getOptionsList(options ?? {}, 1);
        const callbacks = await getCallbackManagerForConfig(config);
        const promise = this.func(patchConfig(config, { callbacks }), input);
        return raceWithSignal(promise, config?.signal);
      }
      async *_streamIterator(input, options) {
        const [config] = this._getOptionsList(options ?? {}, 1);
        const result = await this.invoke(input, options);
        if (isAsyncIterable(result)) {
          for await (const item of result) {
            config?.signal?.throwIfAborted();
            yield item;
          }
          return;
        }
        if (isIterator(result)) {
          while (true) {
            config?.signal?.throwIfAborted();
            const state = result.next();
            if (state.done)
              break;
            yield state.value;
          }
          return;
        }
        yield result;
      }
      static from(func) {
        return new RunnableTraceable({ func });
      }
    };
    RunnableLambda = class extends Runnable {
      static lc_name() {
        return "RunnableLambda";
      }
      constructor(fields) {
        if (isTraceableFunction(fields.func)) {
          return RunnableTraceable.from(fields.func);
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "func", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        assertNonTraceableFunction(fields.func);
        this.func = fields.func;
      }
      static from(func) {
        return new RunnableLambda({
          func
        });
      }
      async _invoke(input, config, runManager) {
        return new Promise((resolve, reject) => {
          const childConfig = patchConfig(config, {
            callbacks: runManager?.getChild(),
            recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1
          });
          void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
            try {
              let output = await this.func(input, {
                ...childConfig
              });
              if (output && Runnable.isRunnable(output)) {
                if (config?.recursionLimit === 0) {
                  throw new Error("Recursion limit reached.");
                }
                output = await output.invoke(input, {
                  ...childConfig,
                  recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1
                });
              } else if (isAsyncIterable(output)) {
                let finalOutput;
                for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) {
                  config?.signal?.throwIfAborted();
                  if (finalOutput === void 0) {
                    finalOutput = chunk;
                  } else {
                    try {
                      finalOutput = concat(finalOutput, chunk);
                    } catch (e3) {
                      finalOutput = chunk;
                    }
                  }
                }
                output = finalOutput;
              } else if (isIterableIterator(output)) {
                let finalOutput;
                for (const chunk of consumeIteratorInContext(childConfig, output)) {
                  config?.signal?.throwIfAborted();
                  if (finalOutput === void 0) {
                    finalOutput = chunk;
                  } else {
                    try {
                      finalOutput = concat(finalOutput, chunk);
                    } catch (e3) {
                      finalOutput = chunk;
                    }
                  }
                }
                output = finalOutput;
              }
              resolve(output);
            } catch (e3) {
              reject(e3);
            }
          });
        });
      }
      async invoke(input, options) {
        return this._callWithConfig(this._invoke.bind(this), input, options);
      }
      async *_transform(generator, runManager, config) {
        let finalChunk;
        for await (const chunk of generator) {
          if (finalChunk === void 0) {
            finalChunk = chunk;
          } else {
            try {
              finalChunk = concat(finalChunk, chunk);
            } catch (e3) {
              finalChunk = chunk;
            }
          }
        }
        const childConfig = patchConfig(config, {
          callbacks: runManager?.getChild(),
          recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1
        });
        const output = await new Promise((resolve, reject) => {
          void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
            try {
              const res = await this.func(finalChunk, {
                ...childConfig,
                config: childConfig
              });
              resolve(res);
            } catch (e3) {
              reject(e3);
            }
          });
        });
        if (output && Runnable.isRunnable(output)) {
          if (config?.recursionLimit === 0) {
            throw new Error("Recursion limit reached.");
          }
          const stream = await output.stream(finalChunk, childConfig);
          for await (const chunk of stream) {
            yield chunk;
          }
        } else if (isAsyncIterable(output)) {
          for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) {
            config?.signal?.throwIfAborted();
            yield chunk;
          }
        } else if (isIterableIterator(output)) {
          for (const chunk of consumeIteratorInContext(childConfig, output)) {
            config?.signal?.throwIfAborted();
            yield chunk;
          }
        } else {
          yield output;
        }
      }
      transform(generator, options) {
        return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
      }
      async stream(input, options) {
        async function* generator() {
          yield input;
        }
        const config = ensureConfig(options);
        const wrappedGenerator = new AsyncGeneratorWithSetup({
          generator: this.transform(generator(), config),
          config
        });
        await wrappedGenerator.setup;
        return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
      }
    };
    RunnableWithFallbacks = class extends Runnable {
      static lc_name() {
        return "RunnableWithFallbacks";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "runnable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "fallbacks", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.runnable = fields.runnable;
        this.fallbacks = fields.fallbacks;
      }
      *runnables() {
        yield this.runnable;
        for (const fallback of this.fallbacks) {
          yield fallback;
        }
      }
      async invoke(input, options) {
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        const { runId, ...otherConfigFields } = config;
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName);
        const childConfig = patchConfig(otherConfigFields, {
          callbacks: runManager?.getChild()
        });
        const res = await AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => {
          let firstError;
          for (const runnable of this.runnables()) {
            config?.signal?.throwIfAborted();
            try {
              const output = await runnable.invoke(input, childConfig);
              await runManager?.handleChainEnd(_coerceToDict2(output, "output"));
              return output;
            } catch (e3) {
              if (firstError === void 0) {
                firstError = e3;
              }
            }
          }
          if (firstError === void 0) {
            throw new Error("No error stored at end of fallback.");
          }
          await runManager?.handleChainError(firstError);
          throw firstError;
        });
        return res;
      }
      async *_streamIterator(input, options) {
        const config = ensureConfig(options);
        const callbackManager_ = await getCallbackManagerForConfig(config);
        const { runId, ...otherConfigFields } = config;
        const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName);
        let firstError;
        let stream;
        for (const runnable of this.runnables()) {
          config?.signal?.throwIfAborted();
          const childConfig = patchConfig(otherConfigFields, {
            callbacks: runManager?.getChild()
          });
          try {
            const originalStream = await runnable.stream(input, childConfig);
            stream = consumeAsyncIterableInContext(childConfig, originalStream);
            break;
          } catch (e3) {
            if (firstError === void 0) {
              firstError = e3;
            }
          }
        }
        if (stream === void 0) {
          const error = firstError ?? new Error("No error stored at end of fallback.");
          await runManager?.handleChainError(error);
          throw error;
        }
        let output;
        try {
          for await (const chunk of stream) {
            yield chunk;
            try {
              output = output === void 0 ? output : concat(output, chunk);
            } catch (e3) {
              output = void 0;
            }
          }
        } catch (e3) {
          await runManager?.handleChainError(e3);
          throw e3;
        }
        await runManager?.handleChainEnd(_coerceToDict2(output, "output"));
      }
      async batch(inputs, options, batchOptions) {
        if (batchOptions?.returnExceptions) {
          throw new Error("Not implemented.");
        }
        const configList = this._getOptionsList(options ?? {}, inputs.length);
        const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config)));
        const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => {
          const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), configList[i3].runId, void 0, void 0, void 0, configList[i3].runName);
          delete configList[i3].runId;
          return handleStartRes;
        }));
        let firstError;
        for (const runnable of this.runnables()) {
          configList[0].signal?.throwIfAborted();
          try {
            const outputs = await runnable.batch(inputs, runManagers.map((runManager, j3) => patchConfig(configList[j3], {
              callbacks: runManager?.getChild()
            })), batchOptions);
            await Promise.all(runManagers.map((runManager, i3) => runManager?.handleChainEnd(_coerceToDict2(outputs[i3], "output"))));
            return outputs;
          } catch (e3) {
            if (firstError === void 0) {
              firstError = e3;
            }
          }
        }
        if (!firstError) {
          throw new Error("No error stored at end of fallbacks.");
        }
        await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));
        throw firstError;
      }
    };
    RunnableAssign = class extends Runnable {
      static lc_name() {
        return "RunnableAssign";
      }
      constructor(fields) {
        if (fields instanceof RunnableMap) {
          fields = { mapper: fields };
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "mapper", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.mapper = fields.mapper;
      }
      async invoke(input, options) {
        const mapperResult = await this.mapper.invoke(input, options);
        return {
          ...input,
          ...mapperResult
        };
      }
      async *_transform(generator, runManager, options) {
        const mapperKeys = this.mapper.getStepsKeys();
        const [forPassthrough, forMapper] = atee(generator);
        const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() }));
        const firstMapperChunkPromise = mapperOutput.next();
        for await (const chunk of forPassthrough) {
          if (typeof chunk !== "object" || Array.isArray(chunk)) {
            throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`);
          }
          const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key)));
          if (Object.keys(filtered).length > 0) {
            yield filtered;
          }
        }
        yield (await firstMapperChunkPromise).value;
        for await (const chunk of mapperOutput) {
          yield chunk;
        }
      }
      transform(generator, options) {
        return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
      }
      async stream(input, options) {
        async function* generator() {
          yield input;
        }
        const config = ensureConfig(options);
        const wrappedGenerator = new AsyncGeneratorWithSetup({
          generator: this.transform(generator(), config),
          config
        });
        await wrappedGenerator.setup;
        return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
      }
    };
    RunnablePick = class extends Runnable {
      static lc_name() {
        return "RunnablePick";
      }
      constructor(fields) {
        if (typeof fields === "string" || Array.isArray(fields)) {
          fields = { keys: fields };
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "keys", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.keys = fields.keys;
      }
      async _pick(input) {
        if (typeof this.keys === "string") {
          return input[this.keys];
        } else {
          const picked = this.keys.map((key) => [key, input[key]]).filter((v5) => v5[1] !== void 0);
          return picked.length === 0 ? void 0 : Object.fromEntries(picked);
        }
      }
      async invoke(input, options) {
        return this._callWithConfig(this._pick.bind(this), input, options);
      }
      async *_transform(generator) {
        for await (const chunk of generator) {
          const picked = await this._pick(chunk);
          if (picked !== void 0) {
            yield picked;
          }
        }
      }
      transform(generator, options) {
        return this._transformStreamWithConfig(generator, this._transform.bind(this), options);
      }
      async stream(input, options) {
        async function* generator() {
          yield input;
        }
        const config = ensureConfig(options);
        const wrappedGenerator = new AsyncGeneratorWithSetup({
          generator: this.transform(generator(), config),
          config
        });
        await wrappedGenerator.setup;
        return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
      }
    };
    RunnableToolLike = class extends RunnableBinding {
      constructor(fields) {
        const sequence = RunnableSequence.from([
          RunnableLambda.from(async (input) => {
            let toolInput;
            if (_isToolCall(input)) {
              try {
                toolInput = await this.schema.parseAsync(input.args);
              } catch (e3) {
                throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));
              }
            } else {
              toolInput = input;
            }
            return toolInput;
          }).withConfig({ runName: `${fields.name}:parse_input` }),
          fields.bound
        ]).withConfig({ runName: fields.name });
        super({
          bound: sequence,
          config: fields.config ?? {}
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "description", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "schema", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.name = fields.name;
        this.description = fields.description;
        this.schema = fields.schema;
      }
      static lc_name() {
        return "RunnableToolLike";
      }
    };
  }
});

// node_modules/@langchain/core/dist/runnables/passthrough.js
var RunnablePassthrough;
var init_passthrough = __esm({
  "node_modules/@langchain/core/dist/runnables/passthrough.js"() {
    init_stream();
    init_base4();
    init_config();
    RunnablePassthrough = class extends Runnable {
      static lc_name() {
        return "RunnablePassthrough";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "runnables"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "func", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (fields) {
          this.func = fields.func;
        }
      }
      async invoke(input, options) {
        const config = ensureConfig(options);
        if (this.func) {
          await this.func(input, config);
        }
        return this._callWithConfig((input2) => Promise.resolve(input2), input, config);
      }
      async *transform(generator, options) {
        const config = ensureConfig(options);
        let finalOutput;
        let finalOutputSupported = true;
        for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) {
          yield chunk;
          if (finalOutputSupported) {
            if (finalOutput === void 0) {
              finalOutput = chunk;
            } else {
              try {
                finalOutput = concat(finalOutput, chunk);
              } catch {
                finalOutput = void 0;
                finalOutputSupported = false;
              }
            }
          }
        }
        if (this.func && finalOutput !== void 0) {
          await this.func(finalOutput, config);
        }
      }
      /**
       * A runnable that assigns key-value pairs to the input.
       *
       * The example below shows how you could use it with an inline function.
       *
       * @example
       * ```typescript
       * const prompt =
       *   PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}
       * Question: {question}
       * SQL Query:`);
       *
       * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`
       * // call (in this example it's the question), along with any inputs passed to the `.assign()` method.
       * // In this case, we're passing the schema.
       * const sqlQueryGeneratorChain = RunnableSequence.from([
       *   RunnablePassthrough.assign({
       *     schema: async () => db.getTableInfo(),
       *   }),
       *   prompt,
       *   new ChatOpenAI({}).bind({ stop: ["\nSQLResult:"] }),
       *   new StringOutputParser(),
       * ]);
       * const result = await sqlQueryGeneratorChain.invoke({
       *   question: "How many employees are there?",
       * });
       * ```
       */
      static assign(mapping) {
        return new RunnableAssign(new RunnableMap({ steps: mapping }));
      }
    };
  }
});

// node_modules/@langchain/core/dist/runnables/router.js
var init_router = __esm({
  "node_modules/@langchain/core/dist/runnables/router.js"() {
    init_base4();
    init_config();
  }
});

// node_modules/@langchain/core/dist/runnables/branch.js
var init_branch = __esm({
  "node_modules/@langchain/core/dist/runnables/branch.js"() {
    init_base4();
    init_config();
    init_stream();
  }
});

// node_modules/@langchain/core/dist/messages/modifier.js
var init_modifier = __esm({
  "node_modules/@langchain/core/dist/messages/modifier.js"() {
    init_base3();
  }
});

// node_modules/@langchain/core/dist/messages/transformers.js
var init_transformers = __esm({
  "node_modules/@langchain/core/dist/messages/transformers.js"() {
    init_base4();
    init_ai();
    init_base3();
    init_chat();
    init_function();
    init_human();
    init_modifier();
    init_system();
    init_tool();
    init_utils2();
  }
});

// node_modules/@langchain/core/dist/messages/index.js
var init_messages2 = __esm({
  "node_modules/@langchain/core/dist/messages/index.js"() {
    init_ai();
    init_base3();
    init_chat();
    init_function();
    init_human();
    init_system();
    init_utils2();
    init_transformers();
    init_modifier();
    init_tool();
  }
});

// node_modules/@langchain/core/dist/runnables/history.js
var init_history = __esm({
  "node_modules/@langchain/core/dist/runnables/history.js"() {
    init_messages2();
    init_base4();
    init_passthrough();
  }
});

// node_modules/@langchain/core/dist/runnables/index.js
var init_runnables = __esm({
  "node_modules/@langchain/core/dist/runnables/index.js"() {
    init_base4();
    init_config();
    init_passthrough();
    init_router();
    init_branch();
    init_history();
  }
});

// node_modules/@langchain/core/dist/output_parsers/base.js
var BaseLLMOutputParser, BaseOutputParser, OutputParserException;
var init_base5 = __esm({
  "node_modules/@langchain/core/dist/output_parsers/base.js"() {
    init_runnables();
    init_errors();
    BaseLLMOutputParser = class extends Runnable {
      /**
       * Parses the result of an LLM call with a given prompt. By default, it
       * simply calls `parseResult`.
       * @param generations The generations from an LLM call.
       * @param _prompt The prompt used in the LLM call.
       * @param callbacks Optional callbacks.
       * @returns A promise of the parsed output.
       */
      parseResultWithPrompt(generations, _prompt, callbacks) {
        return this.parseResult(generations, callbacks);
      }
      _baseMessageToString(message) {
        return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content);
      }
      _baseMessageContentToString(content) {
        return JSON.stringify(content);
      }
      /**
       * Calls the parser with a given input and optional configuration options.
       * If the input is a string, it creates a generation with the input as
       * text and calls `parseResult`. If the input is a `BaseMessage`, it
       * creates a generation with the input as a message and the content of the
       * input as text, and then calls `parseResult`.
       * @param input The input to the parser, which can be a string or a `BaseMessage`.
       * @param options Optional configuration options.
       * @returns A promise of the parsed output.
       */
      async invoke(input, options) {
        if (typeof input === "string") {
          return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { ...options, runType: "parser" });
        } else {
          return this._callWithConfig(async (input2, options2) => this.parseResult([
            {
              message: input2,
              text: this._baseMessageToString(input2)
            }
          ], options2?.callbacks), input, { ...options, runType: "parser" });
        }
      }
    };
    BaseOutputParser = class extends BaseLLMOutputParser {
      parseResult(generations, callbacks) {
        return this.parse(generations[0].text, callbacks);
      }
      async parseWithPrompt(text, _prompt, callbacks) {
        return this.parse(text, callbacks);
      }
      /**
       * Return the string type key uniquely identifying this class of parser
       */
      _type() {
        throw new Error("_type not implemented");
      }
    };
    OutputParserException = class extends Error {
      constructor(message, llmOutput, observation, sendToLLM = false) {
        super(message);
        Object.defineProperty(this, "llmOutput", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "observation", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "sendToLLM", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.llmOutput = llmOutput;
        this.observation = observation;
        this.sendToLLM = sendToLLM;
        if (sendToLLM) {
          if (observation === void 0 || llmOutput === void 0) {
            throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");
          }
        }
        addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE");
      }
    };
  }
});

// node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js
function deepCompareStrict(a3, b3) {
  const typeofa = typeof a3;
  if (typeofa !== typeof b3) {
    return false;
  }
  if (Array.isArray(a3)) {
    if (!Array.isArray(b3)) {
      return false;
    }
    const length = a3.length;
    if (length !== b3.length) {
      return false;
    }
    for (let i3 = 0; i3 < length; i3++) {
      if (!deepCompareStrict(a3[i3], b3[i3])) {
        return false;
      }
    }
    return true;
  }
  if (typeofa === "object") {
    if (!a3 || !b3) {
      return a3 === b3;
    }
    const aKeys = Object.keys(a3);
    const bKeys = Object.keys(b3);
    const length = aKeys.length;
    if (length !== bKeys.length) {
      return false;
    }
    for (const k3 of aKeys) {
      if (!deepCompareStrict(a3[k3], b3[k3])) {
        return false;
      }
    }
    return true;
  }
  return a3 === b3;
}
var init_deep_compare_strict = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js"() {
  }
});

// node_modules/@cfworker/json-schema/dist/esm/pointer.js
var init_pointer = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/pointer.js"() {
  }
});

// node_modules/@cfworker/json-schema/dist/esm/dereference.js
var initialBaseURI;
var init_dereference = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/dereference.js"() {
    init_pointer();
    initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker");
  }
});

// node_modules/@cfworker/json-schema/dist/esm/format.js
function bind(r4) {
  return r4.test.bind(r4);
}
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function date(str2) {
  const matches = str2.match(DATE);
  if (!matches)
    return false;
  const year = +matches[1];
  const month = +matches[2];
  const day = +matches[3];
  return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}
function time(full, str2) {
  const matches = str2.match(TIME);
  if (!matches)
    return false;
  const hour = +matches[1];
  const minute = +matches[2];
  const second2 = +matches[3];
  const timeZone = !!matches[5];
  return (hour <= 23 && minute <= 59 && second2 <= 59 || hour == 23 && minute == 59 && second2 == 60) && (!full || timeZone);
}
function date_time(str2) {
  const dateTime = str2.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]);
}
function uri(str2) {
  return NOT_URI_FRAGMENT.test(str2) && URI_PATTERN.test(str2);
}
function regex(str2) {
  if (Z_ANCHOR.test(str2))
    return false;
  try {
    new RegExp(str2, "u");
    return true;
  } catch (e3) {
    return false;
  }
}
var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, FASTDATE, FASTTIME, FASTDATETIME, FASTURIREFERENCE, EMAIL, IPV4, IPV6, DURATION, fullFormat, fastFormat, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR;
var init_format = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/format.js"() {
    DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
    HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
    URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
    URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
    UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
    JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
    JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
    RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
    FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/;
    FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i;
    FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i;
    FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i;
    EMAIL = (input) => {
      if (input[0] === '"')
        return false;
      const [name, host, ...rest] = input.split("@");
      if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253)
        return false;
      if (name[0] === "." || name.endsWith(".") || name.includes(".."))
        return false;
      if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name))
        return false;
      return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part));
    };
    IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
    IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i;
    DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input));
    fullFormat = {
      date,
      time: time.bind(void 0, false),
      "date-time": date_time,
      duration: DURATION,
      uri,
      "uri-reference": bind(URIREF),
      "uri-template": bind(URITEMPLATE),
      url: bind(URL_),
      email: EMAIL,
      hostname: bind(HOSTNAME),
      ipv4: bind(IPV4),
      ipv6: bind(IPV6),
      regex,
      uuid: bind(UUID),
      "json-pointer": bind(JSON_POINTER),
      "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT),
      "relative-json-pointer": bind(RELATIVE_JSON_POINTER)
    };
    fastFormat = {
      ...fullFormat,
      date: bind(FASTDATE),
      time: bind(FASTTIME),
      "date-time": bind(FASTDATETIME),
      "uri-reference": bind(FASTURIREFERENCE)
    };
    DATE_TIME_SEPARATOR = /t|\s/i;
    NOT_URI_FRAGMENT = /\/|:/;
    URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
    Z_ANCHOR = /[^\\]\\Z/;
  }
});

// node_modules/@cfworker/json-schema/dist/esm/types.js
var OutputFormat;
var init_types = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/types.js"() {
    (function(OutputFormat2) {
      OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag";
      OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic";
      OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed";
    })(OutputFormat || (OutputFormat = {}));
  }
});

// node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js
var init_ucs2_length = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js"() {
  }
});

// node_modules/@cfworker/json-schema/dist/esm/validate.js
var init_validate3 = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/validate.js"() {
    init_deep_compare_strict();
    init_dereference();
    init_format();
    init_pointer();
    init_ucs2_length();
  }
});

// node_modules/@cfworker/json-schema/dist/esm/validator.js
var init_validator = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/validator.js"() {
    init_dereference();
    init_validate3();
  }
});

// node_modules/@cfworker/json-schema/dist/esm/index.js
var init_esm2 = __esm({
  "node_modules/@cfworker/json-schema/dist/esm/index.js"() {
    init_deep_compare_strict();
    init_dereference();
    init_format();
    init_pointer();
    init_types();
    init_ucs2_length();
    init_validate3();
    init_validator();
  }
});

// node_modules/@langchain/core/dist/output_parsers/transform.js
var BaseTransformOutputParser, BaseCumulativeTransformOutputParser;
var init_transform = __esm({
  "node_modules/@langchain/core/dist/output_parsers/transform.js"() {
    init_esm2();
    init_base5();
    init_base3();
    init_utils2();
    init_outputs();
    BaseTransformOutputParser = class extends BaseOutputParser {
      async *_transform(inputGenerator) {
        for await (const chunk of inputGenerator) {
          if (typeof chunk === "string") {
            yield this.parseResult([{ text: chunk }]);
          } else {
            yield this.parseResult([
              {
                message: chunk,
                text: this._baseMessageToString(chunk)
              }
            ]);
          }
        }
      }
      /**
       * Transforms an asynchronous generator of input into an asynchronous
       * generator of parsed output.
       * @param inputGenerator An asynchronous generator of input.
       * @param options A configuration object.
       * @returns An asynchronous generator of parsed output.
       */
      async *transform(inputGenerator, options) {
        yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), {
          ...options,
          runType: "parser"
        });
      }
    };
    BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser {
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "diff", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        this.diff = fields?.diff ?? this.diff;
      }
      async *_transform(inputGenerator) {
        let prevParsed;
        let accGen;
        for await (const chunk of inputGenerator) {
          if (typeof chunk !== "string" && typeof chunk.content !== "string") {
            throw new Error("Cannot handle non-string output.");
          }
          let chunkGen;
          if (isBaseMessageChunk(chunk)) {
            if (typeof chunk.content !== "string") {
              throw new Error("Cannot handle non-string message output.");
            }
            chunkGen = new ChatGenerationChunk({
              message: chunk,
              text: chunk.content
            });
          } else if (isBaseMessage(chunk)) {
            if (typeof chunk.content !== "string") {
              throw new Error("Cannot handle non-string message output.");
            }
            chunkGen = new ChatGenerationChunk({
              message: convertToChunk(chunk),
              text: chunk.content
            });
          } else {
            chunkGen = new GenerationChunk({ text: chunk });
          }
          if (accGen === void 0) {
            accGen = chunkGen;
          } else {
            accGen = accGen.concat(chunkGen);
          }
          const parsed = await this.parsePartialResult([accGen]);
          if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) {
            if (this.diff) {
              yield this._diff(prevParsed, parsed);
            } else {
              yield parsed;
            }
            prevParsed = parsed;
          }
        }
      }
      getFormatInstructions() {
        return "";
      }
    };
  }
});

// node_modules/@langchain/core/dist/output_parsers/bytes.js
var init_bytes = __esm({
  "node_modules/@langchain/core/dist/output_parsers/bytes.js"() {
    init_transform();
  }
});

// node_modules/@langchain/core/dist/output_parsers/list.js
var init_list = __esm({
  "node_modules/@langchain/core/dist/output_parsers/list.js"() {
    init_base5();
    init_transform();
  }
});

// node_modules/@langchain/core/dist/output_parsers/string.js
var StringOutputParser;
var init_string2 = __esm({
  "node_modules/@langchain/core/dist/output_parsers/string.js"() {
    init_transform();
    StringOutputParser = class extends BaseTransformOutputParser {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "output_parsers", "string"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
      }
      static lc_name() {
        return "StrOutputParser";
      }
      /**
       * Parses a string output from an LLM call. This method is meant to be
       * implemented by subclasses to define how a string output from an LLM
       * should be parsed.
       * @param text The string output from an LLM call.
       * @param callbacks Optional callbacks.
       * @returns A promise of the parsed output.
       */
      parse(text) {
        return Promise.resolve(text);
      }
      getFormatInstructions() {
        return "";
      }
      _textContentToString(content) {
        return content.text;
      }
      _imageUrlContentToString(_content) {
        throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`);
      }
      _messageContentComplexToString(content) {
        switch (content.type) {
          case "text":
          case "text_delta":
            if ("text" in content) {
              return this._textContentToString(content);
            }
            break;
          case "image_url":
            if ("image_url" in content) {
              return this._imageUrlContentToString(content);
            }
            break;
          default:
            throw new Error(`Cannot coerce "${content.type}" message part into a string.`);
        }
        throw new Error(`Invalid content type: ${content.type}`);
      }
      _baseMessageContentToString(content) {
        return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), "");
      }
    };
  }
});

// node_modules/@langchain/core/dist/output_parsers/structured.js
var StructuredOutputParser;
var init_structured = __esm({
  "node_modules/@langchain/core/dist/output_parsers/structured.js"() {
    init_lib();
    init_esm();
    init_base5();
    StructuredOutputParser = class extends BaseOutputParser {
      static lc_name() {
        return "StructuredOutputParser";
      }
      toJSON() {
        return this.toJSONNotImplemented();
      }
      constructor(schema) {
        super(schema);
        Object.defineProperty(this, "schema", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: schema
        });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain", "output_parsers", "structured"]
        });
      }
      /**
       * Creates a new StructuredOutputParser from a Zod schema.
       * @param schema The Zod schema which the output should match
       * @returns A new instance of StructuredOutputParser.
       */
      static fromZodSchema(schema) {
        return new this(schema);
      }
      /**
       * Creates a new StructuredOutputParser from a set of names and
       * descriptions.
       * @param schemas An object where each key is a name and each value is a description
       * @returns A new instance of StructuredOutputParser.
       */
      static fromNamesAndDescriptions(schemas) {
        const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)])));
        return new this(zodSchema);
      }
      /**
       * Returns a markdown code snippet with a JSON object formatted according
       * to the schema.
       * @param options Optional. The options for formatting the instructions
       * @returns A markdown code snippet with a JSON object formatted according to the schema.
       */
      getFormatInstructions() {
        return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance.

"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.

For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.

Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!

Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(zodToJsonSchema(this.schema))}
\`\`\`
`;
      }
      /**
       * Parses the given text according to the schema.
       * @param text The text to parse
       * @returns The parsed output.
       */
      async parse(text) {
        try {
          const json = text.includes("```") ? text.trim().split(/```(?:json)?/)[1] : text.trim();
          const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => {
            const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n");
            return `"${escapedInsideQuotes}"`;
          }).replace(/\n/g, "");
          return await this.schema.parseAsync(JSON.parse(escapedJson));
        } catch (e3) {
          throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e3}`, text);
        }
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/json_patch.js
var init_json_patch = __esm({
  "node_modules/@langchain/core/dist/utils/json_patch.js"() {
    init_fast_json_patch();
  }
});

// node_modules/@langchain/core/dist/output_parsers/json.js
var JsonOutputParser;
var init_json2 = __esm({
  "node_modules/@langchain/core/dist/output_parsers/json.js"() {
    init_transform();
    init_json_patch();
    init_json();
    JsonOutputParser = class extends BaseCumulativeTransformOutputParser {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "output_parsers"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
      }
      static lc_name() {
        return "JsonOutputParser";
      }
      _diff(prev, next) {
        if (!next) {
          return void 0;
        }
        if (!prev) {
          return [{ op: "replace", path: "", value: next }];
        }
        return compare(prev, next);
      }
      // This should actually return Partial<T>, but there's no way
      // to specify emitted chunks as instances separate from the main output type.
      async parsePartialResult(generations) {
        return parseJsonMarkdown(generations[0].text);
      }
      async parse(text) {
        return parseJsonMarkdown(text, JSON.parse);
      }
      getFormatInstructions() {
        return "";
      }
    };
  }
});

// node_modules/@langchain/core/dist/utils/sax-js/sax.js
var init_sax = __esm({
  "node_modules/@langchain/core/dist/utils/sax-js/sax.js"() {
  }
});

// node_modules/@langchain/core/dist/output_parsers/xml.js
var init_xml = __esm({
  "node_modules/@langchain/core/dist/output_parsers/xml.js"() {
    init_transform();
    init_json_patch();
    init_sax();
  }
});

// node_modules/@langchain/core/dist/output_parsers/index.js
var init_output_parsers = __esm({
  "node_modules/@langchain/core/dist/output_parsers/index.js"() {
    init_base5();
    init_bytes();
    init_list();
    init_string2();
    init_structured();
    init_transform();
    init_json2();
    init_xml();
  }
});

// node_modules/@langchain/core/output_parsers.js
var init_output_parsers2 = __esm({
  "node_modules/@langchain/core/output_parsers.js"() {
    init_output_parsers();
  }
});

// node_modules/@langchain/core/dist/prompt_values.js
var BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue;
var init_prompt_values = __esm({
  "node_modules/@langchain/core/dist/prompt_values.js"() {
    init_serializable();
    init_human();
    init_utils2();
    BasePromptValue = class extends Serializable {
    };
    StringPromptValue = class extends BasePromptValue {
      static lc_name() {
        return "StringPromptValue";
      }
      constructor(value) {
        super({ value });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompt_values"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "value", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.value = value;
      }
      toString() {
        return this.value;
      }
      toChatMessages() {
        return [new HumanMessage(this.value)];
      }
    };
    ChatPromptValue = class extends BasePromptValue {
      static lc_name() {
        return "ChatPromptValue";
      }
      constructor(fields) {
        if (Array.isArray(fields)) {
          fields = { messages: fields };
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompt_values"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "messages", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.messages = fields.messages;
      }
      toString() {
        return getBufferString(this.messages);
      }
      toChatMessages() {
        return this.messages;
      }
    };
    ImagePromptValue = class extends BasePromptValue {
      static lc_name() {
        return "ImagePromptValue";
      }
      constructor(fields) {
        if (!("imageUrl" in fields)) {
          fields = { imageUrl: fields };
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompt_values"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "imageUrl", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "value", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.imageUrl = fields.imageUrl;
      }
      toString() {
        return this.imageUrl.url;
      }
      toChatMessages() {
        return [
          new HumanMessage({
            content: [
              {
                type: "image_url",
                image_url: {
                  detail: this.imageUrl.detail,
                  url: this.imageUrl.url
                }
              }
            ]
          })
        ];
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/string.js
var BaseStringPromptTemplate;
var init_string3 = __esm({
  "node_modules/@langchain/core/dist/prompts/string.js"() {
    init_prompt_values();
    init_base6();
    BaseStringPromptTemplate = class extends BasePromptTemplate {
      /**
       * Formats the prompt given the input values and returns a formatted
       * prompt value.
       * @param values The input values to format the prompt.
       * @returns A Promise that resolves to a formatted prompt value.
       */
      async formatPromptValue(values) {
        const formattedPrompt = await this.format(values);
        return new StringPromptValue(formattedPrompt);
      }
    };
  }
});

// node_modules/mustache/mustache.mjs
function isFunction(object) {
  return typeof object === "function";
}
function typeStr(obj) {
  return isArray(obj) ? "array" : typeof obj;
}
function escapeRegExp(string) {
  return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function hasProperty(obj, propName) {
  return obj != null && typeof obj === "object" && propName in obj;
}
function primitiveHasOwnProperty(primitive, propName) {
  return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName);
}
function testRegExp(re, string) {
  return regExpTest.call(re, string);
}
function isWhitespace(string) {
  return !testRegExp(nonSpaceRe, string);
}
function escapeHtml(string) {
  return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s4) {
    return entityMap[s4];
  });
}
function parseTemplate(template, tags) {
  if (!template)
    return [];
  var lineHasNonSpace = false;
  var sections = [];
  var tokens = [];
  var spaces = [];
  var hasTag = false;
  var nonSpace = false;
  var indentation = "";
  var tagIndex = 0;
  function stripSpace() {
    if (hasTag && !nonSpace) {
      while (spaces.length)
        delete tokens[spaces.pop()];
    } else {
      spaces = [];
    }
    hasTag = false;
    nonSpace = false;
  }
  var openingTagRe, closingTagRe, closingCurlyRe;
  function compileTags(tagsToCompile) {
    if (typeof tagsToCompile === "string")
      tagsToCompile = tagsToCompile.split(spaceRe, 2);
    if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
      throw new Error("Invalid tags: " + tagsToCompile);
    openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*");
    closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1]));
    closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1]));
  }
  compileTags(tags || mustache.tags);
  var scanner = new Scanner(template);
  var start, type, value, chr, token, openSection;
  while (!scanner.eos()) {
    start = scanner.pos;
    value = scanner.scanUntil(openingTagRe);
    if (value) {
      for (var i3 = 0, valueLength = value.length; i3 < valueLength; ++i3) {
        chr = value.charAt(i3);
        if (isWhitespace(chr)) {
          spaces.push(tokens.length);
          indentation += chr;
        } else {
          nonSpace = true;
          lineHasNonSpace = true;
          indentation += " ";
        }
        tokens.push(["text", chr, start, start + 1]);
        start += 1;
        if (chr === "\n") {
          stripSpace();
          indentation = "";
          tagIndex = 0;
          lineHasNonSpace = false;
        }
      }
    }
    if (!scanner.scan(openingTagRe))
      break;
    hasTag = true;
    type = scanner.scan(tagRe) || "name";
    scanner.scan(whiteRe);
    if (type === "=") {
      value = scanner.scanUntil(equalsRe);
      scanner.scan(equalsRe);
      scanner.scanUntil(closingTagRe);
    } else if (type === "{") {
      value = scanner.scanUntil(closingCurlyRe);
      scanner.scan(curlyRe);
      scanner.scanUntil(closingTagRe);
      type = "&";
    } else {
      value = scanner.scanUntil(closingTagRe);
    }
    if (!scanner.scan(closingTagRe))
      throw new Error("Unclosed tag at " + scanner.pos);
    if (type == ">") {
      token = [type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace];
    } else {
      token = [type, value, start, scanner.pos];
    }
    tagIndex++;
    tokens.push(token);
    if (type === "#" || type === "^") {
      sections.push(token);
    } else if (type === "/") {
      openSection = sections.pop();
      if (!openSection)
        throw new Error('Unopened section "' + value + '" at ' + start);
      if (openSection[1] !== value)
        throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
    } else if (type === "name" || type === "{" || type === "&") {
      nonSpace = true;
    } else if (type === "=") {
      compileTags(value);
    }
  }
  stripSpace();
  openSection = sections.pop();
  if (openSection)
    throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
  return nestTokens(squashTokens(tokens));
}
function squashTokens(tokens) {
  var squashedTokens = [];
  var token, lastToken;
  for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) {
    token = tokens[i3];
    if (token) {
      if (token[0] === "text" && lastToken && lastToken[0] === "text") {
        lastToken[1] += token[1];
        lastToken[3] = token[3];
      } else {
        squashedTokens.push(token);
        lastToken = token;
      }
    }
  }
  return squashedTokens;
}
function nestTokens(tokens) {
  var nestedTokens = [];
  var collector = nestedTokens;
  var sections = [];
  var token, section;
  for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) {
    token = tokens[i3];
    switch (token[0]) {
      case "#":
      case "^":
        collector.push(token);
        sections.push(token);
        collector = token[4] = [];
        break;
      case "/":
        section = sections.pop();
        section[5] = token[2];
        collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
        break;
      default:
        collector.push(token);
    }
  }
  return nestedTokens;
}
function Scanner(string) {
  this.string = string;
  this.tail = string;
  this.pos = 0;
}
function Context(view, parentContext) {
  this.view = view;
  this.cache = { ".": this.view };
  this.parent = parentContext;
}
function Writer() {
  this.templateCache = {
    _cache: {},
    set: function set(key, value) {
      this._cache[key] = value;
    },
    get: function get4(key) {
      return this._cache[key];
    },
    clear: function clear() {
      this._cache = {};
    }
  };
}
var objectToString, isArray, regExpTest, nonSpaceRe, entityMap, whiteRe, spaceRe, equalsRe, curlyRe, tagRe, mustache, defaultWriter, mustache_default;
var init_mustache = __esm({
  "node_modules/mustache/mustache.mjs"() {
    objectToString = Object.prototype.toString;
    isArray = Array.isArray || function isArrayPolyfill(object) {
      return objectToString.call(object) === "[object Array]";
    };
    regExpTest = RegExp.prototype.test;
    nonSpaceRe = /\S/;
    entityMap = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;",
      "/": "&#x2F;",
      "`": "&#x60;",
      "=": "&#x3D;"
    };
    whiteRe = /\s*/;
    spaceRe = /\s+/;
    equalsRe = /\s*=/;
    curlyRe = /\s*\}/;
    tagRe = /#|\^|\/|>|\{|&|=|!/;
    Scanner.prototype.eos = function eos() {
      return this.tail === "";
    };
    Scanner.prototype.scan = function scan(re) {
      var match2 = this.tail.match(re);
      if (!match2 || match2.index !== 0)
        return "";
      var string = match2[0];
      this.tail = this.tail.substring(string.length);
      this.pos += string.length;
      return string;
    };
    Scanner.prototype.scanUntil = function scanUntil(re) {
      var index2 = this.tail.search(re), match2;
      switch (index2) {
        case -1:
          match2 = this.tail;
          this.tail = "";
          break;
        case 0:
          match2 = "";
          break;
        default:
          match2 = this.tail.substring(0, index2);
          this.tail = this.tail.substring(index2);
      }
      this.pos += match2.length;
      return match2;
    };
    Context.prototype.push = function push(view) {
      return new Context(view, this);
    };
    Context.prototype.lookup = function lookup(name) {
      var cache2 = this.cache;
      var value;
      if (cache2.hasOwnProperty(name)) {
        value = cache2[name];
      } else {
        var context = this, intermediateValue, names, index2, lookupHit = false;
        while (context) {
          if (name.indexOf(".") > 0) {
            intermediateValue = context.view;
            names = name.split(".");
            index2 = 0;
            while (intermediateValue != null && index2 < names.length) {
              if (index2 === names.length - 1)
                lookupHit = hasProperty(intermediateValue, names[index2]) || primitiveHasOwnProperty(intermediateValue, names[index2]);
              intermediateValue = intermediateValue[names[index2++]];
            }
          } else {
            intermediateValue = context.view[name];
            lookupHit = hasProperty(context.view, name);
          }
          if (lookupHit) {
            value = intermediateValue;
            break;
          }
          context = context.parent;
        }
        cache2[name] = value;
      }
      if (isFunction(value))
        value = value.call(this.view);
      return value;
    };
    Writer.prototype.clearCache = function clearCache() {
      if (typeof this.templateCache !== "undefined") {
        this.templateCache.clear();
      }
    };
    Writer.prototype.parse = function parse(template, tags) {
      var cache2 = this.templateCache;
      var cacheKey = template + ":" + (tags || mustache.tags).join(":");
      var isCacheEnabled = typeof cache2 !== "undefined";
      var tokens = isCacheEnabled ? cache2.get(cacheKey) : void 0;
      if (tokens == void 0) {
        tokens = parseTemplate(template, tags);
        isCacheEnabled && cache2.set(cacheKey, tokens);
      }
      return tokens;
    };
    Writer.prototype.render = function render(template, view, partials, config) {
      var tags = this.getConfigTags(config);
      var tokens = this.parse(template, tags);
      var context = view instanceof Context ? view : new Context(view, void 0);
      return this.renderTokens(tokens, context, partials, template, config);
    };
    Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config) {
      var buffer = "";
      var token, symbol, value;
      for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) {
        value = void 0;
        token = tokens[i3];
        symbol = token[0];
        if (symbol === "#")
          value = this.renderSection(token, context, partials, originalTemplate, config);
        else if (symbol === "^")
          value = this.renderInverted(token, context, partials, originalTemplate, config);
        else if (symbol === ">")
          value = this.renderPartial(token, context, partials, config);
        else if (symbol === "&")
          value = this.unescapedValue(token, context);
        else if (symbol === "name")
          value = this.escapedValue(token, context, config);
        else if (symbol === "text")
          value = this.rawValue(token);
        if (value !== void 0)
          buffer += value;
      }
      return buffer;
    };
    Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config) {
      var self2 = this;
      var buffer = "";
      var value = context.lookup(token[1]);
      function subRender(template) {
        return self2.render(template, context, partials, config);
      }
      if (!value)
        return;
      if (isArray(value)) {
        for (var j3 = 0, valueLength = value.length; j3 < valueLength; ++j3) {
          buffer += this.renderTokens(token[4], context.push(value[j3]), partials, originalTemplate, config);
        }
      } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") {
        buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
      } else if (isFunction(value)) {
        if (typeof originalTemplate !== "string")
          throw new Error("Cannot use higher-order sections without the original template");
        value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
        if (value != null)
          buffer += value;
      } else {
        buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
      }
      return buffer;
    };
    Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config) {
      var value = context.lookup(token[1]);
      if (!value || isArray(value) && value.length === 0)
        return this.renderTokens(token[4], context, partials, originalTemplate, config);
    };
    Writer.prototype.indentPartial = function indentPartial(partial, indentation, lineHasNonSpace) {
      var filteredIndentation = indentation.replace(/[^ \t]/g, "");
      var partialByNl = partial.split("\n");
      for (var i3 = 0; i3 < partialByNl.length; i3++) {
        if (partialByNl[i3].length && (i3 > 0 || !lineHasNonSpace)) {
          partialByNl[i3] = filteredIndentation + partialByNl[i3];
        }
      }
      return partialByNl.join("\n");
    };
    Writer.prototype.renderPartial = function renderPartial(token, context, partials, config) {
      if (!partials)
        return;
      var tags = this.getConfigTags(config);
      var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
      if (value != null) {
        var lineHasNonSpace = token[6];
        var tagIndex = token[5];
        var indentation = token[4];
        var indentedValue = value;
        if (tagIndex == 0 && indentation) {
          indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
        }
        var tokens = this.parse(indentedValue, tags);
        return this.renderTokens(tokens, context, partials, indentedValue, config);
      }
    };
    Writer.prototype.unescapedValue = function unescapedValue(token, context) {
      var value = context.lookup(token[1]);
      if (value != null)
        return value;
    };
    Writer.prototype.escapedValue = function escapedValue(token, context, config) {
      var escape2 = this.getConfigEscape(config) || mustache.escape;
      var value = context.lookup(token[1]);
      if (value != null)
        return typeof value === "number" && escape2 === mustache.escape ? String(value) : escape2(value);
    };
    Writer.prototype.rawValue = function rawValue(token) {
      return token[1];
    };
    Writer.prototype.getConfigTags = function getConfigTags(config) {
      if (isArray(config)) {
        return config;
      } else if (config && typeof config === "object") {
        return config.tags;
      } else {
        return void 0;
      }
    };
    Writer.prototype.getConfigEscape = function getConfigEscape(config) {
      if (config && typeof config === "object" && !isArray(config)) {
        return config.escape;
      } else {
        return void 0;
      }
    };
    mustache = {
      name: "mustache.js",
      version: "4.2.0",
      tags: ["{{", "}}"],
      clearCache: void 0,
      escape: void 0,
      parse: void 0,
      render: void 0,
      Scanner: void 0,
      Context: void 0,
      Writer: void 0,
      /**
       * Allows a user to override the default caching strategy, by providing an
       * object with set, get and clear methods. This can also be used to disable
       * the cache by setting it to the literal `undefined`.
       */
      set templateCache(cache2) {
        defaultWriter.templateCache = cache2;
      },
      /**
       * Gets the default or overridden caching object from the default writer.
       */
      get templateCache() {
        return defaultWriter.templateCache;
      }
    };
    defaultWriter = new Writer();
    mustache.clearCache = function clearCache2() {
      return defaultWriter.clearCache();
    };
    mustache.parse = function parse2(template, tags) {
      return defaultWriter.parse(template, tags);
    };
    mustache.render = function render2(template, view, partials, config) {
      if (typeof template !== "string") {
        throw new TypeError('Invalid template! Template should be a "string" but "' + typeStr(template) + '" was given as the first argument for mustache#render(template, view, partials)');
      }
      return defaultWriter.render(template, view, partials, config);
    };
    mustache.escape = escapeHtml;
    mustache.Scanner = Scanner;
    mustache.Context = Context;
    mustache.Writer = Writer;
    mustache_default = mustache;
  }
});

// node_modules/@langchain/core/dist/prompts/template.js
function configureMustache() {
  mustache_default.escape = (text) => text;
}
var parseFString, mustacheTemplateToNodes, parseMustache, interpolateFString, interpolateMustache, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate, parseTemplate2, checkValidTemplate;
var init_template = __esm({
  "node_modules/@langchain/core/dist/prompts/template.js"() {
    init_mustache();
    init_errors();
    parseFString = (template) => {
      const chars = template.split("");
      const nodes = [];
      const nextBracket = (bracket, start) => {
        for (let i4 = start; i4 < chars.length; i4 += 1) {
          if (bracket.includes(chars[i4])) {
            return i4;
          }
        }
        return -1;
      };
      let i3 = 0;
      while (i3 < chars.length) {
        if (chars[i3] === "{" && i3 + 1 < chars.length && chars[i3 + 1] === "{") {
          nodes.push({ type: "literal", text: "{" });
          i3 += 2;
        } else if (chars[i3] === "}" && i3 + 1 < chars.length && chars[i3 + 1] === "}") {
          nodes.push({ type: "literal", text: "}" });
          i3 += 2;
        } else if (chars[i3] === "{") {
          const j3 = nextBracket("}", i3);
          if (j3 < 0) {
            throw new Error("Unclosed '{' in template.");
          }
          nodes.push({
            type: "variable",
            name: chars.slice(i3 + 1, j3).join("")
          });
          i3 = j3 + 1;
        } else if (chars[i3] === "}") {
          throw new Error("Single '}' in template.");
        } else {
          const next = nextBracket("{}", i3);
          const text = (next < 0 ? chars.slice(i3) : chars.slice(i3, next)).join("");
          nodes.push({ type: "literal", text });
          i3 = next < 0 ? chars.length : next;
        }
      }
      return nodes;
    };
    mustacheTemplateToNodes = (template) => template.map((temp) => {
      if (temp[0] === "name") {
        const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1];
        return { type: "variable", name };
      } else if (["#", "&", "^", ">"].includes(temp[0])) {
        return { type: "variable", name: temp[1] };
      } else {
        return { type: "literal", text: temp[1] };
      }
    });
    parseMustache = (template) => {
      configureMustache();
      const parsed = mustache_default.parse(template);
      return mustacheTemplateToNodes(parsed);
    };
    interpolateFString = (template, values) => {
      return parseFString(template).reduce((res, node) => {
        if (node.type === "variable") {
          if (node.name in values) {
            const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]);
            return res + stringValue;
          }
          throw new Error(`(f-string) Missing value for input ${node.name}`);
        }
        return res + node.text;
      }, "");
    };
    interpolateMustache = (template, values) => {
      configureMustache();
      return mustache_default.render(template, values);
    };
    DEFAULT_FORMATTER_MAPPING = {
      "f-string": interpolateFString,
      mustache: interpolateMustache
    };
    DEFAULT_PARSER_MAPPING = {
      "f-string": parseFString,
      mustache: parseMustache
    };
    renderTemplate = (template, templateFormat, inputValues) => {
      try {
        return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);
      } catch (e3) {
        const error = addLangChainErrorFields(e3, "INVALID_PROMPT_INPUT");
        throw error;
      }
    };
    parseTemplate2 = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template);
    checkValidTemplate = (template, templateFormat, inputVariables) => {
      if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {
        const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);
        throw new Error(`Invalid template format. Got \`${templateFormat}\`;
                         should be one of ${validFormats}`);
      }
      try {
        const dummyInputs = inputVariables.reduce((acc, v5) => {
          acc[v5] = "foo";
          return acc;
        }, {});
        if (Array.isArray(template)) {
          template.forEach((message) => {
            if (message.type === "text") {
              renderTemplate(message.text, templateFormat, dummyInputs);
            } else if (message.type === "image_url") {
              if (typeof message.image_url === "string") {
                renderTemplate(message.image_url, templateFormat, dummyInputs);
              } else {
                const imageUrl = message.image_url.url;
                renderTemplate(imageUrl, templateFormat, dummyInputs);
              }
            } else {
              throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`);
            }
          });
        } else {
          renderTemplate(template, templateFormat, dummyInputs);
        }
      } catch (e3) {
        throw new Error(`Invalid prompt schema: ${e3.message}`);
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/prompt.js
var prompt_exports = {};
__export(prompt_exports, {
  PromptTemplate: () => PromptTemplate
});
var PromptTemplate;
var init_prompt = __esm({
  "node_modules/@langchain/core/dist/prompts/prompt.js"() {
    init_string3();
    init_template();
    PromptTemplate = class extends BaseStringPromptTemplate {
      static lc_name() {
        return "PromptTemplate";
      }
      constructor(input) {
        super(input);
        Object.defineProperty(this, "template", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "templateFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "f-string"
        });
        Object.defineProperty(this, "validateTemplate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "additionalContentFields", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (input.templateFormat === "mustache" && input.validateTemplate === void 0) {
          this.validateTemplate = false;
        }
        Object.assign(this, input);
        if (this.validateTemplate) {
          if (this.templateFormat === "mustache") {
            throw new Error("Mustache templates cannot be validated.");
          }
          let totalInputVariables = this.inputVariables;
          if (this.partialVariables) {
            totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));
          }
          checkValidTemplate(this.template, this.templateFormat, totalInputVariables);
        }
      }
      _getPromptType() {
        return "prompt";
      }
      /**
       * Formats the prompt template with the provided values.
       * @param values The values to be used to format the prompt template.
       * @returns A promise that resolves to a string which is the formatted prompt.
       */
      async format(values) {
        const allValues = await this.mergePartialAndUserVariables(values);
        return renderTemplate(this.template, this.templateFormat, allValues);
      }
      /**
       * Take examples in list format with prefix and suffix to create a prompt.
       *
       * Intended to be used a a way to dynamically create a prompt from examples.
       *
       * @param examples - List of examples to use in the prompt.
       * @param suffix - String to go after the list of examples. Should generally set up the user's input.
       * @param inputVariables - A list of variable names the final prompt template will expect
       * @param exampleSeparator - The separator to use in between examples
       * @param prefix - String that should go before any examples. Generally includes examples.
       *
       * @returns The final prompt template generated.
       */
      static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") {
        const template = [prefix, ...examples, suffix].join(exampleSeparator);
        return new PromptTemplate({
          inputVariables,
          template
        });
      }
      static fromTemplate(template, options) {
        const { templateFormat = "f-string", ...rest } = options ?? {};
        const names = /* @__PURE__ */ new Set();
        parseTemplate2(template, templateFormat).forEach((node) => {
          if (node.type === "variable") {
            names.add(node.name);
          }
        });
        return new PromptTemplate({
          // Rely on extracted types
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          inputVariables: [...names],
          templateFormat,
          template,
          ...rest
        });
      }
      /**
       * Partially applies values to the prompt template.
       * @param values The values to be partially applied to the prompt template.
       * @returns A new instance of PromptTemplate with the partially applied values.
       */
      async partial(values) {
        const newInputVariables = this.inputVariables.filter((iv) => !(iv in values));
        const newPartialVariables = {
          ...this.partialVariables ?? {},
          ...values
        };
        const promptDict = {
          ...this,
          inputVariables: newInputVariables,
          partialVariables: newPartialVariables
        };
        return new PromptTemplate(promptDict);
      }
      serialize() {
        if (this.outputParser !== void 0) {
          throw new Error("Cannot serialize a prompt template with an output parser");
        }
        return {
          _type: this._getPromptType(),
          input_variables: this.inputVariables,
          template: this.template,
          template_format: this.templateFormat
        };
      }
      static async deserialize(data) {
        if (!data.template) {
          throw new Error("Prompt template must have a template");
        }
        const res = new PromptTemplate({
          inputVariables: data.input_variables,
          template: data.template,
          templateFormat: data.template_format
        });
        return res;
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/image.js
var ImagePromptTemplate;
var init_image = __esm({
  "node_modules/@langchain/core/dist/prompts/image.js"() {
    init_prompt_values();
    init_base6();
    init_template();
    ImagePromptTemplate = class extends BasePromptTemplate {
      static lc_name() {
        return "ImagePromptTemplate";
      }
      constructor(input) {
        super(input);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompts", "image"]
        });
        Object.defineProperty(this, "template", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "templateFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "f-string"
        });
        Object.defineProperty(this, "validateTemplate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "additionalContentFields", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.template = input.template;
        this.templateFormat = input.templateFormat ?? this.templateFormat;
        this.validateTemplate = input.validateTemplate ?? this.validateTemplate;
        this.additionalContentFields = input.additionalContentFields;
        if (this.validateTemplate) {
          let totalInputVariables = this.inputVariables;
          if (this.partialVariables) {
            totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));
          }
          checkValidTemplate([
            { type: "image_url", image_url: this.template }
          ], this.templateFormat, totalInputVariables);
        }
      }
      _getPromptType() {
        return "prompt";
      }
      /**
       * Partially applies values to the prompt template.
       * @param values The values to be partially applied to the prompt template.
       * @returns A new instance of ImagePromptTemplate with the partially applied values.
       */
      async partial(values) {
        const newInputVariables = this.inputVariables.filter((iv) => !(iv in values));
        const newPartialVariables = {
          ...this.partialVariables ?? {},
          ...values
        };
        const promptDict = {
          ...this,
          inputVariables: newInputVariables,
          partialVariables: newPartialVariables
        };
        return new ImagePromptTemplate(promptDict);
      }
      /**
       * Formats the prompt template with the provided values.
       * @param values The values to be used to format the prompt template.
       * @returns A promise that resolves to a string which is the formatted prompt.
       */
      async format(values) {
        const formatted = {};
        for (const [key, value] of Object.entries(this.template)) {
          if (typeof value === "string") {
            formatted[key] = renderTemplate(value, this.templateFormat, values);
          } else {
            formatted[key] = value;
          }
        }
        const url = values.url || formatted.url;
        const detail = values.detail || formatted.detail;
        if (!url) {
          throw new Error("Must provide either an image URL.");
        }
        if (typeof url !== "string") {
          throw new Error("url must be a string.");
        }
        const output = { url };
        if (detail) {
          output.detail = detail;
        }
        return output;
      }
      /**
       * Formats the prompt given the input values and returns a formatted
       * prompt value.
       * @param values The input values to format the prompt.
       * @returns A Promise that resolves to a formatted prompt value.
       */
      async formatPromptValue(values) {
        const formattedPrompt = await this.format(values);
        return new ImagePromptValue(formattedPrompt);
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/chat.js
function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) {
  return typeof baseMessagePromptTemplateLike.formatMessages === "function";
}
function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) {
  if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) {
    return messagePromptTemplateLike;
  }
  if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") {
    const messageContent = messagePromptTemplateLike[1];
    if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") {
      const variableName = messageContent.slice(2, -2);
      return new MessagesPlaceholder({ variableName, optional: true });
    } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") {
      const variableName = messageContent.slice(1, -1);
      return new MessagesPlaceholder({ variableName, optional: true });
    }
    throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`);
  }
  const message = coerceMessageLikeToMessage(messagePromptTemplateLike);
  let templateData;
  if (typeof message.content === "string") {
    templateData = message.content;
  } else {
    templateData = message.content.map((item) => {
      if ("text" in item) {
        return { ...item, text: item.text };
      } else if ("image_url" in item) {
        return { ...item, image_url: item.image_url };
      } else {
        return item;
      }
    });
  }
  if (message._getType() === "human") {
    return HumanMessagePromptTemplate.fromTemplate(templateData, extra);
  } else if (message._getType() === "ai") {
    return AIMessagePromptTemplate.fromTemplate(templateData, extra);
  } else if (message._getType() === "system") {
    return SystemMessagePromptTemplate.fromTemplate(templateData, extra);
  } else if (ChatMessage.isInstance(message)) {
    return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra);
  } else {
    throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`);
  }
}
function isMessagesPlaceholder(x2) {
  return x2.constructor.lc_name() === "MessagesPlaceholder";
}
var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate;
var init_chat2 = __esm({
  "node_modules/@langchain/core/dist/prompts/chat.js"() {
    init_messages2();
    init_prompt_values();
    init_base4();
    init_string3();
    init_base6();
    init_prompt();
    init_image();
    init_template();
    init_errors();
    BaseMessagePromptTemplate = class extends Runnable {
      constructor() {
        super(...arguments);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompts", "chat"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
      }
      /**
       * Calls the formatMessages method with the provided input and options.
       * @param input Input for the formatMessages method
       * @param options Optional BaseCallbackConfig
       * @returns Formatted output messages
       */
      async invoke(input, options) {
        return this._callWithConfig((input2) => this.formatMessages(input2), input, { ...options, runType: "prompt" });
      }
    };
    MessagesPlaceholder = class extends BaseMessagePromptTemplate {
      static lc_name() {
        return "MessagesPlaceholder";
      }
      constructor(fields) {
        if (typeof fields === "string") {
          fields = { variableName: fields };
        }
        super(fields);
        Object.defineProperty(this, "variableName", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "optional", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.variableName = fields.variableName;
        this.optional = fields.optional ?? false;
      }
      get inputVariables() {
        return [this.variableName];
      }
      async formatMessages(values) {
        const input = values[this.variableName];
        if (this.optional && !input) {
          return [];
        } else if (!input) {
          const error = new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);
          error.name = "InputFormatError";
          throw error;
        }
        let formattedMessages;
        try {
          if (Array.isArray(input)) {
            formattedMessages = input.map(coerceMessageLikeToMessage);
          } else {
            formattedMessages = [coerceMessageLikeToMessage(input)];
          }
        } catch (e3) {
          const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2);
          const error = new Error([
            `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,
            `Received value: ${readableInput}`,
            `Additional message: ${e3.message}`
          ].join("\n\n"));
          error.name = "InputFormatError";
          error.lc_error_code = e3.lc_error_code;
          throw error;
        }
        return formattedMessages;
      }
    };
    BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate {
      constructor(fields) {
        if (!("prompt" in fields)) {
          fields = { prompt: fields };
        }
        super(fields);
        Object.defineProperty(this, "prompt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.prompt = fields.prompt;
      }
      get inputVariables() {
        return this.prompt.inputVariables;
      }
      async formatMessages(values) {
        return [await this.format(values)];
      }
    };
    BaseChatPromptTemplate = class extends BasePromptTemplate {
      constructor(input) {
        super(input);
      }
      async format(values) {
        return (await this.formatPromptValue(values)).toString();
      }
      async formatPromptValue(values) {
        const resultMessages = await this.formatMessages(values);
        return new ChatPromptValue(resultMessages);
      }
    };
    ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate {
      static lc_name() {
        return "ChatMessagePromptTemplate";
      }
      constructor(fields, role) {
        if (!("prompt" in fields)) {
          fields = { prompt: fields, role };
        }
        super(fields);
        Object.defineProperty(this, "role", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.role = fields.role;
      }
      async format(values) {
        return new ChatMessage(await this.prompt.format(values), this.role);
      }
      static fromTemplate(template, role, options) {
        return new this(PromptTemplate.fromTemplate(template, {
          templateFormat: options?.templateFormat
        }), role);
      }
    };
    _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate {
      static _messageClass() {
        throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate");
      }
      constructor(fields, additionalOptions) {
        if (!("prompt" in fields)) {
          fields = { prompt: fields };
        }
        super(fields);
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompts", "chat"]
        });
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "inputVariables", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: []
        });
        Object.defineProperty(this, "additionalOptions", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: {}
        });
        Object.defineProperty(this, "prompt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "messageClass", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "chatMessageClass", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.prompt = fields.prompt;
        if (Array.isArray(this.prompt)) {
          let inputVariables = [];
          this.prompt.forEach((prompt) => {
            if ("inputVariables" in prompt) {
              inputVariables = inputVariables.concat(prompt.inputVariables);
            }
          });
          this.inputVariables = inputVariables;
        } else {
          this.inputVariables = this.prompt.inputVariables;
        }
        this.additionalOptions = additionalOptions ?? this.additionalOptions;
      }
      createMessage(content) {
        const constructor = this.constructor;
        if (constructor._messageClass()) {
          const MsgClass = constructor._messageClass();
          return new MsgClass({ content });
        } else if (constructor.chatMessageClass) {
          const MsgClass = constructor.chatMessageClass();
          return new MsgClass({
            content,
            role: this.getRoleFromMessageClass(MsgClass.lc_name())
          });
        } else {
          throw new Error("No message class defined");
        }
      }
      getRoleFromMessageClass(name) {
        switch (name) {
          case "HumanMessage":
            return "human";
          case "AIMessage":
            return "ai";
          case "SystemMessage":
            return "system";
          case "ChatMessage":
            return "chat";
          default:
            throw new Error("Invalid message class name");
        }
      }
      static fromTemplate(template, additionalOptions) {
        if (typeof template === "string") {
          return new this(PromptTemplate.fromTemplate(template, additionalOptions));
        }
        const prompt = [];
        for (const item of template) {
          if (typeof item === "string" || typeof item === "object" && "text" in item) {
            let text = "";
            if (typeof item === "string") {
              text = item;
            } else if (typeof item.text === "string") {
              text = item.text ?? "";
            }
            const options = {
              ...additionalOptions,
              ...typeof item !== "string" ? { additionalContentFields: item } : {}
            };
            prompt.push(PromptTemplate.fromTemplate(text, options));
          } else if (typeof item === "object" && "image_url" in item) {
            let imgTemplate = item.image_url ?? "";
            let imgTemplateObject;
            let inputVariables = [];
            if (typeof imgTemplate === "string") {
              let parsedTemplate;
              if (additionalOptions?.templateFormat === "mustache") {
                parsedTemplate = parseMustache(imgTemplate);
              } else {
                parsedTemplate = parseFString(imgTemplate);
              }
              const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []);
              if ((variables?.length ?? 0) > 0) {
                if (variables.length > 1) {
                  throw new Error(`Only one format variable allowed per image template.
Got: ${variables}
From: ${imgTemplate}`);
                }
                inputVariables = [variables[0]];
              } else {
                inputVariables = [];
              }
              imgTemplate = { url: imgTemplate };
              imgTemplateObject = new ImagePromptTemplate({
                template: imgTemplate,
                inputVariables,
                templateFormat: additionalOptions?.templateFormat,
                additionalContentFields: item
              });
            } else if (typeof imgTemplate === "object") {
              if ("url" in imgTemplate) {
                let parsedTemplate;
                if (additionalOptions?.templateFormat === "mustache") {
                  parsedTemplate = parseMustache(imgTemplate.url);
                } else {
                  parsedTemplate = parseFString(imgTemplate.url);
                }
                inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []);
              } else {
                inputVariables = [];
              }
              imgTemplateObject = new ImagePromptTemplate({
                template: imgTemplate,
                inputVariables,
                templateFormat: additionalOptions?.templateFormat,
                additionalContentFields: item
              });
            } else {
              throw new Error("Invalid image template");
            }
            prompt.push(imgTemplateObject);
          }
        }
        return new this({ prompt, additionalOptions });
      }
      async format(input) {
        if (this.prompt instanceof BaseStringPromptTemplate) {
          const text = await this.prompt.format(input);
          return this.createMessage(text);
        } else {
          const content = [];
          for (const prompt of this.prompt) {
            let inputs = {};
            if (!("inputVariables" in prompt)) {
              throw new Error(`Prompt ${prompt} does not have inputVariables defined.`);
            }
            for (const item of prompt.inputVariables) {
              if (!inputs) {
                inputs = { [item]: input[item] };
              }
              inputs = { ...inputs, [item]: input[item] };
            }
            if (prompt instanceof BaseStringPromptTemplate) {
              const formatted = await prompt.format(inputs);
              let additionalContentFields;
              if ("additionalContentFields" in prompt) {
                additionalContentFields = prompt.additionalContentFields;
              }
              content.push({
                ...additionalContentFields,
                type: "text",
                text: formatted
              });
            } else if (prompt instanceof ImagePromptTemplate) {
              const formatted = await prompt.format(inputs);
              let additionalContentFields;
              if ("additionalContentFields" in prompt) {
                additionalContentFields = prompt.additionalContentFields;
              }
              content.push({
                ...additionalContentFields,
                type: "image_url",
                image_url: formatted
              });
            }
          }
          return this.createMessage(content);
        }
      }
      async formatMessages(values) {
        return [await this.format(values)];
      }
    };
    HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {
      static _messageClass() {
        return HumanMessage;
      }
      static lc_name() {
        return "HumanMessagePromptTemplate";
      }
    };
    AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {
      static _messageClass() {
        return AIMessage;
      }
      static lc_name() {
        return "AIMessagePromptTemplate";
      }
    };
    SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate {
      static _messageClass() {
        return SystemMessage;
      }
      static lc_name() {
        return "SystemMessagePromptTemplate";
      }
    };
    ChatPromptTemplate = class extends BaseChatPromptTemplate {
      static lc_name() {
        return "ChatPromptTemplate";
      }
      get lc_aliases() {
        return {
          promptMessages: "messages"
        };
      }
      constructor(input) {
        super(input);
        Object.defineProperty(this, "promptMessages", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "validateTemplate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "templateFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "f-string"
        });
        if (input.templateFormat === "mustache" && input.validateTemplate === void 0) {
          this.validateTemplate = false;
        }
        Object.assign(this, input);
        if (this.validateTemplate) {
          const inputVariablesMessages = /* @__PURE__ */ new Set();
          for (const promptMessage of this.promptMessages) {
            if (promptMessage instanceof BaseMessage)
              continue;
            for (const inputVariable of promptMessage.inputVariables) {
              inputVariablesMessages.add(inputVariable);
            }
          }
          const totalInputVariables = this.inputVariables;
          const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables);
          const difference = new Set([...inputVariablesInstance].filter((x2) => !inputVariablesMessages.has(x2)));
          if (difference.size > 0) {
            throw new Error(`Input variables \`${[
              ...difference
            ]}\` are not used in any of the prompt messages.`);
          }
          const otherDifference = new Set([...inputVariablesMessages].filter((x2) => !inputVariablesInstance.has(x2)));
          if (otherDifference.size > 0) {
            throw new Error(`Input variables \`${[
              ...otherDifference
            ]}\` are used in prompt messages but not in the prompt template.`);
          }
        }
      }
      _getPromptType() {
        return "chat";
      }
      async _parseImagePrompts(message, inputValues) {
        if (typeof message.content === "string") {
          return message;
        }
        const formattedMessageContent = await Promise.all(message.content.map(async (item) => {
          if (item.type !== "image_url") {
            return item;
          }
          let imageUrl = "";
          if (typeof item.image_url === "string") {
            imageUrl = item.image_url;
          } else {
            imageUrl = item.image_url.url;
          }
          const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, {
            templateFormat: this.templateFormat
          });
          const formattedUrl = await promptTemplatePlaceholder.format(inputValues);
          if (typeof item.image_url !== "string" && "url" in item.image_url) {
            item.image_url.url = formattedUrl;
          } else {
            item.image_url = formattedUrl;
          }
          return item;
        }));
        message.content = formattedMessageContent;
        return message;
      }
      async formatMessages(values) {
        const allValues = await this.mergePartialAndUserVariables(values);
        let resultMessages = [];
        for (const promptMessage of this.promptMessages) {
          if (promptMessage instanceof BaseMessage) {
            resultMessages.push(await this._parseImagePrompts(promptMessage, allValues));
          } else {
            const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => {
              if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) {
                const error = addLangChainErrorFields(new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT");
                throw error;
              }
              acc[inputVariable] = allValues[inputVariable];
              return acc;
            }, {});
            const message = await promptMessage.formatMessages(inputValues);
            resultMessages = resultMessages.concat(message);
          }
        }
        return resultMessages;
      }
      async partial(values) {
        const newInputVariables = this.inputVariables.filter((iv) => !(iv in values));
        const newPartialVariables = {
          ...this.partialVariables ?? {},
          ...values
        };
        const promptDict = {
          ...this,
          inputVariables: newInputVariables,
          partialVariables: newPartialVariables
        };
        return new ChatPromptTemplate(promptDict);
      }
      static fromTemplate(template, options) {
        const prompt = PromptTemplate.fromTemplate(template, options);
        const humanTemplate = new HumanMessagePromptTemplate({ prompt });
        return this.fromMessages([humanTemplate]);
      }
      /**
       * Create a chat model-specific prompt from individual chat messages
       * or message-like tuples.
       * @param promptMessages Messages to be passed to the chat model
       * @returns A new ChatPromptTemplate
       */
      static fromMessages(promptMessages, extra) {
        const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(
          // eslint-disable-next-line no-instanceof/no-instanceof
          promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [
            _coerceMessagePromptTemplateLike(promptMessage, extra)
          ]
        ), []);
        const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => (
          // eslint-disable-next-line no-instanceof/no-instanceof
          promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc
        ), /* @__PURE__ */ Object.create(null));
        const inputVariables = /* @__PURE__ */ new Set();
        for (const promptMessage of flattenedMessages) {
          if (promptMessage instanceof BaseMessage)
            continue;
          for (const inputVariable of promptMessage.inputVariables) {
            if (inputVariable in flattenedPartialVariables) {
              continue;
            }
            inputVariables.add(inputVariable);
          }
        }
        return new this({
          ...extra,
          inputVariables: [...inputVariables],
          promptMessages: flattenedMessages,
          partialVariables: flattenedPartialVariables,
          templateFormat: extra?.templateFormat
        });
      }
      /** @deprecated Renamed to .fromMessages */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static fromPromptMessages(promptMessages) {
        return this.fromMessages(promptMessages);
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/few_shot.js
var few_shot_exports = {};
__export(few_shot_exports, {
  FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate,
  FewShotPromptTemplate: () => FewShotPromptTemplate
});
var FewShotPromptTemplate, FewShotChatMessagePromptTemplate;
var init_few_shot = __esm({
  "node_modules/@langchain/core/dist/prompts/few_shot.js"() {
    init_string3();
    init_template();
    init_prompt();
    init_chat2();
    FewShotPromptTemplate = class extends BaseStringPromptTemplate {
      constructor(input) {
        super(input);
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: false
        });
        Object.defineProperty(this, "examples", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "exampleSelector", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "examplePrompt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "suffix", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ""
        });
        Object.defineProperty(this, "exampleSeparator", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "\n\n"
        });
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ""
        });
        Object.defineProperty(this, "templateFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "f-string"
        });
        Object.defineProperty(this, "validateTemplate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.assign(this, input);
        if (this.examples !== void 0 && this.exampleSelector !== void 0) {
          throw new Error("Only one of 'examples' and 'example_selector' should be provided");
        }
        if (this.examples === void 0 && this.exampleSelector === void 0) {
          throw new Error("One of 'examples' and 'example_selector' should be provided");
        }
        if (this.validateTemplate) {
          let totalInputVariables = this.inputVariables;
          if (this.partialVariables) {
            totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));
          }
          checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables);
        }
      }
      _getPromptType() {
        return "few_shot";
      }
      static lc_name() {
        return "FewShotPromptTemplate";
      }
      async getExamples(inputVariables) {
        if (this.examples !== void 0) {
          return this.examples;
        }
        if (this.exampleSelector !== void 0) {
          return this.exampleSelector.selectExamples(inputVariables);
        }
        throw new Error("One of 'examples' and 'example_selector' should be provided");
      }
      async partial(values) {
        const newInputVariables = this.inputVariables.filter((iv) => !(iv in values));
        const newPartialVariables = {
          ...this.partialVariables ?? {},
          ...values
        };
        const promptDict = {
          ...this,
          inputVariables: newInputVariables,
          partialVariables: newPartialVariables
        };
        return new FewShotPromptTemplate(promptDict);
      }
      /**
       * Formats the prompt with the given values.
       * @param values The values to format the prompt with.
       * @returns A promise that resolves to a string representing the formatted prompt.
       */
      async format(values) {
        const allValues = await this.mergePartialAndUserVariables(values);
        const examples = await this.getExamples(allValues);
        const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example)));
        const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator);
        return renderTemplate(template, this.templateFormat, allValues);
      }
      serialize() {
        if (this.exampleSelector || !this.examples) {
          throw new Error("Serializing an example selector is not currently supported");
        }
        if (this.outputParser !== void 0) {
          throw new Error("Serializing an output parser is not currently supported");
        }
        return {
          _type: this._getPromptType(),
          input_variables: this.inputVariables,
          example_prompt: this.examplePrompt.serialize(),
          example_separator: this.exampleSeparator,
          suffix: this.suffix,
          prefix: this.prefix,
          template_format: this.templateFormat,
          examples: this.examples
        };
      }
      static async deserialize(data) {
        const { example_prompt } = data;
        if (!example_prompt) {
          throw new Error("Missing example prompt");
        }
        const examplePrompt = await PromptTemplate.deserialize(example_prompt);
        let examples;
        if (Array.isArray(data.examples)) {
          examples = data.examples;
        } else {
          throw new Error("Invalid examples format. Only list or string are supported.");
        }
        return new FewShotPromptTemplate({
          inputVariables: data.input_variables,
          examplePrompt,
          examples,
          exampleSeparator: data.example_separator,
          prefix: data.prefix,
          suffix: data.suffix,
          templateFormat: data.template_format
        });
      }
    };
    FewShotChatMessagePromptTemplate = class extends BaseChatPromptTemplate {
      _getPromptType() {
        return "few_shot_chat";
      }
      static lc_name() {
        return "FewShotChatMessagePromptTemplate";
      }
      constructor(fields) {
        super(fields);
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "examples", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "exampleSelector", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "examplePrompt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "suffix", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ""
        });
        Object.defineProperty(this, "exampleSeparator", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "\n\n"
        });
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ""
        });
        Object.defineProperty(this, "templateFormat", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "f-string"
        });
        Object.defineProperty(this, "validateTemplate", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        this.examples = fields.examples;
        this.examplePrompt = fields.examplePrompt;
        this.exampleSeparator = fields.exampleSeparator ?? "\n\n";
        this.exampleSelector = fields.exampleSelector;
        this.prefix = fields.prefix ?? "";
        this.suffix = fields.suffix ?? "";
        this.templateFormat = fields.templateFormat ?? "f-string";
        this.validateTemplate = fields.validateTemplate ?? true;
        if (this.examples !== void 0 && this.exampleSelector !== void 0) {
          throw new Error("Only one of 'examples' and 'example_selector' should be provided");
        }
        if (this.examples === void 0 && this.exampleSelector === void 0) {
          throw new Error("One of 'examples' and 'example_selector' should be provided");
        }
        if (this.validateTemplate) {
          let totalInputVariables = this.inputVariables;
          if (this.partialVariables) {
            totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables));
          }
          checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables);
        }
      }
      async getExamples(inputVariables) {
        if (this.examples !== void 0) {
          return this.examples;
        }
        if (this.exampleSelector !== void 0) {
          return this.exampleSelector.selectExamples(inputVariables);
        }
        throw new Error("One of 'examples' and 'example_selector' should be provided");
      }
      /**
       * Formats the list of values and returns a list of formatted messages.
       * @param values The values to format the prompt with.
       * @returns A promise that resolves to a string representing the formatted prompt.
       */
      async formatMessages(values) {
        const allValues = await this.mergePartialAndUserVariables(values);
        let examples = await this.getExamples(allValues);
        examples = examples.map((example) => {
          const result = {};
          this.examplePrompt.inputVariables.forEach((inputVariable) => {
            result[inputVariable] = example[inputVariable];
          });
          return result;
        });
        const messages = [];
        for (const example of examples) {
          const exampleMessages = await this.examplePrompt.formatMessages(example);
          messages.push(...exampleMessages);
        }
        return messages;
      }
      /**
       * Formats the prompt with the given values.
       * @param values The values to format the prompt with.
       * @returns A promise that resolves to a string representing the formatted prompt.
       */
      async format(values) {
        const allValues = await this.mergePartialAndUserVariables(values);
        const examples = await this.getExamples(allValues);
        const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example)));
        const exampleStrings = exampleMessages.flat().map((message) => message.content);
        const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator);
        return renderTemplate(template, this.templateFormat, allValues);
      }
      /**
       * Partially formats the prompt with the given values.
       * @param values The values to partially format the prompt with.
       * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.
       */
      async partial(values) {
        const newInputVariables = this.inputVariables.filter((variable) => !(variable in values));
        const newPartialVariables = {
          ...this.partialVariables ?? {},
          ...values
        };
        const promptDict = {
          ...this,
          inputVariables: newInputVariables,
          partialVariables: newPartialVariables
        };
        return new FewShotChatMessagePromptTemplate(promptDict);
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/base.js
var BasePromptTemplate;
var init_base6 = __esm({
  "node_modules/@langchain/core/dist/prompts/base.js"() {
    init_base4();
    BasePromptTemplate = class extends Runnable {
      get lc_attributes() {
        return {
          partialVariables: void 0
          // python doesn't support this yet
        };
      }
      constructor(input) {
        super(input);
        Object.defineProperty(this, "lc_serializable", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: true
        });
        Object.defineProperty(this, "lc_namespace", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: ["langchain_core", "prompts", this._getPromptType()]
        });
        Object.defineProperty(this, "inputVariables", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "outputParser", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "partialVariables", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        const { inputVariables } = input;
        if (inputVariables.includes("stop")) {
          throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");
        }
        Object.assign(this, input);
      }
      /**
       * Merges partial variables and user variables.
       * @param userVariables The user variables to merge with the partial variables.
       * @returns A Promise that resolves to an object containing the merged variables.
       */
      async mergePartialAndUserVariables(userVariables) {
        const partialVariables = this.partialVariables ?? {};
        const partialValues = {};
        for (const [key, value] of Object.entries(partialVariables)) {
          if (typeof value === "string") {
            partialValues[key] = value;
          } else {
            partialValues[key] = await value();
          }
        }
        const allKwargs = {
          ...partialValues,
          ...userVariables
        };
        return allKwargs;
      }
      /**
       * Invokes the prompt template with the given input and options.
       * @param input The input to invoke the prompt template with.
       * @param options Optional configuration for the callback.
       * @returns A Promise that resolves to the output of the prompt template.
       */
      async invoke(input, options) {
        const metadata = {
          ...this.metadata,
          ...options?.metadata
        };
        const tags = [...this.tags ?? [], ...options?.tags ?? []];
        return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { ...options, tags, metadata, runType: "prompt" });
      }
      /**
       * Return a json-like object representing this prompt template.
       * @deprecated
       */
      serialize() {
        throw new Error("Use .toJSON() instead");
      }
      /**
       * @deprecated
       * Load a prompt template from a json-like object describing it.
       *
       * @remarks
       * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can
       * reference remote resources that we read asynchronously with a web
       * request.
       */
      static async deserialize(data) {
        switch (data._type) {
          case "prompt": {
            const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports));
            return PromptTemplate2.deserialize(data);
          }
          case void 0: {
            const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports));
            return PromptTemplate2.deserialize({ ...data, _type: "prompt" });
          }
          case "few_shot": {
            const { FewShotPromptTemplate: FewShotPromptTemplate2 } = await Promise.resolve().then(() => (init_few_shot(), few_shot_exports));
            return FewShotPromptTemplate2.deserialize(data);
          }
          default:
            throw new Error(`Invalid prompt type in config: ${data._type}`);
        }
      }
    };
  }
});

// node_modules/@langchain/core/dist/prompts/pipeline.js
var init_pipeline2 = __esm({
  "node_modules/@langchain/core/dist/prompts/pipeline.js"() {
    init_base6();
    init_chat2();
  }
});

// node_modules/@langchain/core/dist/prompts/serde.js
var init_serde = __esm({
  "node_modules/@langchain/core/dist/prompts/serde.js"() {
  }
});

// node_modules/@langchain/core/dist/prompts/structured.js
var init_structured2 = __esm({
  "node_modules/@langchain/core/dist/prompts/structured.js"() {
    init_chat2();
  }
});

// node_modules/@langchain/core/dist/prompts/index.js
var init_prompts2 = __esm({
  "node_modules/@langchain/core/dist/prompts/index.js"() {
    init_base6();
    init_chat2();
    init_few_shot();
    init_pipeline2();
    init_prompt();
    init_serde();
    init_string3();
    init_template();
    init_image();
    init_structured2();
  }
});

// node_modules/@langchain/core/prompts.js
var init_prompts3 = __esm({
  "node_modules/@langchain/core/prompts.js"() {
    init_prompts2();
  }
});

// node_modules/@langchain/core/runnables.js
var init_runnables2 = __esm({
  "node_modules/@langchain/core/runnables.js"() {
    init_runnables();
  }
});

// node_modules/react/cjs/react.development.js
var require_react_development = __commonJS({
  "node_modules/react/cjs/react.development.js"(exports, module2) {
    "use strict";
    if (true) {
      (function() {
        "use strict";
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
        }
        var ReactVersion = "18.2.0";
        var REACT_ELEMENT_TYPE = Symbol.for("react.element");
        var REACT_PORTAL_TYPE = Symbol.for("react.portal");
        var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
        var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
        var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
        var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
        var REACT_CONTEXT_TYPE = Symbol.for("react.context");
        var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
        var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
        var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
        var REACT_MEMO_TYPE = Symbol.for("react.memo");
        var REACT_LAZY_TYPE = Symbol.for("react.lazy");
        var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
        var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
        var FAUX_ITERATOR_SYMBOL = "@@iterator";
        function getIteratorFn(maybeIterable) {
          if (maybeIterable === null || typeof maybeIterable !== "object") {
            return null;
          }
          var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
          if (typeof maybeIterator === "function") {
            return maybeIterator;
          }
          return null;
        }
        var ReactCurrentDispatcher = {
          /**
           * @internal
           * @type {ReactComponent}
           */
          current: null
        };
        var ReactCurrentBatchConfig = {
          transition: null
        };
        var ReactCurrentActQueue = {
          current: null,
          // Used to reproduce behavior of `batchedUpdates` in legacy mode.
          isBatchingLegacy: false,
          didScheduleLegacyUpdate: false
        };
        var ReactCurrentOwner = {
          /**
           * @internal
           * @type {ReactComponent}
           */
          current: null
        };
        var ReactDebugCurrentFrame = {};
        var currentExtraStackFrame = null;
        function setExtraStackFrame(stack) {
          {
            currentExtraStackFrame = stack;
          }
        }
        {
          ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
            {
              currentExtraStackFrame = stack;
            }
          };
          ReactDebugCurrentFrame.getCurrentStack = null;
          ReactDebugCurrentFrame.getStackAddendum = function() {
            var stack = "";
            if (currentExtraStackFrame) {
              stack += currentExtraStackFrame;
            }
            var impl = ReactDebugCurrentFrame.getCurrentStack;
            if (impl) {
              stack += impl() || "";
            }
            return stack;
          };
        }
        var enableScopeAPI = false;
        var enableCacheElement = false;
        var enableTransitionTracing = false;
        var enableLegacyHidden = false;
        var enableDebugTracing = false;
        var ReactSharedInternals = {
          ReactCurrentDispatcher,
          ReactCurrentBatchConfig,
          ReactCurrentOwner
        };
        {
          ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
          ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
        }
        function warn2(format) {
          {
            {
              for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
              }
              printWarning("warn", format, args);
            }
          }
        }
        function error(format) {
          {
            {
              for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                args[_key2 - 1] = arguments[_key2];
              }
              printWarning("error", format, args);
            }
          }
        }
        function printWarning(level, format, args) {
          {
            var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
            var stack = ReactDebugCurrentFrame2.getStackAddendum();
            if (stack !== "") {
              format += "%s";
              args = args.concat([stack]);
            }
            var argsWithFormat = args.map(function(item) {
              return String(item);
            });
            argsWithFormat.unshift("Warning: " + format);
            Function.prototype.apply.call(console[level], console, argsWithFormat);
          }
        }
        var didWarnStateUpdateForUnmountedComponent = {};
        function warnNoop(publicInstance, callerName) {
          {
            var _constructor = publicInstance.constructor;
            var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass";
            var warningKey = componentName + "." + callerName;
            if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
              return;
            }
            error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName);
            didWarnStateUpdateForUnmountedComponent[warningKey] = true;
          }
        }
        var ReactNoopUpdateQueue = {
          /**
           * Checks whether or not this composite component is mounted.
           * @param {ReactClass} publicInstance The instance we want to test.
           * @return {boolean} True if mounted, false otherwise.
           * @protected
           * @final
           */
          isMounted: function(publicInstance) {
            return false;
          },
          /**
           * Forces an update. This should only be invoked when it is known with
           * certainty that we are **not** in a DOM transaction.
           *
           * You may want to call this when you know that some deeper aspect of the
           * component's state has changed but `setState` was not called.
           *
           * This will not invoke `shouldComponentUpdate`, but it will invoke
           * `componentWillUpdate` and `componentDidUpdate`.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {?function} callback Called after component is updated.
           * @param {?string} callerName name of the calling function in the public API.
           * @internal
           */
          enqueueForceUpdate: function(publicInstance, callback, callerName) {
            warnNoop(publicInstance, "forceUpdate");
          },
          /**
           * Replaces all of the state. Always use this or `setState` to mutate state.
           * You should treat `this.state` as immutable.
           *
           * There is no guarantee that `this.state` will be immediately updated, so
           * accessing `this.state` after calling this method may return the old value.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {object} completeState Next state.
           * @param {?function} callback Called after component is updated.
           * @param {?string} callerName name of the calling function in the public API.
           * @internal
           */
          enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
            warnNoop(publicInstance, "replaceState");
          },
          /**
           * Sets a subset of the state. This only exists because _pendingState is
           * internal. This provides a merging strategy that is not available to deep
           * properties which is confusing. TODO: Expose pendingState or don't use it
           * during the merge.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {object} partialState Next partial state to be merged with state.
           * @param {?function} callback Called after component is updated.
           * @param {?string} Name of the calling function in the public API.
           * @internal
           */
          enqueueSetState: function(publicInstance, partialState, callback, callerName) {
            warnNoop(publicInstance, "setState");
          }
        };
        var assign = Object.assign;
        var emptyObject = {};
        {
          Object.freeze(emptyObject);
        }
        function Component2(props, context, updater) {
          this.props = props;
          this.context = context;
          this.refs = emptyObject;
          this.updater = updater || ReactNoopUpdateQueue;
        }
        Component2.prototype.isReactComponent = {};
        Component2.prototype.setState = function(partialState, callback) {
          if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) {
            throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
          }
          this.updater.enqueueSetState(this, partialState, callback, "setState");
        };
        Component2.prototype.forceUpdate = function(callback) {
          this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
        };
        {
          var deprecatedAPIs = {
            isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],
            replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]
          };
          var defineDeprecationWarning = function(methodName, info) {
            Object.defineProperty(Component2.prototype, methodName, {
              get: function() {
                warn2("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
                return void 0;
              }
            });
          };
          for (var fnName in deprecatedAPIs) {
            if (deprecatedAPIs.hasOwnProperty(fnName)) {
              defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
            }
          }
        }
        function ComponentDummy() {
        }
        ComponentDummy.prototype = Component2.prototype;
        function PureComponent(props, context, updater) {
          this.props = props;
          this.context = context;
          this.refs = emptyObject;
          this.updater = updater || ReactNoopUpdateQueue;
        }
        var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
        pureComponentPrototype.constructor = PureComponent;
        assign(pureComponentPrototype, Component2.prototype);
        pureComponentPrototype.isPureReactComponent = true;
        function createRef() {
          var refObject = {
            current: null
          };
          {
            Object.seal(refObject);
          }
          return refObject;
        }
        var isArrayImpl = Array.isArray;
        function isArray2(a3) {
          return isArrayImpl(a3);
        }
        function typeName(value) {
          {
            var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
            var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
            return type;
          }
        }
        function willCoercionThrow(value) {
          {
            try {
              testStringCoercion(value);
              return false;
            } catch (e3) {
              return true;
            }
          }
        }
        function testStringCoercion(value) {
          return "" + value;
        }
        function checkKeyStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function getWrappedName(outerType, innerType, wrapperName) {
          var displayName = outerType.displayName;
          if (displayName) {
            return displayName;
          }
          var functionName = innerType.displayName || innerType.name || "";
          return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
        }
        function getContextName(type) {
          return type.displayName || "Context";
        }
        function getComponentNameFromType(type) {
          if (type == null) {
            return null;
          }
          {
            if (typeof type.tag === "number") {
              error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
            }
          }
          if (typeof type === "function") {
            return type.displayName || type.name || null;
          }
          if (typeof type === "string") {
            return type;
          }
          switch (type) {
            case REACT_FRAGMENT_TYPE:
              return "Fragment";
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_PROFILER_TYPE:
              return "Profiler";
            case REACT_STRICT_MODE_TYPE:
              return "StrictMode";
            case REACT_SUSPENSE_TYPE:
              return "Suspense";
            case REACT_SUSPENSE_LIST_TYPE:
              return "SuspenseList";
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_CONTEXT_TYPE:
                var context = type;
                return getContextName(context) + ".Consumer";
              case REACT_PROVIDER_TYPE:
                var provider = type;
                return getContextName(provider._context) + ".Provider";
              case REACT_FORWARD_REF_TYPE:
                return getWrappedName(type, type.render, "ForwardRef");
              case REACT_MEMO_TYPE:
                var outerName = type.displayName || null;
                if (outerName !== null) {
                  return outerName;
                }
                return getComponentNameFromType(type.type) || "Memo";
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return getComponentNameFromType(init(payload));
                } catch (x2) {
                  return null;
                }
              }
            }
          }
          return null;
        }
        var hasOwnProperty3 = Object.prototype.hasOwnProperty;
        var RESERVED_PROPS = {
          key: true,
          ref: true,
          __self: true,
          __source: true
        };
        var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
        {
          didWarnAboutStringRefs = {};
        }
        function hasValidRef(config) {
          {
            if (hasOwnProperty3.call(config, "ref")) {
              var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.ref !== void 0;
        }
        function hasValidKey(config) {
          {
            if (hasOwnProperty3.call(config, "key")) {
              var getter = Object.getOwnPropertyDescriptor(config, "key").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.key !== void 0;
        }
        function defineKeyPropWarningGetter(props, displayName) {
          var warnAboutAccessingKey = function() {
            {
              if (!specialPropKeyWarningShown) {
                specialPropKeyWarningShown = true;
                error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            }
          };
          warnAboutAccessingKey.isReactWarning = true;
          Object.defineProperty(props, "key", {
            get: warnAboutAccessingKey,
            configurable: true
          });
        }
        function defineRefPropWarningGetter(props, displayName) {
          var warnAboutAccessingRef = function() {
            {
              if (!specialPropRefWarningShown) {
                specialPropRefWarningShown = true;
                error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            }
          };
          warnAboutAccessingRef.isReactWarning = true;
          Object.defineProperty(props, "ref", {
            get: warnAboutAccessingRef,
            configurable: true
          });
        }
        function warnIfStringRefCannotBeAutoConverted(config) {
          {
            if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
              var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
              if (!didWarnAboutStringRefs[componentName]) {
                error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
                didWarnAboutStringRefs[componentName] = true;
              }
            }
          }
        }
        var ReactElement = function(type, key, ref, self2, source, owner, props) {
          var element = {
            // This tag allows us to uniquely identify this as a React Element
            $$typeof: REACT_ELEMENT_TYPE,
            // Built-in properties that belong on the element
            type,
            key,
            ref,
            props,
            // Record the component responsible for creating this element.
            _owner: owner
          };
          {
            element._store = {};
            Object.defineProperty(element._store, "validated", {
              configurable: false,
              enumerable: false,
              writable: true,
              value: false
            });
            Object.defineProperty(element, "_self", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: self2
            });
            Object.defineProperty(element, "_source", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: source
            });
            if (Object.freeze) {
              Object.freeze(element.props);
              Object.freeze(element);
            }
          }
          return element;
        };
        function createElement31(type, config, children) {
          var propName;
          var props = {};
          var key = null;
          var ref = null;
          var self2 = null;
          var source = null;
          if (config != null) {
            if (hasValidRef(config)) {
              ref = config.ref;
              {
                warnIfStringRefCannotBeAutoConverted(config);
              }
            }
            if (hasValidKey(config)) {
              {
                checkKeyStringCoercion(config.key);
              }
              key = "" + config.key;
            }
            self2 = config.__self === void 0 ? null : config.__self;
            source = config.__source === void 0 ? null : config.__source;
            for (propName in config) {
              if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
                props[propName] = config[propName];
              }
            }
          }
          var childrenLength = arguments.length - 2;
          if (childrenLength === 1) {
            props.children = children;
          } else if (childrenLength > 1) {
            var childArray = Array(childrenLength);
            for (var i3 = 0; i3 < childrenLength; i3++) {
              childArray[i3] = arguments[i3 + 2];
            }
            {
              if (Object.freeze) {
                Object.freeze(childArray);
              }
            }
            props.children = childArray;
          }
          if (type && type.defaultProps) {
            var defaultProps2 = type.defaultProps;
            for (propName in defaultProps2) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps2[propName];
              }
            }
          }
          {
            if (key || ref) {
              var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
              if (key) {
                defineKeyPropWarningGetter(props, displayName);
              }
              if (ref) {
                defineRefPropWarningGetter(props, displayName);
              }
            }
          }
          return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props);
        }
        function cloneAndReplaceKey(oldElement, newKey) {
          var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
          return newElement;
        }
        function cloneElement15(element, config, children) {
          if (element === null || element === void 0) {
            throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
          }
          var propName;
          var props = assign({}, element.props);
          var key = element.key;
          var ref = element.ref;
          var self2 = element._self;
          var source = element._source;
          var owner = element._owner;
          if (config != null) {
            if (hasValidRef(config)) {
              ref = config.ref;
              owner = ReactCurrentOwner.current;
            }
            if (hasValidKey(config)) {
              {
                checkKeyStringCoercion(config.key);
              }
              key = "" + config.key;
            }
            var defaultProps2;
            if (element.type && element.type.defaultProps) {
              defaultProps2 = element.type.defaultProps;
            }
            for (propName in config) {
              if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
                if (config[propName] === void 0 && defaultProps2 !== void 0) {
                  props[propName] = defaultProps2[propName];
                } else {
                  props[propName] = config[propName];
                }
              }
            }
          }
          var childrenLength = arguments.length - 2;
          if (childrenLength === 1) {
            props.children = children;
          } else if (childrenLength > 1) {
            var childArray = Array(childrenLength);
            for (var i3 = 0; i3 < childrenLength; i3++) {
              childArray[i3] = arguments[i3 + 2];
            }
            props.children = childArray;
          }
          return ReactElement(element.type, key, ref, self2, source, owner, props);
        }
        function isValidElement11(object) {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
        var SEPARATOR = ".";
        var SUBSEPARATOR = ":";
        function escape2(key) {
          var escapeRegex2 = /[=:]/g;
          var escaperLookup = {
            "=": "=0",
            ":": "=2"
          };
          var escapedString = key.replace(escapeRegex2, function(match2) {
            return escaperLookup[match2];
          });
          return "$" + escapedString;
        }
        var didWarnAboutMaps = false;
        var userProvidedKeyEscapeRegex = /\/+/g;
        function escapeUserProvidedKey(text) {
          return text.replace(userProvidedKeyEscapeRegex, "$&/");
        }
        function getElementKey(element, index2) {
          if (typeof element === "object" && element !== null && element.key != null) {
            {
              checkKeyStringCoercion(element.key);
            }
            return escape2("" + element.key);
          }
          return index2.toString(36);
        }
        function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
          var type = typeof children;
          if (type === "undefined" || type === "boolean") {
            children = null;
          }
          var invokeCallback = false;
          if (children === null) {
            invokeCallback = true;
          } else {
            switch (type) {
              case "string":
              case "number":
                invokeCallback = true;
                break;
              case "object":
                switch (children.$$typeof) {
                  case REACT_ELEMENT_TYPE:
                  case REACT_PORTAL_TYPE:
                    invokeCallback = true;
                }
            }
          }
          if (invokeCallback) {
            var _child = children;
            var mappedChild = callback(_child);
            var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
            if (isArray2(mappedChild)) {
              var escapedChildKey = "";
              if (childKey != null) {
                escapedChildKey = escapeUserProvidedKey(childKey) + "/";
              }
              mapIntoArray(mappedChild, array, escapedChildKey, "", function(c4) {
                return c4;
              });
            } else if (mappedChild != null) {
              if (isValidElement11(mappedChild)) {
                {
                  if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
                    checkKeyStringCoercion(mappedChild.key);
                  }
                }
                mappedChild = cloneAndReplaceKey(
                  mappedChild,
                  // Keep both the (mapped) and old keys if they differ, just as
                  // traverseAllChildren used to do for objects as children
                  escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
                  (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? (
                    // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
                    // eslint-disable-next-line react-internal/safe-string-coercion
                    escapeUserProvidedKey("" + mappedChild.key) + "/"
                  ) : "") + childKey
                );
              }
              array.push(mappedChild);
            }
            return 1;
          }
          var child;
          var nextName;
          var subtreeCount = 0;
          var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR;
          if (isArray2(children)) {
            for (var i3 = 0; i3 < children.length; i3++) {
              child = children[i3];
              nextName = nextNamePrefix + getElementKey(child, i3);
              subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
            }
          } else {
            var iteratorFn = getIteratorFn(children);
            if (typeof iteratorFn === "function") {
              var iterableChildren = children;
              {
                if (iteratorFn === iterableChildren.entries) {
                  if (!didWarnAboutMaps) {
                    warn2("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
                  }
                  didWarnAboutMaps = true;
                }
              }
              var iterator = iteratorFn.call(iterableChildren);
              var step;
              var ii = 0;
              while (!(step = iterator.next()).done) {
                child = step.value;
                nextName = nextNamePrefix + getElementKey(child, ii++);
                subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
              }
            } else if (type === "object") {
              var childrenString = String(children);
              throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead.");
            }
          }
          return subtreeCount;
        }
        function mapChildren(children, func, context) {
          if (children == null) {
            return children;
          }
          var result = [];
          var count5 = 0;
          mapIntoArray(children, result, "", "", function(child) {
            return func.call(context, child, count5++);
          });
          return result;
        }
        function countChildren(children) {
          var n4 = 0;
          mapChildren(children, function() {
            n4++;
          });
          return n4;
        }
        function forEachChildren(children, forEachFunc, forEachContext) {
          mapChildren(children, function() {
            forEachFunc.apply(this, arguments);
          }, forEachContext);
        }
        function toArray2(children) {
          return mapChildren(children, function(child) {
            return child;
          }) || [];
        }
        function onlyChild(children) {
          if (!isValidElement11(children)) {
            throw new Error("React.Children.only expected to receive a single React element child.");
          }
          return children;
        }
        function createContext13(defaultValue) {
          var context = {
            $$typeof: REACT_CONTEXT_TYPE,
            // As a workaround to support multiple concurrent renderers, we categorize
            // some renderers as primary and others as secondary. We only expect
            // there to be two concurrent renderers at most: React Native (primary) and
            // Fabric (secondary); React DOM (primary) and React ART (secondary).
            // Secondary renderers store their context values on separate fields.
            _currentValue: defaultValue,
            _currentValue2: defaultValue,
            // Used to track how many concurrent renderers this context currently
            // supports within in a single renderer. Such as parallel server rendering.
            _threadCount: 0,
            // These are circular
            Provider: null,
            Consumer: null,
            // Add these to use same hidden class in VM as ServerContext
            _defaultValue: null,
            _globalName: null
          };
          context.Provider = {
            $$typeof: REACT_PROVIDER_TYPE,
            _context: context
          };
          var hasWarnedAboutUsingNestedContextConsumers = false;
          var hasWarnedAboutUsingConsumerProvider = false;
          var hasWarnedAboutDisplayNameOnConsumer = false;
          {
            var Consumer = {
              $$typeof: REACT_CONTEXT_TYPE,
              _context: context
            };
            Object.defineProperties(Consumer, {
              Provider: {
                get: function() {
                  if (!hasWarnedAboutUsingConsumerProvider) {
                    hasWarnedAboutUsingConsumerProvider = true;
                    error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?");
                  }
                  return context.Provider;
                },
                set: function(_Provider) {
                  context.Provider = _Provider;
                }
              },
              _currentValue: {
                get: function() {
                  return context._currentValue;
                },
                set: function(_currentValue) {
                  context._currentValue = _currentValue;
                }
              },
              _currentValue2: {
                get: function() {
                  return context._currentValue2;
                },
                set: function(_currentValue2) {
                  context._currentValue2 = _currentValue2;
                }
              },
              _threadCount: {
                get: function() {
                  return context._threadCount;
                },
                set: function(_threadCount) {
                  context._threadCount = _threadCount;
                }
              },
              Consumer: {
                get: function() {
                  if (!hasWarnedAboutUsingNestedContextConsumers) {
                    hasWarnedAboutUsingNestedContextConsumers = true;
                    error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
                  }
                  return context.Consumer;
                }
              },
              displayName: {
                get: function() {
                  return context.displayName;
                },
                set: function(displayName) {
                  if (!hasWarnedAboutDisplayNameOnConsumer) {
                    warn2("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName);
                    hasWarnedAboutDisplayNameOnConsumer = true;
                  }
                }
              }
            });
            context.Consumer = Consumer;
          }
          {
            context._currentRenderer = null;
            context._currentRenderer2 = null;
          }
          return context;
        }
        var Uninitialized = -1;
        var Pending = 0;
        var Resolved = 1;
        var Rejected = 2;
        function lazyInitializer(payload) {
          if (payload._status === Uninitialized) {
            var ctor = payload._result;
            var thenable = ctor();
            thenable.then(function(moduleObject2) {
              if (payload._status === Pending || payload._status === Uninitialized) {
                var resolved = payload;
                resolved._status = Resolved;
                resolved._result = moduleObject2;
              }
            }, function(error2) {
              if (payload._status === Pending || payload._status === Uninitialized) {
                var rejected = payload;
                rejected._status = Rejected;
                rejected._result = error2;
              }
            });
            if (payload._status === Uninitialized) {
              var pending = payload;
              pending._status = Pending;
              pending._result = thenable;
            }
          }
          if (payload._status === Resolved) {
            var moduleObject = payload._result;
            {
              if (moduleObject === void 0) {
                error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject);
              }
            }
            {
              if (!("default" in moduleObject)) {
                error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
              }
            }
            return moduleObject.default;
          } else {
            throw payload._result;
          }
        }
        function lazy(ctor) {
          var payload = {
            // We use these fields to store the result.
            _status: Uninitialized,
            _result: ctor
          };
          var lazyType2 = {
            $$typeof: REACT_LAZY_TYPE,
            _payload: payload,
            _init: lazyInitializer
          };
          {
            var defaultProps2;
            var propTypes;
            Object.defineProperties(lazyType2, {
              defaultProps: {
                configurable: true,
                get: function() {
                  return defaultProps2;
                },
                set: function(newDefaultProps) {
                  error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
                  defaultProps2 = newDefaultProps;
                  Object.defineProperty(lazyType2, "defaultProps", {
                    enumerable: true
                  });
                }
              },
              propTypes: {
                configurable: true,
                get: function() {
                  return propTypes;
                },
                set: function(newPropTypes) {
                  error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
                  propTypes = newPropTypes;
                  Object.defineProperty(lazyType2, "propTypes", {
                    enumerable: true
                  });
                }
              }
            });
          }
          return lazyType2;
        }
        function forwardRef82(render3) {
          {
            if (render3 != null && render3.$$typeof === REACT_MEMO_TYPE) {
              error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).");
            } else if (typeof render3 !== "function") {
              error("forwardRef requires a render function but was given %s.", render3 === null ? "null" : typeof render3);
            } else {
              if (render3.length !== 0 && render3.length !== 2) {
                error("forwardRef render functions accept exactly two parameters: props and ref. %s", render3.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
              }
            }
            if (render3 != null) {
              if (render3.defaultProps != null || render3.propTypes != null) {
                error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");
              }
            }
          }
          var elementType = {
            $$typeof: REACT_FORWARD_REF_TYPE,
            render: render3
          };
          {
            var ownName;
            Object.defineProperty(elementType, "displayName", {
              enumerable: false,
              configurable: true,
              get: function() {
                return ownName;
              },
              set: function(name) {
                ownName = name;
                if (!render3.name && !render3.displayName) {
                  render3.displayName = name;
                }
              }
            });
          }
          return elementType;
        }
        var REACT_MODULE_REFERENCE;
        {
          REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
        }
        function isValidElementType(type) {
          if (typeof type === "string" || typeof type === "function") {
            return true;
          }
          if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
            return true;
          }
          if (typeof type === "object" && type !== null) {
            if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
            // types supported by any Flight configuration anywhere since
            // we don't know which Flight build this will end up being used
            // with.
            type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) {
              return true;
            }
          }
          return false;
        }
        function memo3(type, compare2) {
          {
            if (!isValidElementType(type)) {
              error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
            }
          }
          var elementType = {
            $$typeof: REACT_MEMO_TYPE,
            type,
            compare: compare2 === void 0 ? null : compare2
          };
          {
            var ownName;
            Object.defineProperty(elementType, "displayName", {
              enumerable: false,
              configurable: true,
              get: function() {
                return ownName;
              },
              set: function(name) {
                ownName = name;
                if (!type.name && !type.displayName) {
                  type.displayName = name;
                }
              }
            });
          }
          return elementType;
        }
        function resolveDispatcher() {
          var dispatcher = ReactCurrentDispatcher.current;
          {
            if (dispatcher === null) {
              error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
            }
          }
          return dispatcher;
        }
        function useContext14(Context2) {
          var dispatcher = resolveDispatcher();
          {
            if (Context2._context !== void 0) {
              var realContext = Context2._context;
              if (realContext.Consumer === Context2) {
                error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?");
              } else if (realContext.Provider === Context2) {
                error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?");
              }
            }
          }
          return dispatcher.useContext(Context2);
        }
        function useState56(initialState2) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useState(initialState2);
        }
        function useReducer4(reducer2, initialArg, init) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useReducer(reducer2, initialArg, init);
        }
        function useRef43(initialValue) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useRef(initialValue);
        }
        function useEffect51(create9, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useEffect(create9, deps);
        }
        function useInsertionEffect(create9, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useInsertionEffect(create9, deps);
        }
        function useLayoutEffect6(create9, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useLayoutEffect(create9, deps);
        }
        function useCallback38(callback, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useCallback(callback, deps);
        }
        function useMemo15(create9, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useMemo(create9, deps);
        }
        function useImperativeHandle3(ref, create9, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useImperativeHandle(ref, create9, deps);
        }
        function useDebugValue2(value, formatterFn) {
          {
            var dispatcher = resolveDispatcher();
            return dispatcher.useDebugValue(value, formatterFn);
          }
        }
        function useTransition() {
          var dispatcher = resolveDispatcher();
          return dispatcher.useTransition();
        }
        function useDeferredValue(value) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useDeferredValue(value);
        }
        function useId2() {
          var dispatcher = resolveDispatcher();
          return dispatcher.useId();
        }
        function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
        }
        var disabledDepth = 0;
        var prevLog;
        var prevInfo;
        var prevWarn;
        var prevError;
        var prevGroup;
        var prevGroupCollapsed;
        var prevGroupEnd;
        function disabledLog() {
        }
        disabledLog.__reactDisabledLog = true;
        function disableLogs() {
          {
            if (disabledDepth === 0) {
              prevLog = console.log;
              prevInfo = console.info;
              prevWarn = console.warn;
              prevError = console.error;
              prevGroup = console.group;
              prevGroupCollapsed = console.groupCollapsed;
              prevGroupEnd = console.groupEnd;
              var props = {
                configurable: true,
                enumerable: true,
                value: disabledLog,
                writable: true
              };
              Object.defineProperties(console, {
                info: props,
                log: props,
                warn: props,
                error: props,
                group: props,
                groupCollapsed: props,
                groupEnd: props
              });
            }
            disabledDepth++;
          }
        }
        function reenableLogs() {
          {
            disabledDepth--;
            if (disabledDepth === 0) {
              var props = {
                configurable: true,
                enumerable: true,
                writable: true
              };
              Object.defineProperties(console, {
                log: assign({}, props, {
                  value: prevLog
                }),
                info: assign({}, props, {
                  value: prevInfo
                }),
                warn: assign({}, props, {
                  value: prevWarn
                }),
                error: assign({}, props, {
                  value: prevError
                }),
                group: assign({}, props, {
                  value: prevGroup
                }),
                groupCollapsed: assign({}, props, {
                  value: prevGroupCollapsed
                }),
                groupEnd: assign({}, props, {
                  value: prevGroupEnd
                })
              });
            }
            if (disabledDepth < 0) {
              error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
            }
          }
        }
        var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
        var prefix;
        function describeBuiltInComponentFrame(name, source, ownerFn) {
          {
            if (prefix === void 0) {
              try {
                throw Error();
              } catch (x2) {
                var match2 = x2.stack.trim().match(/\n( *(at )?)/);
                prefix = match2 && match2[1] || "";
              }
            }
            return "\n" + prefix + name;
          }
        }
        var reentry = false;
        var componentFrameCache;
        {
          var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
          componentFrameCache = new PossiblyWeakMap();
        }
        function describeNativeComponentFrame(fn, construct) {
          if (!fn || reentry) {
            return "";
          }
          {
            var frame = componentFrameCache.get(fn);
            if (frame !== void 0) {
              return frame;
            }
          }
          var control;
          reentry = true;
          var previousPrepareStackTrace = Error.prepareStackTrace;
          Error.prepareStackTrace = void 0;
          var previousDispatcher;
          {
            previousDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = null;
            disableLogs();
          }
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if (typeof Reflect === "object" && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x2) {
                  control = x2;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x2) {
                control = x2;
              }
              fn();
            }
          } catch (sample) {
            if (sample && control && typeof sample.stack === "string") {
              var sampleLines = sample.stack.split("\n");
              var controlLines = control.stack.split("\n");
              var s4 = sampleLines.length - 1;
              var c4 = controlLines.length - 1;
              while (s4 >= 1 && c4 >= 0 && sampleLines[s4] !== controlLines[c4]) {
                c4--;
              }
              for (; s4 >= 1 && c4 >= 0; s4--, c4--) {
                if (sampleLines[s4] !== controlLines[c4]) {
                  if (s4 !== 1 || c4 !== 1) {
                    do {
                      s4--;
                      c4--;
                      if (c4 < 0 || sampleLines[s4] !== controlLines[c4]) {
                        var _frame = "\n" + sampleLines[s4].replace(" at new ", " at ");
                        if (fn.displayName && _frame.includes("<anonymous>")) {
                          _frame = _frame.replace("<anonymous>", fn.displayName);
                        }
                        {
                          if (typeof fn === "function") {
                            componentFrameCache.set(fn, _frame);
                          }
                        }
                        return _frame;
                      }
                    } while (s4 >= 1 && c4 >= 0);
                  }
                  break;
                }
              }
            }
          } finally {
            reentry = false;
            {
              ReactCurrentDispatcher$1.current = previousDispatcher;
              reenableLogs();
            }
            Error.prepareStackTrace = previousPrepareStackTrace;
          }
          var name = fn ? fn.displayName || fn.name : "";
          var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
          {
            if (typeof fn === "function") {
              componentFrameCache.set(fn, syntheticFrame);
            }
          }
          return syntheticFrame;
        }
        function describeFunctionComponentFrame(fn, source, ownerFn) {
          {
            return describeNativeComponentFrame(fn, false);
          }
        }
        function shouldConstruct(Component3) {
          var prototype = Component3.prototype;
          return !!(prototype && prototype.isReactComponent);
        }
        function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
          if (type == null) {
            return "";
          }
          if (typeof type === "function") {
            {
              return describeNativeComponentFrame(type, shouldConstruct(type));
            }
          }
          if (typeof type === "string") {
            return describeBuiltInComponentFrame(type);
          }
          switch (type) {
            case REACT_SUSPENSE_TYPE:
              return describeBuiltInComponentFrame("Suspense");
            case REACT_SUSPENSE_LIST_TYPE:
              return describeBuiltInComponentFrame("SuspenseList");
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_FORWARD_REF_TYPE:
                return describeFunctionComponentFrame(type.render);
              case REACT_MEMO_TYPE:
                return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
                } catch (x2) {
                }
              }
            }
          }
          return "";
        }
        var loggedTypeFailures = {};
        var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
        function setCurrentlyValidatingElement(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
            } else {
              ReactDebugCurrentFrame$1.setExtraStackFrame(null);
            }
          }
        }
        function checkPropTypes(typeSpecs, values, location2, componentName, element) {
          {
            var has2 = Function.call.bind(hasOwnProperty3);
            for (var typeSpecName in typeSpecs) {
              if (has2(typeSpecs, typeSpecName)) {
                var error$1 = void 0;
                try {
                  if (typeof typeSpecs[typeSpecName] !== "function") {
                    var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                    err.name = "Invariant Violation";
                    throw err;
                  }
                  error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
                } catch (ex) {
                  error$1 = ex;
                }
                if (error$1 && !(error$1 instanceof Error)) {
                  setCurrentlyValidatingElement(element);
                  error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1);
                  setCurrentlyValidatingElement(null);
                }
                if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                  loggedTypeFailures[error$1.message] = true;
                  setCurrentlyValidatingElement(element);
                  error("Failed %s type: %s", location2, error$1.message);
                  setCurrentlyValidatingElement(null);
                }
              }
            }
          }
        }
        function setCurrentlyValidatingElement$1(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              setExtraStackFrame(stack);
            } else {
              setExtraStackFrame(null);
            }
          }
        }
        var propTypesMisspellWarningShown;
        {
          propTypesMisspellWarningShown = false;
        }
        function getDeclarationErrorAddendum() {
          if (ReactCurrentOwner.current) {
            var name = getComponentNameFromType(ReactCurrentOwner.current.type);
            if (name) {
              return "\n\nCheck the render method of `" + name + "`.";
            }
          }
          return "";
        }
        function getSourceInfoErrorAddendum(source) {
          if (source !== void 0) {
            var fileName = source.fileName.replace(/^.*[\\\/]/, "");
            var lineNumber = source.lineNumber;
            return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
          }
          return "";
        }
        function getSourceInfoErrorAddendumForProps(elementProps) {
          if (elementProps !== null && elementProps !== void 0) {
            return getSourceInfoErrorAddendum(elementProps.__source);
          }
          return "";
        }
        var ownerHasKeyUseWarning = {};
        function getCurrentComponentErrorInfo(parentType) {
          var info = getDeclarationErrorAddendum();
          if (!info) {
            var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
            if (parentName) {
              info = "\n\nCheck the top-level render call using <" + parentName + ">.";
            }
          }
          return info;
        }
        function validateExplicitKey(element, parentType) {
          if (!element._store || element._store.validated || element.key != null) {
            return;
          }
          element._store.validated = true;
          var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
          if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
            return;
          }
          ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
          var childOwner = "";
          if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
            childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
          }
          {
            setCurrentlyValidatingElement$1(element);
            error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
            setCurrentlyValidatingElement$1(null);
          }
        }
        function validateChildKeys(node, parentType) {
          if (typeof node !== "object") {
            return;
          }
          if (isArray2(node)) {
            for (var i3 = 0; i3 < node.length; i3++) {
              var child = node[i3];
              if (isValidElement11(child)) {
                validateExplicitKey(child, parentType);
              }
            }
          } else if (isValidElement11(node)) {
            if (node._store) {
              node._store.validated = true;
            }
          } else if (node) {
            var iteratorFn = getIteratorFn(node);
            if (typeof iteratorFn === "function") {
              if (iteratorFn !== node.entries) {
                var iterator = iteratorFn.call(node);
                var step;
                while (!(step = iterator.next()).done) {
                  if (isValidElement11(step.value)) {
                    validateExplicitKey(step.value, parentType);
                  }
                }
              }
            }
          }
        }
        function validatePropTypes(element) {
          {
            var type = element.type;
            if (type === null || type === void 0 || typeof type === "string") {
              return;
            }
            var propTypes;
            if (typeof type === "function") {
              propTypes = type.propTypes;
            } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
            // Inner props are checked in the reconciler.
            type.$$typeof === REACT_MEMO_TYPE)) {
              propTypes = type.propTypes;
            } else {
              return;
            }
            if (propTypes) {
              var name = getComponentNameFromType(type);
              checkPropTypes(propTypes, element.props, "prop", name, element);
            } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
              propTypesMisspellWarningShown = true;
              var _name = getComponentNameFromType(type);
              error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
            }
            if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
              error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
            }
          }
        }
        function validateFragmentProps(fragment) {
          {
            var keys = Object.keys(fragment.props);
            for (var i3 = 0; i3 < keys.length; i3++) {
              var key = keys[i3];
              if (key !== "children" && key !== "key") {
                setCurrentlyValidatingElement$1(fragment);
                error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
                setCurrentlyValidatingElement$1(null);
                break;
              }
            }
            if (fragment.ref !== null) {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid attribute `ref` supplied to `React.Fragment`.");
              setCurrentlyValidatingElement$1(null);
            }
          }
        }
        function createElementWithValidation(type, props, children) {
          var validType = isValidElementType(type);
          if (!validType) {
            var info = "";
            if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
              info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            }
            var sourceInfo = getSourceInfoErrorAddendumForProps(props);
            if (sourceInfo) {
              info += sourceInfo;
            } else {
              info += getDeclarationErrorAddendum();
            }
            var typeString;
            if (type === null) {
              typeString = "null";
            } else if (isArray2(type)) {
              typeString = "array";
            } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
              typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
              info = " Did you accidentally export a JSX literal instead of a component?";
            } else {
              typeString = typeof type;
            }
            {
              error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
            }
          }
          var element = createElement31.apply(this, arguments);
          if (element == null) {
            return element;
          }
          if (validType) {
            for (var i3 = 2; i3 < arguments.length; i3++) {
              validateChildKeys(arguments[i3], type);
            }
          }
          if (type === REACT_FRAGMENT_TYPE) {
            validateFragmentProps(element);
          } else {
            validatePropTypes(element);
          }
          return element;
        }
        var didWarnAboutDeprecatedCreateFactory = false;
        function createFactoryWithValidation(type) {
          var validatedFactory = createElementWithValidation.bind(null, type);
          validatedFactory.type = type;
          {
            if (!didWarnAboutDeprecatedCreateFactory) {
              didWarnAboutDeprecatedCreateFactory = true;
              warn2("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.");
            }
            Object.defineProperty(validatedFactory, "type", {
              enumerable: false,
              get: function() {
                warn2("Factory.type is deprecated. Access the class directly before passing it to createFactory.");
                Object.defineProperty(this, "type", {
                  value: type
                });
                return type;
              }
            });
          }
          return validatedFactory;
        }
        function cloneElementWithValidation(element, props, children) {
          var newElement = cloneElement15.apply(this, arguments);
          for (var i3 = 2; i3 < arguments.length; i3++) {
            validateChildKeys(arguments[i3], newElement.type);
          }
          validatePropTypes(newElement);
          return newElement;
        }
        function startTransition(scope, options) {
          var prevTransition = ReactCurrentBatchConfig.transition;
          ReactCurrentBatchConfig.transition = {};
          var currentTransition = ReactCurrentBatchConfig.transition;
          {
            ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set();
          }
          try {
            scope();
          } finally {
            ReactCurrentBatchConfig.transition = prevTransition;
            {
              if (prevTransition === null && currentTransition._updatedFibers) {
                var updatedFibersCount = currentTransition._updatedFibers.size;
                if (updatedFibersCount > 10) {
                  warn2("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.");
                }
                currentTransition._updatedFibers.clear();
              }
            }
          }
        }
        var didWarnAboutMessageChannel = false;
        var enqueueTaskImpl = null;
        function enqueueTask(task) {
          if (enqueueTaskImpl === null) {
            try {
              var requireString = ("require" + Math.random()).slice(0, 7);
              var nodeRequire = module2 && module2[requireString];
              enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate;
            } catch (_err) {
              enqueueTaskImpl = function(callback) {
                {
                  if (didWarnAboutMessageChannel === false) {
                    didWarnAboutMessageChannel = true;
                    if (typeof MessageChannel === "undefined") {
                      error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning.");
                    }
                  }
                }
                var channel = new MessageChannel();
                channel.port1.onmessage = callback;
                channel.port2.postMessage(void 0);
              };
            }
          }
          return enqueueTaskImpl(task);
        }
        var actScopeDepth = 0;
        var didWarnNoAwaitAct = false;
        function act(callback) {
          {
            var prevActScopeDepth = actScopeDepth;
            actScopeDepth++;
            if (ReactCurrentActQueue.current === null) {
              ReactCurrentActQueue.current = [];
            }
            var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
            var result;
            try {
              ReactCurrentActQueue.isBatchingLegacy = true;
              result = callback();
              if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
                var queue2 = ReactCurrentActQueue.current;
                if (queue2 !== null) {
                  ReactCurrentActQueue.didScheduleLegacyUpdate = false;
                  flushActQueue(queue2);
                }
              }
            } catch (error2) {
              popActScope(prevActScopeDepth);
              throw error2;
            } finally {
              ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
            }
            if (result !== null && typeof result === "object" && typeof result.then === "function") {
              var thenableResult = result;
              var wasAwaited = false;
              var thenable = {
                then: function(resolve, reject) {
                  wasAwaited = true;
                  thenableResult.then(function(returnValue2) {
                    popActScope(prevActScopeDepth);
                    if (actScopeDepth === 0) {
                      recursivelyFlushAsyncActWork(returnValue2, resolve, reject);
                    } else {
                      resolve(returnValue2);
                    }
                  }, function(error2) {
                    popActScope(prevActScopeDepth);
                    reject(error2);
                  });
                }
              };
              {
                if (!didWarnNoAwaitAct && typeof Promise !== "undefined") {
                  Promise.resolve().then(function() {
                  }).then(function() {
                    if (!wasAwaited) {
                      didWarnNoAwaitAct = true;
                      error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);");
                    }
                  });
                }
              }
              return thenable;
            } else {
              var returnValue = result;
              popActScope(prevActScopeDepth);
              if (actScopeDepth === 0) {
                var _queue = ReactCurrentActQueue.current;
                if (_queue !== null) {
                  flushActQueue(_queue);
                  ReactCurrentActQueue.current = null;
                }
                var _thenable = {
                  then: function(resolve, reject) {
                    if (ReactCurrentActQueue.current === null) {
                      ReactCurrentActQueue.current = [];
                      recursivelyFlushAsyncActWork(returnValue, resolve, reject);
                    } else {
                      resolve(returnValue);
                    }
                  }
                };
                return _thenable;
              } else {
                var _thenable2 = {
                  then: function(resolve, reject) {
                    resolve(returnValue);
                  }
                };
                return _thenable2;
              }
            }
          }
        }
        function popActScope(prevActScopeDepth) {
          {
            if (prevActScopeDepth !== actScopeDepth - 1) {
              error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
            }
            actScopeDepth = prevActScopeDepth;
          }
        }
        function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
          {
            var queue2 = ReactCurrentActQueue.current;
            if (queue2 !== null) {
              try {
                flushActQueue(queue2);
                enqueueTask(function() {
                  if (queue2.length === 0) {
                    ReactCurrentActQueue.current = null;
                    resolve(returnValue);
                  } else {
                    recursivelyFlushAsyncActWork(returnValue, resolve, reject);
                  }
                });
              } catch (error2) {
                reject(error2);
              }
            } else {
              resolve(returnValue);
            }
          }
        }
        var isFlushing = false;
        function flushActQueue(queue2) {
          {
            if (!isFlushing) {
              isFlushing = true;
              var i3 = 0;
              try {
                for (; i3 < queue2.length; i3++) {
                  var callback = queue2[i3];
                  do {
                    callback = callback(true);
                  } while (callback !== null);
                }
                queue2.length = 0;
              } catch (error2) {
                queue2 = queue2.slice(i3 + 1);
                throw error2;
              } finally {
                isFlushing = false;
              }
            }
          }
        }
        var createElement$1 = createElementWithValidation;
        var cloneElement$1 = cloneElementWithValidation;
        var createFactory = createFactoryWithValidation;
        var Children16 = {
          map: mapChildren,
          forEach: forEachChildren,
          count: countChildren,
          toArray: toArray2,
          only: onlyChild
        };
        exports.Children = Children16;
        exports.Component = Component2;
        exports.Fragment = REACT_FRAGMENT_TYPE;
        exports.Profiler = REACT_PROFILER_TYPE;
        exports.PureComponent = PureComponent;
        exports.StrictMode = REACT_STRICT_MODE_TYPE;
        exports.Suspense = REACT_SUSPENSE_TYPE;
        exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
        exports.cloneElement = cloneElement$1;
        exports.createContext = createContext13;
        exports.createElement = createElement$1;
        exports.createFactory = createFactory;
        exports.createRef = createRef;
        exports.forwardRef = forwardRef82;
        exports.isValidElement = isValidElement11;
        exports.lazy = lazy;
        exports.memo = memo3;
        exports.startTransition = startTransition;
        exports.unstable_act = act;
        exports.useCallback = useCallback38;
        exports.useContext = useContext14;
        exports.useDebugValue = useDebugValue2;
        exports.useDeferredValue = useDeferredValue;
        exports.useEffect = useEffect51;
        exports.useId = useId2;
        exports.useImperativeHandle = useImperativeHandle3;
        exports.useInsertionEffect = useInsertionEffect;
        exports.useLayoutEffect = useLayoutEffect6;
        exports.useMemo = useMemo15;
        exports.useReducer = useReducer4;
        exports.useRef = useRef43;
        exports.useState = useState56;
        exports.useSyncExternalStore = useSyncExternalStore;
        exports.useTransition = useTransition;
        exports.version = ReactVersion;
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
        }
      })();
    }
  }
});

// node_modules/react/index.js
var require_react = __commonJS({
  "node_modules/react/index.js"(exports, module2) {
    "use strict";
    if (false) {
      module2.exports = null;
    } else {
      module2.exports = require_react_development();
    }
  }
});

// node_modules/scheduler/cjs/scheduler.development.js
var require_scheduler_development = __commonJS({
  "node_modules/scheduler/cjs/scheduler.development.js"(exports) {
    "use strict";
    if (true) {
      (function() {
        "use strict";
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
        }
        var enableSchedulerDebugging = false;
        var enableProfiling = false;
        var frameYieldMs = 5;
        function push3(heap, node) {
          var index2 = heap.length;
          heap.push(node);
          siftUp(heap, node, index2);
        }
        function peek(heap) {
          return heap.length === 0 ? null : heap[0];
        }
        function pop(heap) {
          if (heap.length === 0) {
            return null;
          }
          var first = heap[0];
          var last = heap.pop();
          if (last !== first) {
            heap[0] = last;
            siftDown(heap, last, 0);
          }
          return first;
        }
        function siftUp(heap, node, i3) {
          var index2 = i3;
          while (index2 > 0) {
            var parentIndex = index2 - 1 >>> 1;
            var parent = heap[parentIndex];
            if (compare2(parent, node) > 0) {
              heap[parentIndex] = node;
              heap[index2] = parent;
              index2 = parentIndex;
            } else {
              return;
            }
          }
        }
        function siftDown(heap, node, i3) {
          var index2 = i3;
          var length = heap.length;
          var halfLength = length >>> 1;
          while (index2 < halfLength) {
            var leftIndex = (index2 + 1) * 2 - 1;
            var left = heap[leftIndex];
            var rightIndex = leftIndex + 1;
            var right = heap[rightIndex];
            if (compare2(left, node) < 0) {
              if (rightIndex < length && compare2(right, left) < 0) {
                heap[index2] = right;
                heap[rightIndex] = node;
                index2 = rightIndex;
              } else {
                heap[index2] = left;
                heap[leftIndex] = node;
                index2 = leftIndex;
              }
            } else if (rightIndex < length && compare2(right, node) < 0) {
              heap[index2] = right;
              heap[rightIndex] = node;
              index2 = rightIndex;
            } else {
              return;
            }
          }
        }
        function compare2(a3, b3) {
          var diff = a3.sortIndex - b3.sortIndex;
          return diff !== 0 ? diff : a3.id - b3.id;
        }
        var ImmediatePriority = 1;
        var UserBlockingPriority = 2;
        var NormalPriority = 3;
        var LowPriority = 4;
        var IdlePriority = 5;
        function markTaskErrored(task, ms) {
        }
        var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function";
        if (hasPerformanceNow) {
          var localPerformance = performance;
          exports.unstable_now = function() {
            return localPerformance.now();
          };
        } else {
          var localDate = Date;
          var initialTime = localDate.now();
          exports.unstable_now = function() {
            return localDate.now() - initialTime;
          };
        }
        var maxSigned31BitInt = 1073741823;
        var IMMEDIATE_PRIORITY_TIMEOUT = -1;
        var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
        var NORMAL_PRIORITY_TIMEOUT = 5e3;
        var LOW_PRIORITY_TIMEOUT = 1e4;
        var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
        var taskQueue = [];
        var timerQueue = [];
        var taskIdCounter = 1;
        var currentTask = null;
        var currentPriorityLevel = NormalPriority;
        var isPerformingWork = false;
        var isHostCallbackScheduled = false;
        var isHostTimeoutScheduled = false;
        var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null;
        var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null;
        var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null;
        var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
        function advanceTimers(currentTime) {
          var timer = peek(timerQueue);
          while (timer !== null) {
            if (timer.callback === null) {
              pop(timerQueue);
            } else if (timer.startTime <= currentTime) {
              pop(timerQueue);
              timer.sortIndex = timer.expirationTime;
              push3(taskQueue, timer);
            } else {
              return;
            }
            timer = peek(timerQueue);
          }
        }
        function handleTimeout(currentTime) {
          isHostTimeoutScheduled = false;
          advanceTimers(currentTime);
          if (!isHostCallbackScheduled) {
            if (peek(taskQueue) !== null) {
              isHostCallbackScheduled = true;
              requestHostCallback(flushWork);
            } else {
              var firstTimer = peek(timerQueue);
              if (firstTimer !== null) {
                requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
              }
            }
          }
        }
        function flushWork(hasTimeRemaining, initialTime2) {
          isHostCallbackScheduled = false;
          if (isHostTimeoutScheduled) {
            isHostTimeoutScheduled = false;
            cancelHostTimeout();
          }
          isPerformingWork = true;
          var previousPriorityLevel = currentPriorityLevel;
          try {
            if (enableProfiling) {
              try {
                return workLoop(hasTimeRemaining, initialTime2);
              } catch (error) {
                if (currentTask !== null) {
                  var currentTime = exports.unstable_now();
                  markTaskErrored(currentTask, currentTime);
                  currentTask.isQueued = false;
                }
                throw error;
              }
            } else {
              return workLoop(hasTimeRemaining, initialTime2);
            }
          } finally {
            currentTask = null;
            currentPriorityLevel = previousPriorityLevel;
            isPerformingWork = false;
          }
        }
        function workLoop(hasTimeRemaining, initialTime2) {
          var currentTime = initialTime2;
          advanceTimers(currentTime);
          currentTask = peek(taskQueue);
          while (currentTask !== null && !enableSchedulerDebugging) {
            if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
              break;
            }
            var callback = currentTask.callback;
            if (typeof callback === "function") {
              currentTask.callback = null;
              currentPriorityLevel = currentTask.priorityLevel;
              var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
              var continuationCallback = callback(didUserCallbackTimeout);
              currentTime = exports.unstable_now();
              if (typeof continuationCallback === "function") {
                currentTask.callback = continuationCallback;
              } else {
                if (currentTask === peek(taskQueue)) {
                  pop(taskQueue);
                }
              }
              advanceTimers(currentTime);
            } else {
              pop(taskQueue);
            }
            currentTask = peek(taskQueue);
          }
          if (currentTask !== null) {
            return true;
          } else {
            var firstTimer = peek(timerQueue);
            if (firstTimer !== null) {
              requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
            }
            return false;
          }
        }
        function unstable_runWithPriority(priorityLevel, eventHandler) {
          switch (priorityLevel) {
            case ImmediatePriority:
            case UserBlockingPriority:
            case NormalPriority:
            case LowPriority:
            case IdlePriority:
              break;
            default:
              priorityLevel = NormalPriority;
          }
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = priorityLevel;
          try {
            return eventHandler();
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        }
        function unstable_next(eventHandler) {
          var priorityLevel;
          switch (currentPriorityLevel) {
            case ImmediatePriority:
            case UserBlockingPriority:
            case NormalPriority:
              priorityLevel = NormalPriority;
              break;
            default:
              priorityLevel = currentPriorityLevel;
              break;
          }
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = priorityLevel;
          try {
            return eventHandler();
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        }
        function unstable_wrapCallback(callback) {
          var parentPriorityLevel = currentPriorityLevel;
          return function() {
            var previousPriorityLevel = currentPriorityLevel;
            currentPriorityLevel = parentPriorityLevel;
            try {
              return callback.apply(this, arguments);
            } finally {
              currentPriorityLevel = previousPriorityLevel;
            }
          };
        }
        function unstable_scheduleCallback(priorityLevel, callback, options) {
          var currentTime = exports.unstable_now();
          var startTime2;
          if (typeof options === "object" && options !== null) {
            var delay = options.delay;
            if (typeof delay === "number" && delay > 0) {
              startTime2 = currentTime + delay;
            } else {
              startTime2 = currentTime;
            }
          } else {
            startTime2 = currentTime;
          }
          var timeout;
          switch (priorityLevel) {
            case ImmediatePriority:
              timeout = IMMEDIATE_PRIORITY_TIMEOUT;
              break;
            case UserBlockingPriority:
              timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
              break;
            case IdlePriority:
              timeout = IDLE_PRIORITY_TIMEOUT;
              break;
            case LowPriority:
              timeout = LOW_PRIORITY_TIMEOUT;
              break;
            case NormalPriority:
            default:
              timeout = NORMAL_PRIORITY_TIMEOUT;
              break;
          }
          var expirationTime = startTime2 + timeout;
          var newTask = {
            id: taskIdCounter++,
            callback,
            priorityLevel,
            startTime: startTime2,
            expirationTime,
            sortIndex: -1
          };
          if (startTime2 > currentTime) {
            newTask.sortIndex = startTime2;
            push3(timerQueue, newTask);
            if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
              if (isHostTimeoutScheduled) {
                cancelHostTimeout();
              } else {
                isHostTimeoutScheduled = true;
              }
              requestHostTimeout(handleTimeout, startTime2 - currentTime);
            }
          } else {
            newTask.sortIndex = expirationTime;
            push3(taskQueue, newTask);
            if (!isHostCallbackScheduled && !isPerformingWork) {
              isHostCallbackScheduled = true;
              requestHostCallback(flushWork);
            }
          }
          return newTask;
        }
        function unstable_pauseExecution() {
        }
        function unstable_continueExecution() {
          if (!isHostCallbackScheduled && !isPerformingWork) {
            isHostCallbackScheduled = true;
            requestHostCallback(flushWork);
          }
        }
        function unstable_getFirstCallbackNode() {
          return peek(taskQueue);
        }
        function unstable_cancelCallback(task) {
          task.callback = null;
        }
        function unstable_getCurrentPriorityLevel() {
          return currentPriorityLevel;
        }
        var isMessageLoopRunning = false;
        var scheduledHostCallback = null;
        var taskTimeoutID = -1;
        var frameInterval = frameYieldMs;
        var startTime = -1;
        function shouldYieldToHost() {
          var timeElapsed = exports.unstable_now() - startTime;
          if (timeElapsed < frameInterval) {
            return false;
          }
          return true;
        }
        function requestPaint() {
        }
        function forceFrameRate(fps) {
          if (fps < 0 || fps > 125) {
            console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported");
            return;
          }
          if (fps > 0) {
            frameInterval = Math.floor(1e3 / fps);
          } else {
            frameInterval = frameYieldMs;
          }
        }
        var performWorkUntilDeadline = function() {
          if (scheduledHostCallback !== null) {
            var currentTime = exports.unstable_now();
            startTime = currentTime;
            var hasTimeRemaining = true;
            var hasMoreWork = true;
            try {
              hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
            } finally {
              if (hasMoreWork) {
                schedulePerformWorkUntilDeadline();
              } else {
                isMessageLoopRunning = false;
                scheduledHostCallback = null;
              }
            }
          } else {
            isMessageLoopRunning = false;
          }
        };
        var schedulePerformWorkUntilDeadline;
        if (typeof localSetImmediate === "function") {
          schedulePerformWorkUntilDeadline = function() {
            localSetImmediate(performWorkUntilDeadline);
          };
        } else if (typeof MessageChannel !== "undefined") {
          var channel = new MessageChannel();
          var port = channel.port2;
          channel.port1.onmessage = performWorkUntilDeadline;
          schedulePerformWorkUntilDeadline = function() {
            port.postMessage(null);
          };
        } else {
          schedulePerformWorkUntilDeadline = function() {
            localSetTimeout(performWorkUntilDeadline, 0);
          };
        }
        function requestHostCallback(callback) {
          scheduledHostCallback = callback;
          if (!isMessageLoopRunning) {
            isMessageLoopRunning = true;
            schedulePerformWorkUntilDeadline();
          }
        }
        function requestHostTimeout(callback, ms) {
          taskTimeoutID = localSetTimeout(function() {
            callback(exports.unstable_now());
          }, ms);
        }
        function cancelHostTimeout() {
          localClearTimeout(taskTimeoutID);
          taskTimeoutID = -1;
        }
        var unstable_requestPaint = requestPaint;
        var unstable_Profiling = null;
        exports.unstable_IdlePriority = IdlePriority;
        exports.unstable_ImmediatePriority = ImmediatePriority;
        exports.unstable_LowPriority = LowPriority;
        exports.unstable_NormalPriority = NormalPriority;
        exports.unstable_Profiling = unstable_Profiling;
        exports.unstable_UserBlockingPriority = UserBlockingPriority;
        exports.unstable_cancelCallback = unstable_cancelCallback;
        exports.unstable_continueExecution = unstable_continueExecution;
        exports.unstable_forceFrameRate = forceFrameRate;
        exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
        exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
        exports.unstable_next = unstable_next;
        exports.unstable_pauseExecution = unstable_pauseExecution;
        exports.unstable_requestPaint = unstable_requestPaint;
        exports.unstable_runWithPriority = unstable_runWithPriority;
        exports.unstable_scheduleCallback = unstable_scheduleCallback;
        exports.unstable_shouldYield = shouldYieldToHost;
        exports.unstable_wrapCallback = unstable_wrapCallback;
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
        }
      })();
    }
  }
});

// node_modules/scheduler/index.js
var require_scheduler = __commonJS({
  "node_modules/scheduler/index.js"(exports, module2) {
    "use strict";
    if (false) {
      module2.exports = null;
    } else {
      module2.exports = require_scheduler_development();
    }
  }
});

// node_modules/react-dom/cjs/react-dom.development.js
var require_react_dom_development = __commonJS({
  "node_modules/react-dom/cjs/react-dom.development.js"(exports) {
    "use strict";
    if (true) {
      (function() {
        "use strict";
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
        }
        var React145 = require_react();
        var Scheduler = require_scheduler();
        var ReactSharedInternals = React145.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
        var suppressWarning = false;
        function setSuppressWarning(newSuppressWarning) {
          {
            suppressWarning = newSuppressWarning;
          }
        }
        function warn2(format) {
          {
            if (!suppressWarning) {
              for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
              }
              printWarning("warn", format, args);
            }
          }
        }
        function error(format) {
          {
            if (!suppressWarning) {
              for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                args[_key2 - 1] = arguments[_key2];
              }
              printWarning("error", format, args);
            }
          }
        }
        function printWarning(level, format, args) {
          {
            var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
            var stack = ReactDebugCurrentFrame2.getStackAddendum();
            if (stack !== "") {
              format += "%s";
              args = args.concat([stack]);
            }
            var argsWithFormat = args.map(function(item) {
              return String(item);
            });
            argsWithFormat.unshift("Warning: " + format);
            Function.prototype.apply.call(console[level], console, argsWithFormat);
          }
        }
        var FunctionComponent = 0;
        var ClassComponent = 1;
        var IndeterminateComponent = 2;
        var HostRoot = 3;
        var HostPortal = 4;
        var HostComponent = 5;
        var HostText = 6;
        var Fragment21 = 7;
        var Mode = 8;
        var ContextConsumer = 9;
        var ContextProvider = 10;
        var ForwardRef = 11;
        var Profiler = 12;
        var SuspenseComponent = 13;
        var MemoComponent = 14;
        var SimpleMemoComponent = 15;
        var LazyComponent = 16;
        var IncompleteClassComponent = 17;
        var DehydratedFragment = 18;
        var SuspenseListComponent = 19;
        var ScopeComponent = 21;
        var OffscreenComponent = 22;
        var LegacyHiddenComponent = 23;
        var CacheComponent = 24;
        var TracingMarkerComponent = 25;
        var enableClientRenderFallbackOnTextMismatch = true;
        var enableNewReconciler = false;
        var enableLazyContextPropagation = false;
        var enableLegacyHidden = false;
        var enableSuspenseAvoidThisFallback = false;
        var disableCommentsAsDOMContainers = true;
        var enableCustomElementPropertySupport = false;
        var warnAboutStringRefs = false;
        var enableSchedulingProfiler = true;
        var enableProfilerTimer = true;
        var enableProfilerCommitHooks = true;
        var allNativeEvents = /* @__PURE__ */ new Set();
        var registrationNameDependencies = {};
        var possibleRegistrationNames = {};
        function registerTwoPhaseEvent(registrationName, dependencies) {
          registerDirectEvent(registrationName, dependencies);
          registerDirectEvent(registrationName + "Capture", dependencies);
        }
        function registerDirectEvent(registrationName, dependencies) {
          {
            if (registrationNameDependencies[registrationName]) {
              error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName);
            }
          }
          registrationNameDependencies[registrationName] = dependencies;
          {
            var lowerCasedName = registrationName.toLowerCase();
            possibleRegistrationNames[lowerCasedName] = registrationName;
            if (registrationName === "onDoubleClick") {
              possibleRegistrationNames.ondblclick = registrationName;
            }
          }
          for (var i3 = 0; i3 < dependencies.length; i3++) {
            allNativeEvents.add(dependencies[i3]);
          }
        }
        var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
        var hasOwnProperty3 = Object.prototype.hasOwnProperty;
        function typeName(value) {
          {
            var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
            var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
            return type;
          }
        }
        function willCoercionThrow(value) {
          {
            try {
              testStringCoercion(value);
              return false;
            } catch (e3) {
              return true;
            }
          }
        }
        function testStringCoercion(value) {
          return "" + value;
        }
        function checkAttributeStringCoercion(value, attributeName) {
          {
            if (willCoercionThrow(value)) {
              error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function checkKeyStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function checkPropStringCoercion(value, propName) {
          {
            if (willCoercionThrow(value)) {
              error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function checkCSSPropertyStringCoercion(value, propName) {
          {
            if (willCoercionThrow(value)) {
              error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function checkHtmlStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function checkFormFieldValueStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        var RESERVED = 0;
        var STRING = 1;
        var BOOLEANISH_STRING = 2;
        var BOOLEAN = 3;
        var OVERLOADED_BOOLEAN = 4;
        var NUMERIC = 5;
        var POSITIVE_NUMERIC = 6;
        var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
        var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
        var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$");
        var illegalAttributeNameCache = {};
        var validatedAttributeNameCache = {};
        function isAttributeNameSafe(attributeName) {
          if (hasOwnProperty3.call(validatedAttributeNameCache, attributeName)) {
            return true;
          }
          if (hasOwnProperty3.call(illegalAttributeNameCache, attributeName)) {
            return false;
          }
          if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
            validatedAttributeNameCache[attributeName] = true;
            return true;
          }
          illegalAttributeNameCache[attributeName] = true;
          {
            error("Invalid attribute name: `%s`", attributeName);
          }
          return false;
        }
        function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
          if (propertyInfo !== null) {
            return propertyInfo.type === RESERVED;
          }
          if (isCustomComponentTag) {
            return false;
          }
          if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) {
            return true;
          }
          return false;
        }
        function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
          if (propertyInfo !== null && propertyInfo.type === RESERVED) {
            return false;
          }
          switch (typeof value) {
            case "function":
            case "symbol":
              return true;
            case "boolean": {
              if (isCustomComponentTag) {
                return false;
              }
              if (propertyInfo !== null) {
                return !propertyInfo.acceptsBooleans;
              } else {
                var prefix2 = name.toLowerCase().slice(0, 5);
                return prefix2 !== "data-" && prefix2 !== "aria-";
              }
            }
            default:
              return false;
          }
        }
        function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
          if (value === null || typeof value === "undefined") {
            return true;
          }
          if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
            return true;
          }
          if (isCustomComponentTag) {
            return false;
          }
          if (propertyInfo !== null) {
            switch (propertyInfo.type) {
              case BOOLEAN:
                return !value;
              case OVERLOADED_BOOLEAN:
                return value === false;
              case NUMERIC:
                return isNaN(value);
              case POSITIVE_NUMERIC:
                return isNaN(value) || value < 1;
            }
          }
          return false;
        }
        function getPropertyInfo(name) {
          return properties.hasOwnProperty(name) ? properties[name] : null;
        }
        function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) {
          this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
          this.attributeName = attributeName;
          this.attributeNamespace = attributeNamespace;
          this.mustUseProperty = mustUseProperty;
          this.propertyName = name;
          this.type = type;
          this.sanitizeURL = sanitizeURL2;
          this.removeEmptyString = removeEmptyString;
        }
        var properties = {};
        var reservedProps = [
          "children",
          "dangerouslySetInnerHTML",
          // TODO: This prevents the assignment of defaultValue to regular
          // elements (not just inputs). Now that ReactDOMInput assigns to the
          // defaultValue property -- do we need this?
          "defaultValue",
          "defaultChecked",
          "innerHTML",
          "suppressContentEditableWarning",
          "suppressHydrationWarning",
          "style"
        ];
        reservedProps.forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            RESERVED,
            false,
            // mustUseProperty
            name,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) {
          var name = _ref[0], attributeName = _ref[1];
          properties[name] = new PropertyInfoRecord(
            name,
            STRING,
            false,
            // mustUseProperty
            attributeName,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            BOOLEANISH_STRING,
            false,
            // mustUseProperty
            name.toLowerCase(),
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            BOOLEANISH_STRING,
            false,
            // mustUseProperty
            name,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [
          "allowFullScreen",
          "async",
          // Note: there is a special case that prevents it from being written to the DOM
          // on the client side because the browsers are inconsistent. Instead we call focus().
          "autoFocus",
          "autoPlay",
          "controls",
          "default",
          "defer",
          "disabled",
          "disablePictureInPicture",
          "disableRemotePlayback",
          "formNoValidate",
          "hidden",
          "loop",
          "noModule",
          "noValidate",
          "open",
          "playsInline",
          "readOnly",
          "required",
          "reversed",
          "scoped",
          "seamless",
          // Microdata
          "itemScope"
        ].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            BOOLEAN,
            false,
            // mustUseProperty
            name.toLowerCase(),
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [
          "checked",
          // Note: `option.selected` is not updated if `select.multiple` is
          // disabled with `removeAttribute`. We have special logic for handling this.
          "multiple",
          "muted",
          "selected"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            BOOLEAN,
            true,
            // mustUseProperty
            name,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [
          "capture",
          "download"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            OVERLOADED_BOOLEAN,
            false,
            // mustUseProperty
            name,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [
          "cols",
          "rows",
          "size",
          "span"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            POSITIVE_NUMERIC,
            false,
            // mustUseProperty
            name,
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        ["rowSpan", "start"].forEach(function(name) {
          properties[name] = new PropertyInfoRecord(
            name,
            NUMERIC,
            false,
            // mustUseProperty
            name.toLowerCase(),
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        var CAMELIZE = /[\-\:]([a-z])/g;
        var capitalize = function(token) {
          return token[1].toUpperCase();
        };
        [
          "accent-height",
          "alignment-baseline",
          "arabic-form",
          "baseline-shift",
          "cap-height",
          "clip-path",
          "clip-rule",
          "color-interpolation",
          "color-interpolation-filters",
          "color-profile",
          "color-rendering",
          "dominant-baseline",
          "enable-background",
          "fill-opacity",
          "fill-rule",
          "flood-color",
          "flood-opacity",
          "font-family",
          "font-size",
          "font-size-adjust",
          "font-stretch",
          "font-style",
          "font-variant",
          "font-weight",
          "glyph-name",
          "glyph-orientation-horizontal",
          "glyph-orientation-vertical",
          "horiz-adv-x",
          "horiz-origin-x",
          "image-rendering",
          "letter-spacing",
          "lighting-color",
          "marker-end",
          "marker-mid",
          "marker-start",
          "overline-position",
          "overline-thickness",
          "paint-order",
          "panose-1",
          "pointer-events",
          "rendering-intent",
          "shape-rendering",
          "stop-color",
          "stop-opacity",
          "strikethrough-position",
          "strikethrough-thickness",
          "stroke-dasharray",
          "stroke-dashoffset",
          "stroke-linecap",
          "stroke-linejoin",
          "stroke-miterlimit",
          "stroke-opacity",
          "stroke-width",
          "text-anchor",
          "text-decoration",
          "text-rendering",
          "underline-position",
          "underline-thickness",
          "unicode-bidi",
          "unicode-range",
          "units-per-em",
          "v-alphabetic",
          "v-hanging",
          "v-ideographic",
          "v-mathematical",
          "vector-effect",
          "vert-adv-y",
          "vert-origin-x",
          "vert-origin-y",
          "word-spacing",
          "writing-mode",
          "xmlns:xlink",
          "x-height"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(attributeName) {
          var name = attributeName.replace(CAMELIZE, capitalize);
          properties[name] = new PropertyInfoRecord(
            name,
            STRING,
            false,
            // mustUseProperty
            attributeName,
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        [
          "xlink:actuate",
          "xlink:arcrole",
          "xlink:role",
          "xlink:show",
          "xlink:title",
          "xlink:type"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(attributeName) {
          var name = attributeName.replace(CAMELIZE, capitalize);
          properties[name] = new PropertyInfoRecord(
            name,
            STRING,
            false,
            // mustUseProperty
            attributeName,
            "http://www.w3.org/1999/xlink",
            false,
            // sanitizeURL
            false
          );
        });
        [
          "xml:base",
          "xml:lang",
          "xml:space"
          // NOTE: if you add a camelCased prop to this list,
          // you'll need to set attributeName to name.toLowerCase()
          // instead in the assignment below.
        ].forEach(function(attributeName) {
          var name = attributeName.replace(CAMELIZE, capitalize);
          properties[name] = new PropertyInfoRecord(
            name,
            STRING,
            false,
            // mustUseProperty
            attributeName,
            "http://www.w3.org/XML/1998/namespace",
            false,
            // sanitizeURL
            false
          );
        });
        ["tabIndex", "crossOrigin"].forEach(function(attributeName) {
          properties[attributeName] = new PropertyInfoRecord(
            attributeName,
            STRING,
            false,
            // mustUseProperty
            attributeName.toLowerCase(),
            // attributeName
            null,
            // attributeNamespace
            false,
            // sanitizeURL
            false
          );
        });
        var xlinkHref = "xlinkHref";
        properties[xlinkHref] = new PropertyInfoRecord(
          "xlinkHref",
          STRING,
          false,
          // mustUseProperty
          "xlink:href",
          "http://www.w3.org/1999/xlink",
          true,
          // sanitizeURL
          false
        );
        ["src", "href", "action", "formAction"].forEach(function(attributeName) {
          properties[attributeName] = new PropertyInfoRecord(
            attributeName,
            STRING,
            false,
            // mustUseProperty
            attributeName.toLowerCase(),
            // attributeName
            null,
            // attributeNamespace
            true,
            // sanitizeURL
            true
          );
        });
        var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
        var didWarn = false;
        function sanitizeURL(url) {
          {
            if (!didWarn && isJavaScriptProtocol.test(url)) {
              didWarn = true;
              error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url));
            }
          }
        }
        function getValueForProperty(node, name, expected, propertyInfo) {
          {
            if (propertyInfo.mustUseProperty) {
              var propertyName = propertyInfo.propertyName;
              return node[propertyName];
            } else {
              {
                checkAttributeStringCoercion(expected, name);
              }
              if (propertyInfo.sanitizeURL) {
                sanitizeURL("" + expected);
              }
              var attributeName = propertyInfo.attributeName;
              var stringValue = null;
              if (propertyInfo.type === OVERLOADED_BOOLEAN) {
                if (node.hasAttribute(attributeName)) {
                  var value = node.getAttribute(attributeName);
                  if (value === "") {
                    return true;
                  }
                  if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                    return value;
                  }
                  if (value === "" + expected) {
                    return expected;
                  }
                  return value;
                }
              } else if (node.hasAttribute(attributeName)) {
                if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                  return node.getAttribute(attributeName);
                }
                if (propertyInfo.type === BOOLEAN) {
                  return expected;
                }
                stringValue = node.getAttribute(attributeName);
              }
              if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                return stringValue === null ? expected : stringValue;
              } else if (stringValue === "" + expected) {
                return expected;
              } else {
                return stringValue;
              }
            }
          }
        }
        function getValueForAttribute(node, name, expected, isCustomComponentTag) {
          {
            if (!isAttributeNameSafe(name)) {
              return;
            }
            if (!node.hasAttribute(name)) {
              return expected === void 0 ? void 0 : null;
            }
            var value = node.getAttribute(name);
            {
              checkAttributeStringCoercion(expected, name);
            }
            if (value === "" + expected) {
              return expected;
            }
            return value;
          }
        }
        function setValueForProperty(node, name, value, isCustomComponentTag) {
          var propertyInfo = getPropertyInfo(name);
          if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
            return;
          }
          if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
            value = null;
          }
          if (isCustomComponentTag || propertyInfo === null) {
            if (isAttributeNameSafe(name)) {
              var _attributeName = name;
              if (value === null) {
                node.removeAttribute(_attributeName);
              } else {
                {
                  checkAttributeStringCoercion(value, name);
                }
                node.setAttribute(_attributeName, "" + value);
              }
            }
            return;
          }
          var mustUseProperty = propertyInfo.mustUseProperty;
          if (mustUseProperty) {
            var propertyName = propertyInfo.propertyName;
            if (value === null) {
              var type = propertyInfo.type;
              node[propertyName] = type === BOOLEAN ? false : "";
            } else {
              node[propertyName] = value;
            }
            return;
          }
          var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace;
          if (value === null) {
            node.removeAttribute(attributeName);
          } else {
            var _type = propertyInfo.type;
            var attributeValue;
            if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
              attributeValue = "";
            } else {
              {
                {
                  checkAttributeStringCoercion(value, attributeName);
                }
                attributeValue = "" + value;
              }
              if (propertyInfo.sanitizeURL) {
                sanitizeURL(attributeValue.toString());
              }
            }
            if (attributeNamespace) {
              node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
            } else {
              node.setAttribute(attributeName, attributeValue);
            }
          }
        }
        var REACT_ELEMENT_TYPE = Symbol.for("react.element");
        var REACT_PORTAL_TYPE = Symbol.for("react.portal");
        var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
        var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
        var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
        var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
        var REACT_CONTEXT_TYPE = Symbol.for("react.context");
        var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
        var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
        var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
        var REACT_MEMO_TYPE = Symbol.for("react.memo");
        var REACT_LAZY_TYPE = Symbol.for("react.lazy");
        var REACT_SCOPE_TYPE = Symbol.for("react.scope");
        var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode");
        var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
        var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden");
        var REACT_CACHE_TYPE = Symbol.for("react.cache");
        var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker");
        var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
        var FAUX_ITERATOR_SYMBOL = "@@iterator";
        function getIteratorFn(maybeIterable) {
          if (maybeIterable === null || typeof maybeIterable !== "object") {
            return null;
          }
          var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
          if (typeof maybeIterator === "function") {
            return maybeIterator;
          }
          return null;
        }
        var assign = Object.assign;
        var disabledDepth = 0;
        var prevLog;
        var prevInfo;
        var prevWarn;
        var prevError;
        var prevGroup;
        var prevGroupCollapsed;
        var prevGroupEnd;
        function disabledLog() {
        }
        disabledLog.__reactDisabledLog = true;
        function disableLogs() {
          {
            if (disabledDepth === 0) {
              prevLog = console.log;
              prevInfo = console.info;
              prevWarn = console.warn;
              prevError = console.error;
              prevGroup = console.group;
              prevGroupCollapsed = console.groupCollapsed;
              prevGroupEnd = console.groupEnd;
              var props = {
                configurable: true,
                enumerable: true,
                value: disabledLog,
                writable: true
              };
              Object.defineProperties(console, {
                info: props,
                log: props,
                warn: props,
                error: props,
                group: props,
                groupCollapsed: props,
                groupEnd: props
              });
            }
            disabledDepth++;
          }
        }
        function reenableLogs() {
          {
            disabledDepth--;
            if (disabledDepth === 0) {
              var props = {
                configurable: true,
                enumerable: true,
                writable: true
              };
              Object.defineProperties(console, {
                log: assign({}, props, {
                  value: prevLog
                }),
                info: assign({}, props, {
                  value: prevInfo
                }),
                warn: assign({}, props, {
                  value: prevWarn
                }),
                error: assign({}, props, {
                  value: prevError
                }),
                group: assign({}, props, {
                  value: prevGroup
                }),
                groupCollapsed: assign({}, props, {
                  value: prevGroupCollapsed
                }),
                groupEnd: assign({}, props, {
                  value: prevGroupEnd
                })
              });
            }
            if (disabledDepth < 0) {
              error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
            }
          }
        }
        var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
        var prefix;
        function describeBuiltInComponentFrame(name, source, ownerFn) {
          {
            if (prefix === void 0) {
              try {
                throw Error();
              } catch (x2) {
                var match2 = x2.stack.trim().match(/\n( *(at )?)/);
                prefix = match2 && match2[1] || "";
              }
            }
            return "\n" + prefix + name;
          }
        }
        var reentry = false;
        var componentFrameCache;
        {
          var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
          componentFrameCache = new PossiblyWeakMap();
        }
        function describeNativeComponentFrame(fn, construct) {
          if (!fn || reentry) {
            return "";
          }
          {
            var frame = componentFrameCache.get(fn);
            if (frame !== void 0) {
              return frame;
            }
          }
          var control;
          reentry = true;
          var previousPrepareStackTrace = Error.prepareStackTrace;
          Error.prepareStackTrace = void 0;
          var previousDispatcher;
          {
            previousDispatcher = ReactCurrentDispatcher.current;
            ReactCurrentDispatcher.current = null;
            disableLogs();
          }
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if (typeof Reflect === "object" && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x2) {
                  control = x2;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x2) {
                control = x2;
              }
              fn();
            }
          } catch (sample) {
            if (sample && control && typeof sample.stack === "string") {
              var sampleLines = sample.stack.split("\n");
              var controlLines = control.stack.split("\n");
              var s4 = sampleLines.length - 1;
              var c4 = controlLines.length - 1;
              while (s4 >= 1 && c4 >= 0 && sampleLines[s4] !== controlLines[c4]) {
                c4--;
              }
              for (; s4 >= 1 && c4 >= 0; s4--, c4--) {
                if (sampleLines[s4] !== controlLines[c4]) {
                  if (s4 !== 1 || c4 !== 1) {
                    do {
                      s4--;
                      c4--;
                      if (c4 < 0 || sampleLines[s4] !== controlLines[c4]) {
                        var _frame = "\n" + sampleLines[s4].replace(" at new ", " at ");
                        if (fn.displayName && _frame.includes("<anonymous>")) {
                          _frame = _frame.replace("<anonymous>", fn.displayName);
                        }
                        {
                          if (typeof fn === "function") {
                            componentFrameCache.set(fn, _frame);
                          }
                        }
                        return _frame;
                      }
                    } while (s4 >= 1 && c4 >= 0);
                  }
                  break;
                }
              }
            }
          } finally {
            reentry = false;
            {
              ReactCurrentDispatcher.current = previousDispatcher;
              reenableLogs();
            }
            Error.prepareStackTrace = previousPrepareStackTrace;
          }
          var name = fn ? fn.displayName || fn.name : "";
          var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
          {
            if (typeof fn === "function") {
              componentFrameCache.set(fn, syntheticFrame);
            }
          }
          return syntheticFrame;
        }
        function describeClassComponentFrame(ctor, source, ownerFn) {
          {
            return describeNativeComponentFrame(ctor, true);
          }
        }
        function describeFunctionComponentFrame(fn, source, ownerFn) {
          {
            return describeNativeComponentFrame(fn, false);
          }
        }
        function shouldConstruct(Component2) {
          var prototype = Component2.prototype;
          return !!(prototype && prototype.isReactComponent);
        }
        function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
          if (type == null) {
            return "";
          }
          if (typeof type === "function") {
            {
              return describeNativeComponentFrame(type, shouldConstruct(type));
            }
          }
          if (typeof type === "string") {
            return describeBuiltInComponentFrame(type);
          }
          switch (type) {
            case REACT_SUSPENSE_TYPE:
              return describeBuiltInComponentFrame("Suspense");
            case REACT_SUSPENSE_LIST_TYPE:
              return describeBuiltInComponentFrame("SuspenseList");
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_FORWARD_REF_TYPE:
                return describeFunctionComponentFrame(type.render);
              case REACT_MEMO_TYPE:
                return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
                } catch (x2) {
                }
              }
            }
          }
          return "";
        }
        function describeFiber(fiber) {
          var owner = fiber._debugOwner ? fiber._debugOwner.type : null;
          var source = fiber._debugSource;
          switch (fiber.tag) {
            case HostComponent:
              return describeBuiltInComponentFrame(fiber.type);
            case LazyComponent:
              return describeBuiltInComponentFrame("Lazy");
            case SuspenseComponent:
              return describeBuiltInComponentFrame("Suspense");
            case SuspenseListComponent:
              return describeBuiltInComponentFrame("SuspenseList");
            case FunctionComponent:
            case IndeterminateComponent:
            case SimpleMemoComponent:
              return describeFunctionComponentFrame(fiber.type);
            case ForwardRef:
              return describeFunctionComponentFrame(fiber.type.render);
            case ClassComponent:
              return describeClassComponentFrame(fiber.type);
            default:
              return "";
          }
        }
        function getStackByFiberInDevAndProd(workInProgress2) {
          try {
            var info = "";
            var node = workInProgress2;
            do {
              info += describeFiber(node);
              node = node.return;
            } while (node);
            return info;
          } catch (x2) {
            return "\nError generating stack: " + x2.message + "\n" + x2.stack;
          }
        }
        function getWrappedName(outerType, innerType, wrapperName) {
          var displayName = outerType.displayName;
          if (displayName) {
            return displayName;
          }
          var functionName = innerType.displayName || innerType.name || "";
          return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
        }
        function getContextName(type) {
          return type.displayName || "Context";
        }
        function getComponentNameFromType(type) {
          if (type == null) {
            return null;
          }
          {
            if (typeof type.tag === "number") {
              error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
            }
          }
          if (typeof type === "function") {
            return type.displayName || type.name || null;
          }
          if (typeof type === "string") {
            return type;
          }
          switch (type) {
            case REACT_FRAGMENT_TYPE:
              return "Fragment";
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_PROFILER_TYPE:
              return "Profiler";
            case REACT_STRICT_MODE_TYPE:
              return "StrictMode";
            case REACT_SUSPENSE_TYPE:
              return "Suspense";
            case REACT_SUSPENSE_LIST_TYPE:
              return "SuspenseList";
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_CONTEXT_TYPE:
                var context = type;
                return getContextName(context) + ".Consumer";
              case REACT_PROVIDER_TYPE:
                var provider = type;
                return getContextName(provider._context) + ".Provider";
              case REACT_FORWARD_REF_TYPE:
                return getWrappedName(type, type.render, "ForwardRef");
              case REACT_MEMO_TYPE:
                var outerName = type.displayName || null;
                if (outerName !== null) {
                  return outerName;
                }
                return getComponentNameFromType(type.type) || "Memo";
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return getComponentNameFromType(init(payload));
                } catch (x2) {
                  return null;
                }
              }
            }
          }
          return null;
        }
        function getWrappedName$1(outerType, innerType, wrapperName) {
          var functionName = innerType.displayName || innerType.name || "";
          return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName);
        }
        function getContextName$1(type) {
          return type.displayName || "Context";
        }
        function getComponentNameFromFiber(fiber) {
          var tag = fiber.tag, type = fiber.type;
          switch (tag) {
            case CacheComponent:
              return "Cache";
            case ContextConsumer:
              var context = type;
              return getContextName$1(context) + ".Consumer";
            case ContextProvider:
              var provider = type;
              return getContextName$1(provider._context) + ".Provider";
            case DehydratedFragment:
              return "DehydratedFragment";
            case ForwardRef:
              return getWrappedName$1(type, type.render, "ForwardRef");
            case Fragment21:
              return "Fragment";
            case HostComponent:
              return type;
            case HostPortal:
              return "Portal";
            case HostRoot:
              return "Root";
            case HostText:
              return "Text";
            case LazyComponent:
              return getComponentNameFromType(type);
            case Mode:
              if (type === REACT_STRICT_MODE_TYPE) {
                return "StrictMode";
              }
              return "Mode";
            case OffscreenComponent:
              return "Offscreen";
            case Profiler:
              return "Profiler";
            case ScopeComponent:
              return "Scope";
            case SuspenseComponent:
              return "Suspense";
            case SuspenseListComponent:
              return "SuspenseList";
            case TracingMarkerComponent:
              return "TracingMarker";
            case ClassComponent:
            case FunctionComponent:
            case IncompleteClassComponent:
            case IndeterminateComponent:
            case MemoComponent:
            case SimpleMemoComponent:
              if (typeof type === "function") {
                return type.displayName || type.name || null;
              }
              if (typeof type === "string") {
                return type;
              }
              break;
          }
          return null;
        }
        var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
        var current = null;
        var isRendering = false;
        function getCurrentFiberOwnerNameInDevOrNull() {
          {
            if (current === null) {
              return null;
            }
            var owner = current._debugOwner;
            if (owner !== null && typeof owner !== "undefined") {
              return getComponentNameFromFiber(owner);
            }
          }
          return null;
        }
        function getCurrentFiberStackInDev() {
          {
            if (current === null) {
              return "";
            }
            return getStackByFiberInDevAndProd(current);
          }
        }
        function resetCurrentFiber() {
          {
            ReactDebugCurrentFrame.getCurrentStack = null;
            current = null;
            isRendering = false;
          }
        }
        function setCurrentFiber(fiber) {
          {
            ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
            current = fiber;
            isRendering = false;
          }
        }
        function getCurrentFiber() {
          {
            return current;
          }
        }
        function setIsRendering(rendering) {
          {
            isRendering = rendering;
          }
        }
        function toString(value) {
          return "" + value;
        }
        function getToStringValue(value) {
          switch (typeof value) {
            case "boolean":
            case "number":
            case "string":
            case "undefined":
              return value;
            case "object":
              {
                checkFormFieldValueStringCoercion(value);
              }
              return value;
            default:
              return "";
          }
        }
        var hasReadOnlyValue = {
          button: true,
          checkbox: true,
          image: true,
          hidden: true,
          radio: true,
          reset: true,
          submit: true
        };
        function checkControlledValueProps(tagName, props) {
          {
            if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
              error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.");
            }
            if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
              error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.");
            }
          }
        }
        function isCheckable(elem) {
          var type = elem.type;
          var nodeName = elem.nodeName;
          return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio");
        }
        function getTracker(node) {
          return node._valueTracker;
        }
        function detachTracker(node) {
          node._valueTracker = null;
        }
        function getValueFromNode(node) {
          var value = "";
          if (!node) {
            return value;
          }
          if (isCheckable(node)) {
            value = node.checked ? "true" : "false";
          } else {
            value = node.value;
          }
          return value;
        }
        function trackValueOnNode(node) {
          var valueField = isCheckable(node) ? "checked" : "value";
          var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
          {
            checkFormFieldValueStringCoercion(node[valueField]);
          }
          var currentValue = "" + node[valueField];
          if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") {
            return;
          }
          var get5 = descriptor.get, set2 = descriptor.set;
          Object.defineProperty(node, valueField, {
            configurable: true,
            get: function() {
              return get5.call(this);
            },
            set: function(value) {
              {
                checkFormFieldValueStringCoercion(value);
              }
              currentValue = "" + value;
              set2.call(this, value);
            }
          });
          Object.defineProperty(node, valueField, {
            enumerable: descriptor.enumerable
          });
          var tracker = {
            getValue: function() {
              return currentValue;
            },
            setValue: function(value) {
              {
                checkFormFieldValueStringCoercion(value);
              }
              currentValue = "" + value;
            },
            stopTracking: function() {
              detachTracker(node);
              delete node[valueField];
            }
          };
          return tracker;
        }
        function track(node) {
          if (getTracker(node)) {
            return;
          }
          node._valueTracker = trackValueOnNode(node);
        }
        function updateValueIfChanged(node) {
          if (!node) {
            return false;
          }
          var tracker = getTracker(node);
          if (!tracker) {
            return true;
          }
          var lastValue = tracker.getValue();
          var nextValue = getValueFromNode(node);
          if (nextValue !== lastValue) {
            tracker.setValue(nextValue);
            return true;
          }
          return false;
        }
        function getActiveElement(doc) {
          doc = doc || (typeof document !== "undefined" ? document : void 0);
          if (typeof doc === "undefined") {
            return null;
          }
          try {
            return doc.activeElement || doc.body;
          } catch (e3) {
            return doc.body;
          }
        }
        var didWarnValueDefaultValue = false;
        var didWarnCheckedDefaultChecked = false;
        var didWarnControlledToUncontrolled = false;
        var didWarnUncontrolledToControlled = false;
        function isControlled(props) {
          var usesChecked = props.type === "checkbox" || props.type === "radio";
          return usesChecked ? props.checked != null : props.value != null;
        }
        function getHostProps(element, props) {
          var node = element;
          var checked = props.checked;
          var hostProps = assign({}, props, {
            defaultChecked: void 0,
            defaultValue: void 0,
            value: void 0,
            checked: checked != null ? checked : node._wrapperState.initialChecked
          });
          return hostProps;
        }
        function initWrapperState(element, props) {
          {
            checkControlledValueProps("input", props);
            if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) {
              error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
              didWarnCheckedDefaultChecked = true;
            }
            if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) {
              error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
              didWarnValueDefaultValue = true;
            }
          }
          var node = element;
          var defaultValue = props.defaultValue == null ? "" : props.defaultValue;
          node._wrapperState = {
            initialChecked: props.checked != null ? props.checked : props.defaultChecked,
            initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
            controlled: isControlled(props)
          };
        }
        function updateChecked(element, props) {
          var node = element;
          var checked = props.checked;
          if (checked != null) {
            setValueForProperty(node, "checked", checked, false);
          }
        }
        function updateWrapper(element, props) {
          var node = element;
          {
            var controlled = isControlled(props);
            if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
              error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
              didWarnUncontrolledToControlled = true;
            }
            if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
              error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
              didWarnControlledToUncontrolled = true;
            }
          }
          updateChecked(element, props);
          var value = getToStringValue(props.value);
          var type = props.type;
          if (value != null) {
            if (type === "number") {
              if (value === 0 && node.value === "" || // We explicitly want to coerce to number here if possible.
              // eslint-disable-next-line
              node.value != value) {
                node.value = toString(value);
              }
            } else if (node.value !== toString(value)) {
              node.value = toString(value);
            }
          } else if (type === "submit" || type === "reset") {
            node.removeAttribute("value");
            return;
          }
          {
            if (props.hasOwnProperty("value")) {
              setDefaultValue(node, props.type, value);
            } else if (props.hasOwnProperty("defaultValue")) {
              setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
            }
          }
          {
            if (props.checked == null && props.defaultChecked != null) {
              node.defaultChecked = !!props.defaultChecked;
            }
          }
        }
        function postMountWrapper(element, props, isHydrating2) {
          var node = element;
          if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) {
            var type = props.type;
            var isButton = type === "submit" || type === "reset";
            if (isButton && (props.value === void 0 || props.value === null)) {
              return;
            }
            var initialValue = toString(node._wrapperState.initialValue);
            if (!isHydrating2) {
              {
                if (initialValue !== node.value) {
                  node.value = initialValue;
                }
              }
            }
            {
              node.defaultValue = initialValue;
            }
          }
          var name = node.name;
          if (name !== "") {
            node.name = "";
          }
          {
            node.defaultChecked = !node.defaultChecked;
            node.defaultChecked = !!node._wrapperState.initialChecked;
          }
          if (name !== "") {
            node.name = name;
          }
        }
        function restoreControlledState(element, props) {
          var node = element;
          updateWrapper(node, props);
          updateNamedCousins(node, props);
        }
        function updateNamedCousins(rootNode, props) {
          var name = props.name;
          if (props.type === "radio" && name != null) {
            var queryRoot = rootNode;
            while (queryRoot.parentNode) {
              queryRoot = queryRoot.parentNode;
            }
            {
              checkAttributeStringCoercion(name, "name");
            }
            var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]');
            for (var i3 = 0; i3 < group.length; i3++) {
              var otherNode = group[i3];
              if (otherNode === rootNode || otherNode.form !== rootNode.form) {
                continue;
              }
              var otherProps = getFiberCurrentPropsFromNode(otherNode);
              if (!otherProps) {
                throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
              }
              updateValueIfChanged(otherNode);
              updateWrapper(otherNode, otherProps);
            }
          }
        }
        function setDefaultValue(node, type, value) {
          if (
            // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
            type !== "number" || getActiveElement(node.ownerDocument) !== node
          ) {
            if (value == null) {
              node.defaultValue = toString(node._wrapperState.initialValue);
            } else if (node.defaultValue !== toString(value)) {
              node.defaultValue = toString(value);
            }
          }
        }
        var didWarnSelectedSetOnOption = false;
        var didWarnInvalidChild = false;
        var didWarnInvalidInnerHTML = false;
        function validateProps(element, props) {
          {
            if (props.value == null) {
              if (typeof props.children === "object" && props.children !== null) {
                React145.Children.forEach(props.children, function(child) {
                  if (child == null) {
                    return;
                  }
                  if (typeof child === "string" || typeof child === "number") {
                    return;
                  }
                  if (!didWarnInvalidChild) {
                    didWarnInvalidChild = true;
                    error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>.");
                  }
                });
              } else if (props.dangerouslySetInnerHTML != null) {
                if (!didWarnInvalidInnerHTML) {
                  didWarnInvalidInnerHTML = true;
                  error("Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected.");
                }
              }
            }
            if (props.selected != null && !didWarnSelectedSetOnOption) {
              error("Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.");
              didWarnSelectedSetOnOption = true;
            }
          }
        }
        function postMountWrapper$1(element, props) {
          if (props.value != null) {
            element.setAttribute("value", toString(getToStringValue(props.value)));
          }
        }
        var isArrayImpl = Array.isArray;
        function isArray2(a3) {
          return isArrayImpl(a3);
        }
        var didWarnValueDefaultValue$1;
        {
          didWarnValueDefaultValue$1 = false;
        }
        function getDeclarationErrorAddendum() {
          var ownerName = getCurrentFiberOwnerNameInDevOrNull();
          if (ownerName) {
            return "\n\nCheck the render method of `" + ownerName + "`.";
          }
          return "";
        }
        var valuePropNames = ["value", "defaultValue"];
        function checkSelectPropTypes(props) {
          {
            checkControlledValueProps("select", props);
            for (var i3 = 0; i3 < valuePropNames.length; i3++) {
              var propName = valuePropNames[i3];
              if (props[propName] == null) {
                continue;
              }
              var propNameIsArray = isArray2(props[propName]);
              if (props.multiple && !propNameIsArray) {
                error("The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum());
              } else if (!props.multiple && propNameIsArray) {
                error("The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum());
              }
            }
          }
        }
        function updateOptions(node, multiple, propValue, setDefaultSelected) {
          var options2 = node.options;
          if (multiple) {
            var selectedValues = propValue;
            var selectedValue = {};
            for (var i3 = 0; i3 < selectedValues.length; i3++) {
              selectedValue["$" + selectedValues[i3]] = true;
            }
            for (var _i = 0; _i < options2.length; _i++) {
              var selected = selectedValue.hasOwnProperty("$" + options2[_i].value);
              if (options2[_i].selected !== selected) {
                options2[_i].selected = selected;
              }
              if (selected && setDefaultSelected) {
                options2[_i].defaultSelected = true;
              }
            }
          } else {
            var _selectedValue = toString(getToStringValue(propValue));
            var defaultSelected = null;
            for (var _i2 = 0; _i2 < options2.length; _i2++) {
              if (options2[_i2].value === _selectedValue) {
                options2[_i2].selected = true;
                if (setDefaultSelected) {
                  options2[_i2].defaultSelected = true;
                }
                return;
              }
              if (defaultSelected === null && !options2[_i2].disabled) {
                defaultSelected = options2[_i2];
              }
            }
            if (defaultSelected !== null) {
              defaultSelected.selected = true;
            }
          }
        }
        function getHostProps$1(element, props) {
          return assign({}, props, {
            value: void 0
          });
        }
        function initWrapperState$1(element, props) {
          var node = element;
          {
            checkSelectPropTypes(props);
          }
          node._wrapperState = {
            wasMultiple: !!props.multiple
          };
          {
            if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue$1) {
              error("Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://reactjs.org/link/controlled-components");
              didWarnValueDefaultValue$1 = true;
            }
          }
        }
        function postMountWrapper$2(element, props) {
          var node = element;
          node.multiple = !!props.multiple;
          var value = props.value;
          if (value != null) {
            updateOptions(node, !!props.multiple, value, false);
          } else if (props.defaultValue != null) {
            updateOptions(node, !!props.multiple, props.defaultValue, true);
          }
        }
        function postUpdateWrapper(element, props) {
          var node = element;
          var wasMultiple = node._wrapperState.wasMultiple;
          node._wrapperState.wasMultiple = !!props.multiple;
          var value = props.value;
          if (value != null) {
            updateOptions(node, !!props.multiple, value, false);
          } else if (wasMultiple !== !!props.multiple) {
            if (props.defaultValue != null) {
              updateOptions(node, !!props.multiple, props.defaultValue, true);
            } else {
              updateOptions(node, !!props.multiple, props.multiple ? [] : "", false);
            }
          }
        }
        function restoreControlledState$1(element, props) {
          var node = element;
          var value = props.value;
          if (value != null) {
            updateOptions(node, !!props.multiple, value, false);
          }
        }
        var didWarnValDefaultVal = false;
        function getHostProps$2(element, props) {
          var node = element;
          if (props.dangerouslySetInnerHTML != null) {
            throw new Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
          }
          var hostProps = assign({}, props, {
            value: void 0,
            defaultValue: void 0,
            children: toString(node._wrapperState.initialValue)
          });
          return hostProps;
        }
        function initWrapperState$2(element, props) {
          var node = element;
          {
            checkControlledValueProps("textarea", props);
            if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValDefaultVal) {
              error("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component");
              didWarnValDefaultVal = true;
            }
          }
          var initialValue = props.value;
          if (initialValue == null) {
            var children = props.children, defaultValue = props.defaultValue;
            if (children != null) {
              {
                error("Use the `defaultValue` or `value` props instead of setting children on <textarea>.");
              }
              {
                if (defaultValue != null) {
                  throw new Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
                }
                if (isArray2(children)) {
                  if (children.length > 1) {
                    throw new Error("<textarea> can only have at most one child.");
                  }
                  children = children[0];
                }
                defaultValue = children;
              }
            }
            if (defaultValue == null) {
              defaultValue = "";
            }
            initialValue = defaultValue;
          }
          node._wrapperState = {
            initialValue: getToStringValue(initialValue)
          };
        }
        function updateWrapper$1(element, props) {
          var node = element;
          var value = getToStringValue(props.value);
          var defaultValue = getToStringValue(props.defaultValue);
          if (value != null) {
            var newValue = toString(value);
            if (newValue !== node.value) {
              node.value = newValue;
            }
            if (props.defaultValue == null && node.defaultValue !== newValue) {
              node.defaultValue = newValue;
            }
          }
          if (defaultValue != null) {
            node.defaultValue = toString(defaultValue);
          }
        }
        function postMountWrapper$3(element, props) {
          var node = element;
          var textContent = node.textContent;
          if (textContent === node._wrapperState.initialValue) {
            if (textContent !== "" && textContent !== null) {
              node.value = textContent;
            }
          }
        }
        function restoreControlledState$2(element, props) {
          updateWrapper$1(element, props);
        }
        var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
        var MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
        var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
        function getIntrinsicNamespace(type) {
          switch (type) {
            case "svg":
              return SVG_NAMESPACE;
            case "math":
              return MATH_NAMESPACE;
            default:
              return HTML_NAMESPACE;
          }
        }
        function getChildNamespace(parentNamespace, type) {
          if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
            return getIntrinsicNamespace(type);
          }
          if (parentNamespace === SVG_NAMESPACE && type === "foreignObject") {
            return HTML_NAMESPACE;
          }
          return parentNamespace;
        }
        var createMicrosoftUnsafeLocalFunction = function(func) {
          if (typeof MSApp !== "undefined" && MSApp.execUnsafeLocalFunction) {
            return function(arg0, arg1, arg2, arg3) {
              MSApp.execUnsafeLocalFunction(function() {
                return func(arg0, arg1, arg2, arg3);
              });
            };
          } else {
            return func;
          }
        };
        var reusableSVGContainer;
        var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) {
          if (node.namespaceURI === SVG_NAMESPACE) {
            if (!("innerHTML" in node)) {
              reusableSVGContainer = reusableSVGContainer || document.createElement("div");
              reusableSVGContainer.innerHTML = "<svg>" + html.valueOf().toString() + "</svg>";
              var svgNode = reusableSVGContainer.firstChild;
              while (node.firstChild) {
                node.removeChild(node.firstChild);
              }
              while (svgNode.firstChild) {
                node.appendChild(svgNode.firstChild);
              }
              return;
            }
          }
          node.innerHTML = html;
        });
        var ELEMENT_NODE = 1;
        var TEXT_NODE = 3;
        var COMMENT_NODE = 8;
        var DOCUMENT_NODE = 9;
        var DOCUMENT_FRAGMENT_NODE = 11;
        var setTextContent = function(node, text) {
          if (text) {
            var firstChild = node.firstChild;
            if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
              firstChild.nodeValue = text;
              return;
            }
          }
          node.textContent = text;
        };
        var shorthandToLonghand = {
          animation: ["animationDelay", "animationDirection", "animationDuration", "animationFillMode", "animationIterationCount", "animationName", "animationPlayState", "animationTimingFunction"],
          background: ["backgroundAttachment", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundOrigin", "backgroundPositionX", "backgroundPositionY", "backgroundRepeat", "backgroundSize"],
          backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
          border: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth", "borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth", "borderLeftColor", "borderLeftStyle", "borderLeftWidth", "borderRightColor", "borderRightStyle", "borderRightWidth", "borderTopColor", "borderTopStyle", "borderTopWidth"],
          borderBlockEnd: ["borderBlockEndColor", "borderBlockEndStyle", "borderBlockEndWidth"],
          borderBlockStart: ["borderBlockStartColor", "borderBlockStartStyle", "borderBlockStartWidth"],
          borderBottom: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth"],
          borderColor: ["borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor"],
          borderImage: ["borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth"],
          borderInlineEnd: ["borderInlineEndColor", "borderInlineEndStyle", "borderInlineEndWidth"],
          borderInlineStart: ["borderInlineStartColor", "borderInlineStartStyle", "borderInlineStartWidth"],
          borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
          borderRadius: ["borderBottomLeftRadius", "borderBottomRightRadius", "borderTopLeftRadius", "borderTopRightRadius"],
          borderRight: ["borderRightColor", "borderRightStyle", "borderRightWidth"],
          borderStyle: ["borderBottomStyle", "borderLeftStyle", "borderRightStyle", "borderTopStyle"],
          borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
          borderWidth: ["borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderTopWidth"],
          columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
          columns: ["columnCount", "columnWidth"],
          flex: ["flexBasis", "flexGrow", "flexShrink"],
          flexFlow: ["flexDirection", "flexWrap"],
          font: ["fontFamily", "fontFeatureSettings", "fontKerning", "fontLanguageOverride", "fontSize", "fontSizeAdjust", "fontStretch", "fontStyle", "fontVariant", "fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition", "fontWeight", "lineHeight"],
          fontVariant: ["fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition"],
          gap: ["columnGap", "rowGap"],
          grid: ["gridAutoColumns", "gridAutoFlow", "gridAutoRows", "gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
          gridArea: ["gridColumnEnd", "gridColumnStart", "gridRowEnd", "gridRowStart"],
          gridColumn: ["gridColumnEnd", "gridColumnStart"],
          gridColumnGap: ["columnGap"],
          gridGap: ["columnGap", "rowGap"],
          gridRow: ["gridRowEnd", "gridRowStart"],
          gridRowGap: ["rowGap"],
          gridTemplate: ["gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
          listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
          margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
          marker: ["markerEnd", "markerMid", "markerStart"],
          mask: ["maskClip", "maskComposite", "maskImage", "maskMode", "maskOrigin", "maskPositionX", "maskPositionY", "maskRepeat", "maskSize"],
          maskPosition: ["maskPositionX", "maskPositionY"],
          outline: ["outlineColor", "outlineStyle", "outlineWidth"],
          overflow: ["overflowX", "overflowY"],
          padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
          placeContent: ["alignContent", "justifyContent"],
          placeItems: ["alignItems", "justifyItems"],
          placeSelf: ["alignSelf", "justifySelf"],
          textDecoration: ["textDecorationColor", "textDecorationLine", "textDecorationStyle"],
          textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
          transition: ["transitionDelay", "transitionDuration", "transitionProperty", "transitionTimingFunction"],
          wordWrap: ["overflowWrap"]
        };
        var isUnitlessNumber = {
          animationIterationCount: true,
          aspectRatio: true,
          borderImageOutset: true,
          borderImageSlice: true,
          borderImageWidth: true,
          boxFlex: true,
          boxFlexGroup: true,
          boxOrdinalGroup: true,
          columnCount: true,
          columns: true,
          flex: true,
          flexGrow: true,
          flexPositive: true,
          flexShrink: true,
          flexNegative: true,
          flexOrder: true,
          gridArea: true,
          gridRow: true,
          gridRowEnd: true,
          gridRowSpan: true,
          gridRowStart: true,
          gridColumn: true,
          gridColumnEnd: true,
          gridColumnSpan: true,
          gridColumnStart: true,
          fontWeight: true,
          lineClamp: true,
          lineHeight: true,
          opacity: true,
          order: true,
          orphans: true,
          tabSize: true,
          widows: true,
          zIndex: true,
          zoom: true,
          // SVG-related properties
          fillOpacity: true,
          floodOpacity: true,
          stopOpacity: true,
          strokeDasharray: true,
          strokeDashoffset: true,
          strokeMiterlimit: true,
          strokeOpacity: true,
          strokeWidth: true
        };
        function prefixKey(prefix2, key) {
          return prefix2 + key.charAt(0).toUpperCase() + key.substring(1);
        }
        var prefixes = ["Webkit", "ms", "Moz", "O"];
        Object.keys(isUnitlessNumber).forEach(function(prop) {
          prefixes.forEach(function(prefix2) {
            isUnitlessNumber[prefixKey(prefix2, prop)] = isUnitlessNumber[prop];
          });
        });
        function dangerousStyleValue(name, value, isCustomProperty) {
          var isEmpty = value == null || typeof value === "boolean" || value === "";
          if (isEmpty) {
            return "";
          }
          if (!isCustomProperty && typeof value === "number" && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
            return value + "px";
          }
          {
            checkCSSPropertyStringCoercion(value, name);
          }
          return ("" + value).trim();
        }
        var uppercasePattern = /([A-Z])/g;
        var msPattern = /^ms-/;
        function hyphenateStyleName(name) {
          return name.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-");
        }
        var warnValidStyle = function() {
        };
        {
          var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
          var msPattern$1 = /^-ms-/;
          var hyphenPattern = /-(.)/g;
          var badStyleValueWithSemicolonPattern = /;\s*$/;
          var warnedStyleNames = {};
          var warnedStyleValues = {};
          var warnedForNaNValue = false;
          var warnedForInfinityValue = false;
          var camelize = function(string) {
            return string.replace(hyphenPattern, function(_2, character) {
              return character.toUpperCase();
            });
          };
          var warnHyphenatedStyleName = function(name) {
            if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
              return;
            }
            warnedStyleNames[name] = true;
            error(
              "Unsupported style property %s. Did you mean %s?",
              name,
              // As Andi Smith suggests
              // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
              // is converted to lowercase `ms`.
              camelize(name.replace(msPattern$1, "ms-"))
            );
          };
          var warnBadVendoredStyleName = function(name) {
            if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
              return;
            }
            warnedStyleNames[name] = true;
            error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name, name.charAt(0).toUpperCase() + name.slice(1));
          };
          var warnStyleValueWithSemicolon = function(name, value) {
            if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
              return;
            }
            warnedStyleValues[value] = true;
            error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name, value.replace(badStyleValueWithSemicolonPattern, ""));
          };
          var warnStyleValueIsNaN = function(name, value) {
            if (warnedForNaNValue) {
              return;
            }
            warnedForNaNValue = true;
            error("`NaN` is an invalid value for the `%s` css style property.", name);
          };
          var warnStyleValueIsInfinity = function(name, value) {
            if (warnedForInfinityValue) {
              return;
            }
            warnedForInfinityValue = true;
            error("`Infinity` is an invalid value for the `%s` css style property.", name);
          };
          warnValidStyle = function(name, value) {
            if (name.indexOf("-") > -1) {
              warnHyphenatedStyleName(name);
            } else if (badVendoredStyleNamePattern.test(name)) {
              warnBadVendoredStyleName(name);
            } else if (badStyleValueWithSemicolonPattern.test(value)) {
              warnStyleValueWithSemicolon(name, value);
            }
            if (typeof value === "number") {
              if (isNaN(value)) {
                warnStyleValueIsNaN(name, value);
              } else if (!isFinite(value)) {
                warnStyleValueIsInfinity(name, value);
              }
            }
          };
        }
        var warnValidStyle$1 = warnValidStyle;
        function createDangerousStringForStyles(styles2) {
          {
            var serialized = "";
            var delimiter = "";
            for (var styleName in styles2) {
              if (!styles2.hasOwnProperty(styleName)) {
                continue;
              }
              var styleValue = styles2[styleName];
              if (styleValue != null) {
                var isCustomProperty = styleName.indexOf("--") === 0;
                serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ":";
                serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
                delimiter = ";";
              }
            }
            return serialized || null;
          }
        }
        function setValueForStyles(node, styles2) {
          var style2 = node.style;
          for (var styleName in styles2) {
            if (!styles2.hasOwnProperty(styleName)) {
              continue;
            }
            var isCustomProperty = styleName.indexOf("--") === 0;
            {
              if (!isCustomProperty) {
                warnValidStyle$1(styleName, styles2[styleName]);
              }
            }
            var styleValue = dangerousStyleValue(styleName, styles2[styleName], isCustomProperty);
            if (styleName === "float") {
              styleName = "cssFloat";
            }
            if (isCustomProperty) {
              style2.setProperty(styleName, styleValue);
            } else {
              style2[styleName] = styleValue;
            }
          }
        }
        function isValueEmpty(value) {
          return value == null || typeof value === "boolean" || value === "";
        }
        function expandShorthandMap(styles2) {
          var expanded = {};
          for (var key in styles2) {
            var longhands = shorthandToLonghand[key] || [key];
            for (var i3 = 0; i3 < longhands.length; i3++) {
              expanded[longhands[i3]] = key;
            }
          }
          return expanded;
        }
        function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
          {
            if (!nextStyles) {
              return;
            }
            var expandedUpdates = expandShorthandMap(styleUpdates);
            var expandedStyles = expandShorthandMap(nextStyles);
            var warnedAbout = {};
            for (var key in expandedUpdates) {
              var originalKey = expandedUpdates[key];
              var correctOriginalKey = expandedStyles[key];
              if (correctOriginalKey && originalKey !== correctOriginalKey) {
                var warningKey = originalKey + "," + correctOriginalKey;
                if (warnedAbout[warningKey]) {
                  continue;
                }
                warnedAbout[warningKey] = true;
                error("%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.", isValueEmpty(styleUpdates[originalKey]) ? "Removing" : "Updating", originalKey, correctOriginalKey);
              }
            }
          }
        }
        var omittedCloseTags = {
          area: true,
          base: true,
          br: true,
          col: true,
          embed: true,
          hr: true,
          img: true,
          input: true,
          keygen: true,
          link: true,
          meta: true,
          param: true,
          source: true,
          track: true,
          wbr: true
          // NOTE: menuitem's close tag should be omitted, but that causes problems.
        };
        var voidElementTags = assign({
          menuitem: true
        }, omittedCloseTags);
        var HTML = "__html";
        function assertValidProps(tag, props) {
          if (!props) {
            return;
          }
          if (voidElementTags[tag]) {
            if (props.children != null || props.dangerouslySetInnerHTML != null) {
              throw new Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");
            }
          }
          if (props.dangerouslySetInnerHTML != null) {
            if (props.children != null) {
              throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
            }
            if (typeof props.dangerouslySetInnerHTML !== "object" || !(HTML in props.dangerouslySetInnerHTML)) {
              throw new Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");
            }
          }
          {
            if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
              error("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.");
            }
          }
          if (props.style != null && typeof props.style !== "object") {
            throw new Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");
          }
        }
        function isCustomComponent(tagName, props) {
          if (tagName.indexOf("-") === -1) {
            return typeof props.is === "string";
          }
          switch (tagName) {
            case "annotation-xml":
            case "color-profile":
            case "font-face":
            case "font-face-src":
            case "font-face-uri":
            case "font-face-format":
            case "font-face-name":
            case "missing-glyph":
              return false;
            default:
              return true;
          }
        }
        var possibleStandardNames = {
          // HTML
          accept: "accept",
          acceptcharset: "acceptCharset",
          "accept-charset": "acceptCharset",
          accesskey: "accessKey",
          action: "action",
          allowfullscreen: "allowFullScreen",
          alt: "alt",
          as: "as",
          async: "async",
          autocapitalize: "autoCapitalize",
          autocomplete: "autoComplete",
          autocorrect: "autoCorrect",
          autofocus: "autoFocus",
          autoplay: "autoPlay",
          autosave: "autoSave",
          capture: "capture",
          cellpadding: "cellPadding",
          cellspacing: "cellSpacing",
          challenge: "challenge",
          charset: "charSet",
          checked: "checked",
          children: "children",
          cite: "cite",
          class: "className",
          classid: "classID",
          classname: "className",
          cols: "cols",
          colspan: "colSpan",
          content: "content",
          contenteditable: "contentEditable",
          contextmenu: "contextMenu",
          controls: "controls",
          controlslist: "controlsList",
          coords: "coords",
          crossorigin: "crossOrigin",
          dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
          data: "data",
          datetime: "dateTime",
          default: "default",
          defaultchecked: "defaultChecked",
          defaultvalue: "defaultValue",
          defer: "defer",
          dir: "dir",
          disabled: "disabled",
          disablepictureinpicture: "disablePictureInPicture",
          disableremoteplayback: "disableRemotePlayback",
          download: "download",
          draggable: "draggable",
          enctype: "encType",
          enterkeyhint: "enterKeyHint",
          for: "htmlFor",
          form: "form",
          formmethod: "formMethod",
          formaction: "formAction",
          formenctype: "formEncType",
          formnovalidate: "formNoValidate",
          formtarget: "formTarget",
          frameborder: "frameBorder",
          headers: "headers",
          height: "height",
          hidden: "hidden",
          high: "high",
          href: "href",
          hreflang: "hrefLang",
          htmlfor: "htmlFor",
          httpequiv: "httpEquiv",
          "http-equiv": "httpEquiv",
          icon: "icon",
          id: "id",
          imagesizes: "imageSizes",
          imagesrcset: "imageSrcSet",
          innerhtml: "innerHTML",
          inputmode: "inputMode",
          integrity: "integrity",
          is: "is",
          itemid: "itemID",
          itemprop: "itemProp",
          itemref: "itemRef",
          itemscope: "itemScope",
          itemtype: "itemType",
          keyparams: "keyParams",
          keytype: "keyType",
          kind: "kind",
          label: "label",
          lang: "lang",
          list: "list",
          loop: "loop",
          low: "low",
          manifest: "manifest",
          marginwidth: "marginWidth",
          marginheight: "marginHeight",
          max: "max",
          maxlength: "maxLength",
          media: "media",
          mediagroup: "mediaGroup",
          method: "method",
          min: "min",
          minlength: "minLength",
          multiple: "multiple",
          muted: "muted",
          name: "name",
          nomodule: "noModule",
          nonce: "nonce",
          novalidate: "noValidate",
          open: "open",
          optimum: "optimum",
          pattern: "pattern",
          placeholder: "placeholder",
          playsinline: "playsInline",
          poster: "poster",
          preload: "preload",
          profile: "profile",
          radiogroup: "radioGroup",
          readonly: "readOnly",
          referrerpolicy: "referrerPolicy",
          rel: "rel",
          required: "required",
          reversed: "reversed",
          role: "role",
          rows: "rows",
          rowspan: "rowSpan",
          sandbox: "sandbox",
          scope: "scope",
          scoped: "scoped",
          scrolling: "scrolling",
          seamless: "seamless",
          selected: "selected",
          shape: "shape",
          size: "size",
          sizes: "sizes",
          span: "span",
          spellcheck: "spellCheck",
          src: "src",
          srcdoc: "srcDoc",
          srclang: "srcLang",
          srcset: "srcSet",
          start: "start",
          step: "step",
          style: "style",
          summary: "summary",
          tabindex: "tabIndex",
          target: "target",
          title: "title",
          type: "type",
          usemap: "useMap",
          value: "value",
          width: "width",
          wmode: "wmode",
          wrap: "wrap",
          // SVG
          about: "about",
          accentheight: "accentHeight",
          "accent-height": "accentHeight",
          accumulate: "accumulate",
          additive: "additive",
          alignmentbaseline: "alignmentBaseline",
          "alignment-baseline": "alignmentBaseline",
          allowreorder: "allowReorder",
          alphabetic: "alphabetic",
          amplitude: "amplitude",
          arabicform: "arabicForm",
          "arabic-form": "arabicForm",
          ascent: "ascent",
          attributename: "attributeName",
          attributetype: "attributeType",
          autoreverse: "autoReverse",
          azimuth: "azimuth",
          basefrequency: "baseFrequency",
          baselineshift: "baselineShift",
          "baseline-shift": "baselineShift",
          baseprofile: "baseProfile",
          bbox: "bbox",
          begin: "begin",
          bias: "bias",
          by: "by",
          calcmode: "calcMode",
          capheight: "capHeight",
          "cap-height": "capHeight",
          clip: "clip",
          clippath: "clipPath",
          "clip-path": "clipPath",
          clippathunits: "clipPathUnits",
          cliprule: "clipRule",
          "clip-rule": "clipRule",
          color: "color",
          colorinterpolation: "colorInterpolation",
          "color-interpolation": "colorInterpolation",
          colorinterpolationfilters: "colorInterpolationFilters",
          "color-interpolation-filters": "colorInterpolationFilters",
          colorprofile: "colorProfile",
          "color-profile": "colorProfile",
          colorrendering: "colorRendering",
          "color-rendering": "colorRendering",
          contentscripttype: "contentScriptType",
          contentstyletype: "contentStyleType",
          cursor: "cursor",
          cx: "cx",
          cy: "cy",
          d: "d",
          datatype: "datatype",
          decelerate: "decelerate",
          descent: "descent",
          diffuseconstant: "diffuseConstant",
          direction: "direction",
          display: "display",
          divisor: "divisor",
          dominantbaseline: "dominantBaseline",
          "dominant-baseline": "dominantBaseline",
          dur: "dur",
          dx: "dx",
          dy: "dy",
          edgemode: "edgeMode",
          elevation: "elevation",
          enablebackground: "enableBackground",
          "enable-background": "enableBackground",
          end: "end",
          exponent: "exponent",
          externalresourcesrequired: "externalResourcesRequired",
          fill: "fill",
          fillopacity: "fillOpacity",
          "fill-opacity": "fillOpacity",
          fillrule: "fillRule",
          "fill-rule": "fillRule",
          filter: "filter",
          filterres: "filterRes",
          filterunits: "filterUnits",
          floodopacity: "floodOpacity",
          "flood-opacity": "floodOpacity",
          floodcolor: "floodColor",
          "flood-color": "floodColor",
          focusable: "focusable",
          fontfamily: "fontFamily",
          "font-family": "fontFamily",
          fontsize: "fontSize",
          "font-size": "fontSize",
          fontsizeadjust: "fontSizeAdjust",
          "font-size-adjust": "fontSizeAdjust",
          fontstretch: "fontStretch",
          "font-stretch": "fontStretch",
          fontstyle: "fontStyle",
          "font-style": "fontStyle",
          fontvariant: "fontVariant",
          "font-variant": "fontVariant",
          fontweight: "fontWeight",
          "font-weight": "fontWeight",
          format: "format",
          from: "from",
          fx: "fx",
          fy: "fy",
          g1: "g1",
          g2: "g2",
          glyphname: "glyphName",
          "glyph-name": "glyphName",
          glyphorientationhorizontal: "glyphOrientationHorizontal",
          "glyph-orientation-horizontal": "glyphOrientationHorizontal",
          glyphorientationvertical: "glyphOrientationVertical",
          "glyph-orientation-vertical": "glyphOrientationVertical",
          glyphref: "glyphRef",
          gradienttransform: "gradientTransform",
          gradientunits: "gradientUnits",
          hanging: "hanging",
          horizadvx: "horizAdvX",
          "horiz-adv-x": "horizAdvX",
          horizoriginx: "horizOriginX",
          "horiz-origin-x": "horizOriginX",
          ideographic: "ideographic",
          imagerendering: "imageRendering",
          "image-rendering": "imageRendering",
          in2: "in2",
          in: "in",
          inlist: "inlist",
          intercept: "intercept",
          k1: "k1",
          k2: "k2",
          k3: "k3",
          k4: "k4",
          k: "k",
          kernelmatrix: "kernelMatrix",
          kernelunitlength: "kernelUnitLength",
          kerning: "kerning",
          keypoints: "keyPoints",
          keysplines: "keySplines",
          keytimes: "keyTimes",
          lengthadjust: "lengthAdjust",
          letterspacing: "letterSpacing",
          "letter-spacing": "letterSpacing",
          lightingcolor: "lightingColor",
          "lighting-color": "lightingColor",
          limitingconeangle: "limitingConeAngle",
          local: "local",
          markerend: "markerEnd",
          "marker-end": "markerEnd",
          markerheight: "markerHeight",
          markermid: "markerMid",
          "marker-mid": "markerMid",
          markerstart: "markerStart",
          "marker-start": "markerStart",
          markerunits: "markerUnits",
          markerwidth: "markerWidth",
          mask: "mask",
          maskcontentunits: "maskContentUnits",
          maskunits: "maskUnits",
          mathematical: "mathematical",
          mode: "mode",
          numoctaves: "numOctaves",
          offset: "offset",
          opacity: "opacity",
          operator: "operator",
          order: "order",
          orient: "orient",
          orientation: "orientation",
          origin: "origin",
          overflow: "overflow",
          overlineposition: "overlinePosition",
          "overline-position": "overlinePosition",
          overlinethickness: "overlineThickness",
          "overline-thickness": "overlineThickness",
          paintorder: "paintOrder",
          "paint-order": "paintOrder",
          panose1: "panose1",
          "panose-1": "panose1",
          pathlength: "pathLength",
          patterncontentunits: "patternContentUnits",
          patterntransform: "patternTransform",
          patternunits: "patternUnits",
          pointerevents: "pointerEvents",
          "pointer-events": "pointerEvents",
          points: "points",
          pointsatx: "pointsAtX",
          pointsaty: "pointsAtY",
          pointsatz: "pointsAtZ",
          prefix: "prefix",
          preservealpha: "preserveAlpha",
          preserveaspectratio: "preserveAspectRatio",
          primitiveunits: "primitiveUnits",
          property: "property",
          r: "r",
          radius: "radius",
          refx: "refX",
          refy: "refY",
          renderingintent: "renderingIntent",
          "rendering-intent": "renderingIntent",
          repeatcount: "repeatCount",
          repeatdur: "repeatDur",
          requiredextensions: "requiredExtensions",
          requiredfeatures: "requiredFeatures",
          resource: "resource",
          restart: "restart",
          result: "result",
          results: "results",
          rotate: "rotate",
          rx: "rx",
          ry: "ry",
          scale: "scale",
          security: "security",
          seed: "seed",
          shaperendering: "shapeRendering",
          "shape-rendering": "shapeRendering",
          slope: "slope",
          spacing: "spacing",
          specularconstant: "specularConstant",
          specularexponent: "specularExponent",
          speed: "speed",
          spreadmethod: "spreadMethod",
          startoffset: "startOffset",
          stddeviation: "stdDeviation",
          stemh: "stemh",
          stemv: "stemv",
          stitchtiles: "stitchTiles",
          stopcolor: "stopColor",
          "stop-color": "stopColor",
          stopopacity: "stopOpacity",
          "stop-opacity": "stopOpacity",
          strikethroughposition: "strikethroughPosition",
          "strikethrough-position": "strikethroughPosition",
          strikethroughthickness: "strikethroughThickness",
          "strikethrough-thickness": "strikethroughThickness",
          string: "string",
          stroke: "stroke",
          strokedasharray: "strokeDasharray",
          "stroke-dasharray": "strokeDasharray",
          strokedashoffset: "strokeDashoffset",
          "stroke-dashoffset": "strokeDashoffset",
          strokelinecap: "strokeLinecap",
          "stroke-linecap": "strokeLinecap",
          strokelinejoin: "strokeLinejoin",
          "stroke-linejoin": "strokeLinejoin",
          strokemiterlimit: "strokeMiterlimit",
          "stroke-miterlimit": "strokeMiterlimit",
          strokewidth: "strokeWidth",
          "stroke-width": "strokeWidth",
          strokeopacity: "strokeOpacity",
          "stroke-opacity": "strokeOpacity",
          suppresscontenteditablewarning: "suppressContentEditableWarning",
          suppresshydrationwarning: "suppressHydrationWarning",
          surfacescale: "surfaceScale",
          systemlanguage: "systemLanguage",
          tablevalues: "tableValues",
          targetx: "targetX",
          targety: "targetY",
          textanchor: "textAnchor",
          "text-anchor": "textAnchor",
          textdecoration: "textDecoration",
          "text-decoration": "textDecoration",
          textlength: "textLength",
          textrendering: "textRendering",
          "text-rendering": "textRendering",
          to: "to",
          transform: "transform",
          typeof: "typeof",
          u1: "u1",
          u2: "u2",
          underlineposition: "underlinePosition",
          "underline-position": "underlinePosition",
          underlinethickness: "underlineThickness",
          "underline-thickness": "underlineThickness",
          unicode: "unicode",
          unicodebidi: "unicodeBidi",
          "unicode-bidi": "unicodeBidi",
          unicoderange: "unicodeRange",
          "unicode-range": "unicodeRange",
          unitsperem: "unitsPerEm",
          "units-per-em": "unitsPerEm",
          unselectable: "unselectable",
          valphabetic: "vAlphabetic",
          "v-alphabetic": "vAlphabetic",
          values: "values",
          vectoreffect: "vectorEffect",
          "vector-effect": "vectorEffect",
          version: "version",
          vertadvy: "vertAdvY",
          "vert-adv-y": "vertAdvY",
          vertoriginx: "vertOriginX",
          "vert-origin-x": "vertOriginX",
          vertoriginy: "vertOriginY",
          "vert-origin-y": "vertOriginY",
          vhanging: "vHanging",
          "v-hanging": "vHanging",
          videographic: "vIdeographic",
          "v-ideographic": "vIdeographic",
          viewbox: "viewBox",
          viewtarget: "viewTarget",
          visibility: "visibility",
          vmathematical: "vMathematical",
          "v-mathematical": "vMathematical",
          vocab: "vocab",
          widths: "widths",
          wordspacing: "wordSpacing",
          "word-spacing": "wordSpacing",
          writingmode: "writingMode",
          "writing-mode": "writingMode",
          x1: "x1",
          x2: "x2",
          x: "x",
          xchannelselector: "xChannelSelector",
          xheight: "xHeight",
          "x-height": "xHeight",
          xlinkactuate: "xlinkActuate",
          "xlink:actuate": "xlinkActuate",
          xlinkarcrole: "xlinkArcrole",
          "xlink:arcrole": "xlinkArcrole",
          xlinkhref: "xlinkHref",
          "xlink:href": "xlinkHref",
          xlinkrole: "xlinkRole",
          "xlink:role": "xlinkRole",
          xlinkshow: "xlinkShow",
          "xlink:show": "xlinkShow",
          xlinktitle: "xlinkTitle",
          "xlink:title": "xlinkTitle",
          xlinktype: "xlinkType",
          "xlink:type": "xlinkType",
          xmlbase: "xmlBase",
          "xml:base": "xmlBase",
          xmllang: "xmlLang",
          "xml:lang": "xmlLang",
          xmlns: "xmlns",
          "xml:space": "xmlSpace",
          xmlnsxlink: "xmlnsXlink",
          "xmlns:xlink": "xmlnsXlink",
          xmlspace: "xmlSpace",
          y1: "y1",
          y2: "y2",
          y: "y",
          ychannelselector: "yChannelSelector",
          z: "z",
          zoomandpan: "zoomAndPan"
        };
        var ariaProperties = {
          "aria-current": 0,
          // state
          "aria-description": 0,
          "aria-details": 0,
          "aria-disabled": 0,
          // state
          "aria-hidden": 0,
          // state
          "aria-invalid": 0,
          // state
          "aria-keyshortcuts": 0,
          "aria-label": 0,
          "aria-roledescription": 0,
          // Widget Attributes
          "aria-autocomplete": 0,
          "aria-checked": 0,
          "aria-expanded": 0,
          "aria-haspopup": 0,
          "aria-level": 0,
          "aria-modal": 0,
          "aria-multiline": 0,
          "aria-multiselectable": 0,
          "aria-orientation": 0,
          "aria-placeholder": 0,
          "aria-pressed": 0,
          "aria-readonly": 0,
          "aria-required": 0,
          "aria-selected": 0,
          "aria-sort": 0,
          "aria-valuemax": 0,
          "aria-valuemin": 0,
          "aria-valuenow": 0,
          "aria-valuetext": 0,
          // Live Region Attributes
          "aria-atomic": 0,
          "aria-busy": 0,
          "aria-live": 0,
          "aria-relevant": 0,
          // Drag-and-Drop Attributes
          "aria-dropeffect": 0,
          "aria-grabbed": 0,
          // Relationship Attributes
          "aria-activedescendant": 0,
          "aria-colcount": 0,
          "aria-colindex": 0,
          "aria-colspan": 0,
          "aria-controls": 0,
          "aria-describedby": 0,
          "aria-errormessage": 0,
          "aria-flowto": 0,
          "aria-labelledby": 0,
          "aria-owns": 0,
          "aria-posinset": 0,
          "aria-rowcount": 0,
          "aria-rowindex": 0,
          "aria-rowspan": 0,
          "aria-setsize": 0
        };
        var warnedProperties = {};
        var rARIA = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
        var rARIACamel = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
        function validateProperty(tagName, name) {
          {
            if (hasOwnProperty3.call(warnedProperties, name) && warnedProperties[name]) {
              return true;
            }
            if (rARIACamel.test(name)) {
              var ariaName = "aria-" + name.slice(4).toLowerCase();
              var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
              if (correctName == null) {
                error("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.", name);
                warnedProperties[name] = true;
                return true;
              }
              if (name !== correctName) {
                error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name, correctName);
                warnedProperties[name] = true;
                return true;
              }
            }
            if (rARIA.test(name)) {
              var lowerCasedName = name.toLowerCase();
              var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
              if (standardName == null) {
                warnedProperties[name] = true;
                return false;
              }
              if (name !== standardName) {
                error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name, standardName);
                warnedProperties[name] = true;
                return true;
              }
            }
          }
          return true;
        }
        function warnInvalidARIAProps(type, props) {
          {
            var invalidProps = [];
            for (var key in props) {
              var isValid2 = validateProperty(type, key);
              if (!isValid2) {
                invalidProps.push(key);
              }
            }
            var unknownPropString = invalidProps.map(function(prop) {
              return "`" + prop + "`";
            }).join(", ");
            if (invalidProps.length === 1) {
              error("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type);
            } else if (invalidProps.length > 1) {
              error("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type);
            }
          }
        }
        function validateProperties(type, props) {
          if (isCustomComponent(type, props)) {
            return;
          }
          warnInvalidARIAProps(type, props);
        }
        var didWarnValueNull = false;
        function validateProperties$1(type, props) {
          {
            if (type !== "input" && type !== "textarea" && type !== "select") {
              return;
            }
            if (props != null && props.value === null && !didWarnValueNull) {
              didWarnValueNull = true;
              if (type === "select" && props.multiple) {
                error("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.", type);
              } else {
                error("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.", type);
              }
            }
          }
        }
        var validateProperty$1 = function() {
        };
        {
          var warnedProperties$1 = {};
          var EVENT_NAME_REGEX = /^on./;
          var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
          var rARIA$1 = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
          var rARIACamel$1 = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
          validateProperty$1 = function(tagName, name, value, eventRegistry) {
            if (hasOwnProperty3.call(warnedProperties$1, name) && warnedProperties$1[name]) {
              return true;
            }
            var lowerCasedName = name.toLowerCase();
            if (lowerCasedName === "onfocusin" || lowerCasedName === "onfocusout") {
              error("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React.");
              warnedProperties$1[name] = true;
              return true;
            }
            if (eventRegistry != null) {
              var registrationNameDependencies2 = eventRegistry.registrationNameDependencies, possibleRegistrationNames2 = eventRegistry.possibleRegistrationNames;
              if (registrationNameDependencies2.hasOwnProperty(name)) {
                return true;
              }
              var registrationName = possibleRegistrationNames2.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames2[lowerCasedName] : null;
              if (registrationName != null) {
                error("Invalid event handler property `%s`. Did you mean `%s`?", name, registrationName);
                warnedProperties$1[name] = true;
                return true;
              }
              if (EVENT_NAME_REGEX.test(name)) {
                error("Unknown event handler property `%s`. It will be ignored.", name);
                warnedProperties$1[name] = true;
                return true;
              }
            } else if (EVENT_NAME_REGEX.test(name)) {
              if (INVALID_EVENT_NAME_REGEX.test(name)) {
                error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name);
              }
              warnedProperties$1[name] = true;
              return true;
            }
            if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
              return true;
            }
            if (lowerCasedName === "innerhtml") {
              error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.");
              warnedProperties$1[name] = true;
              return true;
            }
            if (lowerCasedName === "aria") {
              error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead.");
              warnedProperties$1[name] = true;
              return true;
            }
            if (lowerCasedName === "is" && value !== null && value !== void 0 && typeof value !== "string") {
              error("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.", typeof value);
              warnedProperties$1[name] = true;
              return true;
            }
            if (typeof value === "number" && isNaN(value)) {
              error("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.", name);
              warnedProperties$1[name] = true;
              return true;
            }
            var propertyInfo = getPropertyInfo(name);
            var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
            if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
              var standardName = possibleStandardNames[lowerCasedName];
              if (standardName !== name) {
                error("Invalid DOM property `%s`. Did you mean `%s`?", name, standardName);
                warnedProperties$1[name] = true;
                return true;
              }
            } else if (!isReserved && name !== lowerCasedName) {
              error("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.", name, lowerCasedName);
              warnedProperties$1[name] = true;
              return true;
            }
            if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
              if (value) {
                error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.', value, name, name, value, name);
              } else {
                error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
              }
              warnedProperties$1[name] = true;
              return true;
            }
            if (isReserved) {
              return true;
            }
            if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
              warnedProperties$1[name] = true;
              return false;
            }
            if ((value === "false" || value === "true") && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
              error("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?", value, name, value === "false" ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
              warnedProperties$1[name] = true;
              return true;
            }
            return true;
          };
        }
        var warnUnknownProperties = function(type, props, eventRegistry) {
          {
            var unknownProps = [];
            for (var key in props) {
              var isValid2 = validateProperty$1(type, key, props[key], eventRegistry);
              if (!isValid2) {
                unknownProps.push(key);
              }
            }
            var unknownPropString = unknownProps.map(function(prop) {
              return "`" + prop + "`";
            }).join(", ");
            if (unknownProps.length === 1) {
              error("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type);
            } else if (unknownProps.length > 1) {
              error("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type);
            }
          }
        };
        function validateProperties$2(type, props, eventRegistry) {
          if (isCustomComponent(type, props)) {
            return;
          }
          warnUnknownProperties(type, props, eventRegistry);
        }
        var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
        var IS_NON_DELEGATED = 1 << 1;
        var IS_CAPTURE_PHASE = 1 << 2;
        var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
        var currentReplayingEvent = null;
        function setReplayingEvent(event) {
          {
            if (currentReplayingEvent !== null) {
              error("Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          currentReplayingEvent = event;
        }
        function resetReplayingEvent() {
          {
            if (currentReplayingEvent === null) {
              error("Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          currentReplayingEvent = null;
        }
        function isReplayingEvent(event) {
          return event === currentReplayingEvent;
        }
        function getEventTarget(nativeEvent) {
          var target = nativeEvent.target || nativeEvent.srcElement || window;
          if (target.correspondingUseElement) {
            target = target.correspondingUseElement;
          }
          return target.nodeType === TEXT_NODE ? target.parentNode : target;
        }
        var restoreImpl = null;
        var restoreTarget = null;
        var restoreQueue = null;
        function restoreStateOfTarget(target) {
          var internalInstance = getInstanceFromNode(target);
          if (!internalInstance) {
            return;
          }
          if (typeof restoreImpl !== "function") {
            throw new Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.");
          }
          var stateNode = internalInstance.stateNode;
          if (stateNode) {
            var _props = getFiberCurrentPropsFromNode(stateNode);
            restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
          }
        }
        function setRestoreImplementation(impl) {
          restoreImpl = impl;
        }
        function enqueueStateRestore(target) {
          if (restoreTarget) {
            if (restoreQueue) {
              restoreQueue.push(target);
            } else {
              restoreQueue = [target];
            }
          } else {
            restoreTarget = target;
          }
        }
        function needsStateRestore() {
          return restoreTarget !== null || restoreQueue !== null;
        }
        function restoreStateIfNeeded() {
          if (!restoreTarget) {
            return;
          }
          var target = restoreTarget;
          var queuedTargets = restoreQueue;
          restoreTarget = null;
          restoreQueue = null;
          restoreStateOfTarget(target);
          if (queuedTargets) {
            for (var i3 = 0; i3 < queuedTargets.length; i3++) {
              restoreStateOfTarget(queuedTargets[i3]);
            }
          }
        }
        var batchedUpdatesImpl = function(fn, bookkeeping) {
          return fn(bookkeeping);
        };
        var flushSyncImpl = function() {
        };
        var isInsideEventHandler = false;
        function finishEventHandler() {
          var controlledComponentsHavePendingUpdates = needsStateRestore();
          if (controlledComponentsHavePendingUpdates) {
            flushSyncImpl();
            restoreStateIfNeeded();
          }
        }
        function batchedUpdates(fn, a3, b3) {
          if (isInsideEventHandler) {
            return fn(a3, b3);
          }
          isInsideEventHandler = true;
          try {
            return batchedUpdatesImpl(fn, a3, b3);
          } finally {
            isInsideEventHandler = false;
            finishEventHandler();
          }
        }
        function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
          batchedUpdatesImpl = _batchedUpdatesImpl;
          flushSyncImpl = _flushSyncImpl;
        }
        function isInteractive(tag) {
          return tag === "button" || tag === "input" || tag === "select" || tag === "textarea";
        }
        function shouldPreventMouseEvent(name, type, props) {
          switch (name) {
            case "onClick":
            case "onClickCapture":
            case "onDoubleClick":
            case "onDoubleClickCapture":
            case "onMouseDown":
            case "onMouseDownCapture":
            case "onMouseMove":
            case "onMouseMoveCapture":
            case "onMouseUp":
            case "onMouseUpCapture":
            case "onMouseEnter":
              return !!(props.disabled && isInteractive(type));
            default:
              return false;
          }
        }
        function getListener(inst, registrationName) {
          var stateNode = inst.stateNode;
          if (stateNode === null) {
            return null;
          }
          var props = getFiberCurrentPropsFromNode(stateNode);
          if (props === null) {
            return null;
          }
          var listener = props[registrationName];
          if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
            return null;
          }
          if (listener && typeof listener !== "function") {
            throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
          }
          return listener;
        }
        var passiveBrowserEventsSupported = false;
        if (canUseDOM) {
          try {
            var options = {};
            Object.defineProperty(options, "passive", {
              get: function() {
                passiveBrowserEventsSupported = true;
              }
            });
            window.addEventListener("test", options, options);
            window.removeEventListener("test", options, options);
          } catch (e3) {
            passiveBrowserEventsSupported = false;
          }
        }
        function invokeGuardedCallbackProd(name, func, context, a3, b3, c4, d3, e3, f3) {
          var funcArgs = Array.prototype.slice.call(arguments, 3);
          try {
            func.apply(context, funcArgs);
          } catch (error2) {
            this.onError(error2);
          }
        }
        var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
        {
          if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof document !== "undefined" && typeof document.createEvent === "function") {
            var fakeNode = document.createElement("react");
            invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a3, b3, c4, d3, e3, f3) {
              if (typeof document === "undefined" || document === null) {
                throw new Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");
              }
              var evt = document.createEvent("Event");
              var didCall = false;
              var didError = true;
              var windowEvent = window.event;
              var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event");
              function restoreAfterDispatch() {
                fakeNode.removeEventListener(evtType, callCallback2, false);
                if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) {
                  window.event = windowEvent;
                }
              }
              var funcArgs = Array.prototype.slice.call(arguments, 3);
              function callCallback2() {
                didCall = true;
                restoreAfterDispatch();
                func.apply(context, funcArgs);
                didError = false;
              }
              var error2;
              var didSetError = false;
              var isCrossOriginError = false;
              function handleWindowError(event) {
                error2 = event.error;
                didSetError = true;
                if (error2 === null && event.colno === 0 && event.lineno === 0) {
                  isCrossOriginError = true;
                }
                if (event.defaultPrevented) {
                  if (error2 != null && typeof error2 === "object") {
                    try {
                      error2._suppressLogging = true;
                    } catch (inner) {
                    }
                  }
                }
              }
              var evtType = "react-" + (name ? name : "invokeguardedcallback");
              window.addEventListener("error", handleWindowError);
              fakeNode.addEventListener(evtType, callCallback2, false);
              evt.initEvent(evtType, false, false);
              fakeNode.dispatchEvent(evt);
              if (windowEventDescriptor) {
                Object.defineProperty(window, "event", windowEventDescriptor);
              }
              if (didCall && didError) {
                if (!didSetError) {
                  error2 = new Error(`An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue.`);
                } else if (isCrossOriginError) {
                  error2 = new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.");
                }
                this.onError(error2);
              }
              window.removeEventListener("error", handleWindowError);
              if (!didCall) {
                restoreAfterDispatch();
                return invokeGuardedCallbackProd.apply(this, arguments);
              }
            };
          }
        }
        var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
        var hasError = false;
        var caughtError = null;
        var hasRethrowError = false;
        var rethrowError = null;
        var reporter = {
          onError: function(error2) {
            hasError = true;
            caughtError = error2;
          }
        };
        function invokeGuardedCallback(name, func, context, a3, b3, c4, d3, e3, f3) {
          hasError = false;
          caughtError = null;
          invokeGuardedCallbackImpl$1.apply(reporter, arguments);
        }
        function invokeGuardedCallbackAndCatchFirstError(name, func, context, a3, b3, c4, d3, e3, f3) {
          invokeGuardedCallback.apply(this, arguments);
          if (hasError) {
            var error2 = clearCaughtError();
            if (!hasRethrowError) {
              hasRethrowError = true;
              rethrowError = error2;
            }
          }
        }
        function rethrowCaughtError() {
          if (hasRethrowError) {
            var error2 = rethrowError;
            hasRethrowError = false;
            rethrowError = null;
            throw error2;
          }
        }
        function hasCaughtError() {
          return hasError;
        }
        function clearCaughtError() {
          if (hasError) {
            var error2 = caughtError;
            hasError = false;
            caughtError = null;
            return error2;
          } else {
            throw new Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        function get4(key) {
          return key._reactInternals;
        }
        function has2(key) {
          return key._reactInternals !== void 0;
        }
        function set(key, value) {
          key._reactInternals = value;
        }
        var NoFlags = (
          /*                      */
          0
        );
        var PerformedWork = (
          /*                */
          1
        );
        var Placement = (
          /*                    */
          2
        );
        var Update = (
          /*                       */
          4
        );
        var ChildDeletion = (
          /*                */
          16
        );
        var ContentReset = (
          /*                 */
          32
        );
        var Callback = (
          /*                     */
          64
        );
        var DidCapture = (
          /*                   */
          128
        );
        var ForceClientRender = (
          /*            */
          256
        );
        var Ref = (
          /*                          */
          512
        );
        var Snapshot = (
          /*                     */
          1024
        );
        var Passive = (
          /*                      */
          2048
        );
        var Hydrating = (
          /*                    */
          4096
        );
        var Visibility = (
          /*                   */
          8192
        );
        var StoreConsistency = (
          /*             */
          16384
        );
        var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency;
        var HostEffectMask = (
          /*               */
          32767
        );
        var Incomplete = (
          /*                   */
          32768
        );
        var ShouldCapture = (
          /*                */
          65536
        );
        var ForceUpdateForLegacySuspense = (
          /* */
          131072
        );
        var Forked = (
          /*                       */
          1048576
        );
        var RefStatic = (
          /*                    */
          2097152
        );
        var LayoutStatic = (
          /*                 */
          4194304
        );
        var PassiveStatic = (
          /*                */
          8388608
        );
        var MountLayoutDev = (
          /*               */
          16777216
        );
        var MountPassiveDev = (
          /*              */
          33554432
        );
        var BeforeMutationMask = (
          // TODO: Remove Update flag from before mutation phase by re-landing Visibility
          // flag logic (see #20043)
          Update | Snapshot | 0
        );
        var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
        var LayoutMask = Update | Callback | Ref | Visibility;
        var PassiveMask = Passive | ChildDeletion;
        var StaticMask = LayoutStatic | PassiveStatic | RefStatic;
        var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
        function getNearestMountedFiber(fiber) {
          var node = fiber;
          var nearestMounted = fiber;
          if (!fiber.alternate) {
            var nextNode = node;
            do {
              node = nextNode;
              if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
                nearestMounted = node.return;
              }
              nextNode = node.return;
            } while (nextNode);
          } else {
            while (node.return) {
              node = node.return;
            }
          }
          if (node.tag === HostRoot) {
            return nearestMounted;
          }
          return null;
        }
        function getSuspenseInstanceFromFiber(fiber) {
          if (fiber.tag === SuspenseComponent) {
            var suspenseState = fiber.memoizedState;
            if (suspenseState === null) {
              var current2 = fiber.alternate;
              if (current2 !== null) {
                suspenseState = current2.memoizedState;
              }
            }
            if (suspenseState !== null) {
              return suspenseState.dehydrated;
            }
          }
          return null;
        }
        function getContainerFromFiber(fiber) {
          return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
        }
        function isFiberMounted(fiber) {
          return getNearestMountedFiber(fiber) === fiber;
        }
        function isMounted(component) {
          {
            var owner = ReactCurrentOwner.current;
            if (owner !== null && owner.tag === ClassComponent) {
              var ownerFiber = owner;
              var instance = ownerFiber.stateNode;
              if (!instance._warnedAboutRefsInRender) {
                error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromFiber(ownerFiber) || "A component");
              }
              instance._warnedAboutRefsInRender = true;
            }
          }
          var fiber = get4(component);
          if (!fiber) {
            return false;
          }
          return getNearestMountedFiber(fiber) === fiber;
        }
        function assertIsMounted(fiber) {
          if (getNearestMountedFiber(fiber) !== fiber) {
            throw new Error("Unable to find node on an unmounted component.");
          }
        }
        function findCurrentFiberUsingSlowPath(fiber) {
          var alternate = fiber.alternate;
          if (!alternate) {
            var nearestMounted = getNearestMountedFiber(fiber);
            if (nearestMounted === null) {
              throw new Error("Unable to find node on an unmounted component.");
            }
            if (nearestMounted !== fiber) {
              return null;
            }
            return fiber;
          }
          var a3 = fiber;
          var b3 = alternate;
          while (true) {
            var parentA = a3.return;
            if (parentA === null) {
              break;
            }
            var parentB = parentA.alternate;
            if (parentB === null) {
              var nextParent = parentA.return;
              if (nextParent !== null) {
                a3 = b3 = nextParent;
                continue;
              }
              break;
            }
            if (parentA.child === parentB.child) {
              var child = parentA.child;
              while (child) {
                if (child === a3) {
                  assertIsMounted(parentA);
                  return fiber;
                }
                if (child === b3) {
                  assertIsMounted(parentA);
                  return alternate;
                }
                child = child.sibling;
              }
              throw new Error("Unable to find node on an unmounted component.");
            }
            if (a3.return !== b3.return) {
              a3 = parentA;
              b3 = parentB;
            } else {
              var didFindChild = false;
              var _child = parentA.child;
              while (_child) {
                if (_child === a3) {
                  didFindChild = true;
                  a3 = parentA;
                  b3 = parentB;
                  break;
                }
                if (_child === b3) {
                  didFindChild = true;
                  b3 = parentA;
                  a3 = parentB;
                  break;
                }
                _child = _child.sibling;
              }
              if (!didFindChild) {
                _child = parentB.child;
                while (_child) {
                  if (_child === a3) {
                    didFindChild = true;
                    a3 = parentB;
                    b3 = parentA;
                    break;
                  }
                  if (_child === b3) {
                    didFindChild = true;
                    b3 = parentB;
                    a3 = parentA;
                    break;
                  }
                  _child = _child.sibling;
                }
                if (!didFindChild) {
                  throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
                }
              }
            }
            if (a3.alternate !== b3) {
              throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          if (a3.tag !== HostRoot) {
            throw new Error("Unable to find node on an unmounted component.");
          }
          if (a3.stateNode.current === a3) {
            return fiber;
          }
          return alternate;
        }
        function findCurrentHostFiber(parent) {
          var currentParent = findCurrentFiberUsingSlowPath(parent);
          return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
        }
        function findCurrentHostFiberImpl(node) {
          if (node.tag === HostComponent || node.tag === HostText) {
            return node;
          }
          var child = node.child;
          while (child !== null) {
            var match2 = findCurrentHostFiberImpl(child);
            if (match2 !== null) {
              return match2;
            }
            child = child.sibling;
          }
          return null;
        }
        function findCurrentHostFiberWithNoPortals(parent) {
          var currentParent = findCurrentFiberUsingSlowPath(parent);
          return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
        }
        function findCurrentHostFiberWithNoPortalsImpl(node) {
          if (node.tag === HostComponent || node.tag === HostText) {
            return node;
          }
          var child = node.child;
          while (child !== null) {
            if (child.tag !== HostPortal) {
              var match2 = findCurrentHostFiberWithNoPortalsImpl(child);
              if (match2 !== null) {
                return match2;
              }
            }
            child = child.sibling;
          }
          return null;
        }
        var scheduleCallback = Scheduler.unstable_scheduleCallback;
        var cancelCallback = Scheduler.unstable_cancelCallback;
        var shouldYield = Scheduler.unstable_shouldYield;
        var requestPaint = Scheduler.unstable_requestPaint;
        var now3 = Scheduler.unstable_now;
        var getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel;
        var ImmediatePriority = Scheduler.unstable_ImmediatePriority;
        var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
        var NormalPriority = Scheduler.unstable_NormalPriority;
        var LowPriority = Scheduler.unstable_LowPriority;
        var IdlePriority = Scheduler.unstable_IdlePriority;
        var unstable_yieldValue = Scheduler.unstable_yieldValue;
        var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue;
        var rendererID = null;
        var injectedHook = null;
        var injectedProfilingHooks = null;
        var hasLoggedError = false;
        var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined";
        function injectInternals(internals) {
          if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") {
            return false;
          }
          var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
          if (hook.isDisabled) {
            return true;
          }
          if (!hook.supportsFiber) {
            {
              error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://reactjs.org/link/react-devtools");
            }
            return true;
          }
          try {
            if (enableSchedulingProfiler) {
              internals = assign({}, internals, {
                getLaneLabelMap,
                injectProfilingHooks
              });
            }
            rendererID = hook.inject(internals);
            injectedHook = hook;
          } catch (err) {
            {
              error("React instrumentation encountered an error: %s.", err);
            }
          }
          if (hook.checkDCE) {
            return true;
          } else {
            return false;
          }
        }
        function onScheduleRoot(root3, children) {
          {
            if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") {
              try {
                injectedHook.onScheduleFiberRoot(rendererID, root3, children);
              } catch (err) {
                if (!hasLoggedError) {
                  hasLoggedError = true;
                  error("React instrumentation encountered an error: %s", err);
                }
              }
            }
          }
        }
        function onCommitRoot(root3, eventPriority) {
          if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") {
            try {
              var didError = (root3.current.flags & DidCapture) === DidCapture;
              if (enableProfilerTimer) {
                var schedulerPriority;
                switch (eventPriority) {
                  case DiscreteEventPriority:
                    schedulerPriority = ImmediatePriority;
                    break;
                  case ContinuousEventPriority:
                    schedulerPriority = UserBlockingPriority;
                    break;
                  case DefaultEventPriority:
                    schedulerPriority = NormalPriority;
                    break;
                  case IdleEventPriority:
                    schedulerPriority = IdlePriority;
                    break;
                  default:
                    schedulerPriority = NormalPriority;
                    break;
                }
                injectedHook.onCommitFiberRoot(rendererID, root3, schedulerPriority, didError);
              } else {
                injectedHook.onCommitFiberRoot(rendererID, root3, void 0, didError);
              }
            } catch (err) {
              {
                if (!hasLoggedError) {
                  hasLoggedError = true;
                  error("React instrumentation encountered an error: %s", err);
                }
              }
            }
          }
        }
        function onPostCommitRoot(root3) {
          if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function") {
            try {
              injectedHook.onPostCommitFiberRoot(rendererID, root3);
            } catch (err) {
              {
                if (!hasLoggedError) {
                  hasLoggedError = true;
                  error("React instrumentation encountered an error: %s", err);
                }
              }
            }
          }
        }
        function onCommitUnmount(fiber) {
          if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function") {
            try {
              injectedHook.onCommitFiberUnmount(rendererID, fiber);
            } catch (err) {
              {
                if (!hasLoggedError) {
                  hasLoggedError = true;
                  error("React instrumentation encountered an error: %s", err);
                }
              }
            }
          }
        }
        function setIsStrictModeForDevtools(newIsStrictMode) {
          {
            if (typeof unstable_yieldValue === "function") {
              unstable_setDisableYieldValue(newIsStrictMode);
              setSuppressWarning(newIsStrictMode);
            }
            if (injectedHook && typeof injectedHook.setStrictMode === "function") {
              try {
                injectedHook.setStrictMode(rendererID, newIsStrictMode);
              } catch (err) {
                {
                  if (!hasLoggedError) {
                    hasLoggedError = true;
                    error("React instrumentation encountered an error: %s", err);
                  }
                }
              }
            }
          }
        }
        function injectProfilingHooks(profilingHooks) {
          injectedProfilingHooks = profilingHooks;
        }
        function getLaneLabelMap() {
          {
            var map = /* @__PURE__ */ new Map();
            var lane = 1;
            for (var index3 = 0; index3 < TotalLanes; index3++) {
              var label = getLabelForLane(lane);
              map.set(lane, label);
              lane *= 2;
            }
            return map;
          }
        }
        function markCommitStarted(lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === "function") {
              injectedProfilingHooks.markCommitStarted(lanes);
            }
          }
        }
        function markCommitStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === "function") {
              injectedProfilingHooks.markCommitStopped();
            }
          }
        }
        function markComponentRenderStarted(fiber) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === "function") {
              injectedProfilingHooks.markComponentRenderStarted(fiber);
            }
          }
        }
        function markComponentRenderStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === "function") {
              injectedProfilingHooks.markComponentRenderStopped();
            }
          }
        }
        function markComponentPassiveEffectMountStarted(fiber) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === "function") {
              injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
            }
          }
        }
        function markComponentPassiveEffectMountStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === "function") {
              injectedProfilingHooks.markComponentPassiveEffectMountStopped();
            }
          }
        }
        function markComponentPassiveEffectUnmountStarted(fiber) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === "function") {
              injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
            }
          }
        }
        function markComponentPassiveEffectUnmountStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === "function") {
              injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
            }
          }
        }
        function markComponentLayoutEffectMountStarted(fiber) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === "function") {
              injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
            }
          }
        }
        function markComponentLayoutEffectMountStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === "function") {
              injectedProfilingHooks.markComponentLayoutEffectMountStopped();
            }
          }
        }
        function markComponentLayoutEffectUnmountStarted(fiber) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === "function") {
              injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
            }
          }
        }
        function markComponentLayoutEffectUnmountStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === "function") {
              injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
            }
          }
        }
        function markComponentErrored(fiber, thrownValue, lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === "function") {
              injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
            }
          }
        }
        function markComponentSuspended(fiber, wakeable, lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === "function") {
              injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
            }
          }
        }
        function markLayoutEffectsStarted(lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === "function") {
              injectedProfilingHooks.markLayoutEffectsStarted(lanes);
            }
          }
        }
        function markLayoutEffectsStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === "function") {
              injectedProfilingHooks.markLayoutEffectsStopped();
            }
          }
        }
        function markPassiveEffectsStarted(lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === "function") {
              injectedProfilingHooks.markPassiveEffectsStarted(lanes);
            }
          }
        }
        function markPassiveEffectsStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === "function") {
              injectedProfilingHooks.markPassiveEffectsStopped();
            }
          }
        }
        function markRenderStarted(lanes) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === "function") {
              injectedProfilingHooks.markRenderStarted(lanes);
            }
          }
        }
        function markRenderYielded() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === "function") {
              injectedProfilingHooks.markRenderYielded();
            }
          }
        }
        function markRenderStopped() {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === "function") {
              injectedProfilingHooks.markRenderStopped();
            }
          }
        }
        function markRenderScheduled(lane) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === "function") {
              injectedProfilingHooks.markRenderScheduled(lane);
            }
          }
        }
        function markForceUpdateScheduled(fiber, lane) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === "function") {
              injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
            }
          }
        }
        function markStateUpdateScheduled(fiber, lane) {
          {
            if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === "function") {
              injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
            }
          }
        }
        var NoMode = (
          /*                         */
          0
        );
        var ConcurrentMode = (
          /*                 */
          1
        );
        var ProfileMode = (
          /*                    */
          2
        );
        var StrictLegacyMode = (
          /*               */
          8
        );
        var StrictEffectsMode = (
          /*              */
          16
        );
        var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback;
        var log = Math.log;
        var LN2 = Math.LN2;
        function clz32Fallback(x2) {
          var asUint = x2 >>> 0;
          if (asUint === 0) {
            return 32;
          }
          return 31 - (log(asUint) / LN2 | 0) | 0;
        }
        var TotalLanes = 31;
        var NoLanes = (
          /*                        */
          0
        );
        var NoLane = (
          /*                          */
          0
        );
        var SyncLane = (
          /*                        */
          1
        );
        var InputContinuousHydrationLane = (
          /*    */
          2
        );
        var InputContinuousLane = (
          /*             */
          4
        );
        var DefaultHydrationLane = (
          /*            */
          8
        );
        var DefaultLane = (
          /*                     */
          16
        );
        var TransitionHydrationLane = (
          /*                */
          32
        );
        var TransitionLanes = (
          /*                       */
          4194240
        );
        var TransitionLane1 = (
          /*                        */
          64
        );
        var TransitionLane2 = (
          /*                        */
          128
        );
        var TransitionLane3 = (
          /*                        */
          256
        );
        var TransitionLane4 = (
          /*                        */
          512
        );
        var TransitionLane5 = (
          /*                        */
          1024
        );
        var TransitionLane6 = (
          /*                        */
          2048
        );
        var TransitionLane7 = (
          /*                        */
          4096
        );
        var TransitionLane8 = (
          /*                        */
          8192
        );
        var TransitionLane9 = (
          /*                        */
          16384
        );
        var TransitionLane10 = (
          /*                       */
          32768
        );
        var TransitionLane11 = (
          /*                       */
          65536
        );
        var TransitionLane12 = (
          /*                       */
          131072
        );
        var TransitionLane13 = (
          /*                       */
          262144
        );
        var TransitionLane14 = (
          /*                       */
          524288
        );
        var TransitionLane15 = (
          /*                       */
          1048576
        );
        var TransitionLane16 = (
          /*                       */
          2097152
        );
        var RetryLanes = (
          /*                            */
          130023424
        );
        var RetryLane1 = (
          /*                             */
          4194304
        );
        var RetryLane2 = (
          /*                             */
          8388608
        );
        var RetryLane3 = (
          /*                             */
          16777216
        );
        var RetryLane4 = (
          /*                             */
          33554432
        );
        var RetryLane5 = (
          /*                             */
          67108864
        );
        var SomeRetryLane = RetryLane1;
        var SelectiveHydrationLane = (
          /*          */
          134217728
        );
        var NonIdleLanes = (
          /*                          */
          268435455
        );
        var IdleHydrationLane = (
          /*               */
          268435456
        );
        var IdleLane = (
          /*                        */
          536870912
        );
        var OffscreenLane = (
          /*                   */
          1073741824
        );
        function getLabelForLane(lane) {
          {
            if (lane & SyncLane) {
              return "Sync";
            }
            if (lane & InputContinuousHydrationLane) {
              return "InputContinuousHydration";
            }
            if (lane & InputContinuousLane) {
              return "InputContinuous";
            }
            if (lane & DefaultHydrationLane) {
              return "DefaultHydration";
            }
            if (lane & DefaultLane) {
              return "Default";
            }
            if (lane & TransitionHydrationLane) {
              return "TransitionHydration";
            }
            if (lane & TransitionLanes) {
              return "Transition";
            }
            if (lane & RetryLanes) {
              return "Retry";
            }
            if (lane & SelectiveHydrationLane) {
              return "SelectiveHydration";
            }
            if (lane & IdleHydrationLane) {
              return "IdleHydration";
            }
            if (lane & IdleLane) {
              return "Idle";
            }
            if (lane & OffscreenLane) {
              return "Offscreen";
            }
          }
        }
        var NoTimestamp = -1;
        var nextTransitionLane = TransitionLane1;
        var nextRetryLane = RetryLane1;
        function getHighestPriorityLanes(lanes) {
          switch (getHighestPriorityLane(lanes)) {
            case SyncLane:
              return SyncLane;
            case InputContinuousHydrationLane:
              return InputContinuousHydrationLane;
            case InputContinuousLane:
              return InputContinuousLane;
            case DefaultHydrationLane:
              return DefaultHydrationLane;
            case DefaultLane:
              return DefaultLane;
            case TransitionHydrationLane:
              return TransitionHydrationLane;
            case TransitionLane1:
            case TransitionLane2:
            case TransitionLane3:
            case TransitionLane4:
            case TransitionLane5:
            case TransitionLane6:
            case TransitionLane7:
            case TransitionLane8:
            case TransitionLane9:
            case TransitionLane10:
            case TransitionLane11:
            case TransitionLane12:
            case TransitionLane13:
            case TransitionLane14:
            case TransitionLane15:
            case TransitionLane16:
              return lanes & TransitionLanes;
            case RetryLane1:
            case RetryLane2:
            case RetryLane3:
            case RetryLane4:
            case RetryLane5:
              return lanes & RetryLanes;
            case SelectiveHydrationLane:
              return SelectiveHydrationLane;
            case IdleHydrationLane:
              return IdleHydrationLane;
            case IdleLane:
              return IdleLane;
            case OffscreenLane:
              return OffscreenLane;
            default:
              {
                error("Should have found matching lanes. This is a bug in React.");
              }
              return lanes;
          }
        }
        function getNextLanes(root3, wipLanes) {
          var pendingLanes = root3.pendingLanes;
          if (pendingLanes === NoLanes) {
            return NoLanes;
          }
          var nextLanes = NoLanes;
          var suspendedLanes = root3.suspendedLanes;
          var pingedLanes = root3.pingedLanes;
          var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
          if (nonIdlePendingLanes !== NoLanes) {
            var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
            if (nonIdleUnblockedLanes !== NoLanes) {
              nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
            } else {
              var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
              if (nonIdlePingedLanes !== NoLanes) {
                nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
              }
            }
          } else {
            var unblockedLanes = pendingLanes & ~suspendedLanes;
            if (unblockedLanes !== NoLanes) {
              nextLanes = getHighestPriorityLanes(unblockedLanes);
            } else {
              if (pingedLanes !== NoLanes) {
                nextLanes = getHighestPriorityLanes(pingedLanes);
              }
            }
          }
          if (nextLanes === NoLanes) {
            return NoLanes;
          }
          if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
          // bother waiting until the root is complete.
          (wipLanes & suspendedLanes) === NoLanes) {
            var nextLane = getHighestPriorityLane(nextLanes);
            var wipLane = getHighestPriorityLane(wipLanes);
            if (
              // Tests whether the next lane is equal or lower priority than the wip
              // one. This works because the bits decrease in priority as you go left.
              nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
              // only difference between default updates and transition updates is that
              // default updates do not support refresh transitions.
              nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes
            ) {
              return wipLanes;
            }
          }
          if ((nextLanes & InputContinuousLane) !== NoLanes) {
            nextLanes |= pendingLanes & DefaultLane;
          }
          var entangledLanes = root3.entangledLanes;
          if (entangledLanes !== NoLanes) {
            var entanglements = root3.entanglements;
            var lanes = nextLanes & entangledLanes;
            while (lanes > 0) {
              var index3 = pickArbitraryLaneIndex(lanes);
              var lane = 1 << index3;
              nextLanes |= entanglements[index3];
              lanes &= ~lane;
            }
          }
          return nextLanes;
        }
        function getMostRecentEventTime(root3, lanes) {
          var eventTimes = root3.eventTimes;
          var mostRecentEventTime = NoTimestamp;
          while (lanes > 0) {
            var index3 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index3;
            var eventTime = eventTimes[index3];
            if (eventTime > mostRecentEventTime) {
              mostRecentEventTime = eventTime;
            }
            lanes &= ~lane;
          }
          return mostRecentEventTime;
        }
        function computeExpirationTime(lane, currentTime) {
          switch (lane) {
            case SyncLane:
            case InputContinuousHydrationLane:
            case InputContinuousLane:
              return currentTime + 250;
            case DefaultHydrationLane:
            case DefaultLane:
            case TransitionHydrationLane:
            case TransitionLane1:
            case TransitionLane2:
            case TransitionLane3:
            case TransitionLane4:
            case TransitionLane5:
            case TransitionLane6:
            case TransitionLane7:
            case TransitionLane8:
            case TransitionLane9:
            case TransitionLane10:
            case TransitionLane11:
            case TransitionLane12:
            case TransitionLane13:
            case TransitionLane14:
            case TransitionLane15:
            case TransitionLane16:
              return currentTime + 5e3;
            case RetryLane1:
            case RetryLane2:
            case RetryLane3:
            case RetryLane4:
            case RetryLane5:
              return NoTimestamp;
            case SelectiveHydrationLane:
            case IdleHydrationLane:
            case IdleLane:
            case OffscreenLane:
              return NoTimestamp;
            default:
              {
                error("Should have found matching lanes. This is a bug in React.");
              }
              return NoTimestamp;
          }
        }
        function markStarvedLanesAsExpired(root3, currentTime) {
          var pendingLanes = root3.pendingLanes;
          var suspendedLanes = root3.suspendedLanes;
          var pingedLanes = root3.pingedLanes;
          var expirationTimes = root3.expirationTimes;
          var lanes = pendingLanes;
          while (lanes > 0) {
            var index3 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index3;
            var expirationTime = expirationTimes[index3];
            if (expirationTime === NoTimestamp) {
              if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
                expirationTimes[index3] = computeExpirationTime(lane, currentTime);
              }
            } else if (expirationTime <= currentTime) {
              root3.expiredLanes |= lane;
            }
            lanes &= ~lane;
          }
        }
        function getHighestPriorityPendingLanes(root3) {
          return getHighestPriorityLanes(root3.pendingLanes);
        }
        function getLanesToRetrySynchronouslyOnError(root3) {
          var everythingButOffscreen = root3.pendingLanes & ~OffscreenLane;
          if (everythingButOffscreen !== NoLanes) {
            return everythingButOffscreen;
          }
          if (everythingButOffscreen & OffscreenLane) {
            return OffscreenLane;
          }
          return NoLanes;
        }
        function includesSyncLane(lanes) {
          return (lanes & SyncLane) !== NoLanes;
        }
        function includesNonIdleWork(lanes) {
          return (lanes & NonIdleLanes) !== NoLanes;
        }
        function includesOnlyRetries(lanes) {
          return (lanes & RetryLanes) === lanes;
        }
        function includesOnlyNonUrgentLanes(lanes) {
          var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
          return (lanes & UrgentLanes) === NoLanes;
        }
        function includesOnlyTransitions(lanes) {
          return (lanes & TransitionLanes) === lanes;
        }
        function includesBlockingLane(root3, lanes) {
          var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
          return (lanes & SyncDefaultLanes) !== NoLanes;
        }
        function includesExpiredLane(root3, lanes) {
          return (lanes & root3.expiredLanes) !== NoLanes;
        }
        function isTransitionLane(lane) {
          return (lane & TransitionLanes) !== NoLanes;
        }
        function claimNextTransitionLane() {
          var lane = nextTransitionLane;
          nextTransitionLane <<= 1;
          if ((nextTransitionLane & TransitionLanes) === NoLanes) {
            nextTransitionLane = TransitionLane1;
          }
          return lane;
        }
        function claimNextRetryLane() {
          var lane = nextRetryLane;
          nextRetryLane <<= 1;
          if ((nextRetryLane & RetryLanes) === NoLanes) {
            nextRetryLane = RetryLane1;
          }
          return lane;
        }
        function getHighestPriorityLane(lanes) {
          return lanes & -lanes;
        }
        function pickArbitraryLane(lanes) {
          return getHighestPriorityLane(lanes);
        }
        function pickArbitraryLaneIndex(lanes) {
          return 31 - clz32(lanes);
        }
        function laneToIndex(lane) {
          return pickArbitraryLaneIndex(lane);
        }
        function includesSomeLane(a3, b3) {
          return (a3 & b3) !== NoLanes;
        }
        function isSubsetOfLanes(set2, subset) {
          return (set2 & subset) === subset;
        }
        function mergeLanes(a3, b3) {
          return a3 | b3;
        }
        function removeLanes(set2, subset) {
          return set2 & ~subset;
        }
        function intersectLanes(a3, b3) {
          return a3 & b3;
        }
        function laneToLanes(lane) {
          return lane;
        }
        function higherPriorityLane(a3, b3) {
          return a3 !== NoLane && a3 < b3 ? a3 : b3;
        }
        function createLaneMap(initial) {
          var laneMap = [];
          for (var i3 = 0; i3 < TotalLanes; i3++) {
            laneMap.push(initial);
          }
          return laneMap;
        }
        function markRootUpdated(root3, updateLane, eventTime) {
          root3.pendingLanes |= updateLane;
          if (updateLane !== IdleLane) {
            root3.suspendedLanes = NoLanes;
            root3.pingedLanes = NoLanes;
          }
          var eventTimes = root3.eventTimes;
          var index3 = laneToIndex(updateLane);
          eventTimes[index3] = eventTime;
        }
        function markRootSuspended(root3, suspendedLanes) {
          root3.suspendedLanes |= suspendedLanes;
          root3.pingedLanes &= ~suspendedLanes;
          var expirationTimes = root3.expirationTimes;
          var lanes = suspendedLanes;
          while (lanes > 0) {
            var index3 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index3;
            expirationTimes[index3] = NoTimestamp;
            lanes &= ~lane;
          }
        }
        function markRootPinged(root3, pingedLanes, eventTime) {
          root3.pingedLanes |= root3.suspendedLanes & pingedLanes;
        }
        function markRootFinished(root3, remainingLanes) {
          var noLongerPendingLanes = root3.pendingLanes & ~remainingLanes;
          root3.pendingLanes = remainingLanes;
          root3.suspendedLanes = NoLanes;
          root3.pingedLanes = NoLanes;
          root3.expiredLanes &= remainingLanes;
          root3.mutableReadLanes &= remainingLanes;
          root3.entangledLanes &= remainingLanes;
          var entanglements = root3.entanglements;
          var eventTimes = root3.eventTimes;
          var expirationTimes = root3.expirationTimes;
          var lanes = noLongerPendingLanes;
          while (lanes > 0) {
            var index3 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index3;
            entanglements[index3] = NoLanes;
            eventTimes[index3] = NoTimestamp;
            expirationTimes[index3] = NoTimestamp;
            lanes &= ~lane;
          }
        }
        function markRootEntangled(root3, entangledLanes) {
          var rootEntangledLanes = root3.entangledLanes |= entangledLanes;
          var entanglements = root3.entanglements;
          var lanes = rootEntangledLanes;
          while (lanes) {
            var index3 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index3;
            if (
              // Is this one of the newly entangled lanes?
              lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
              entanglements[index3] & entangledLanes
            ) {
              entanglements[index3] |= entangledLanes;
            }
            lanes &= ~lane;
          }
        }
        function getBumpedLaneForHydration(root3, renderLanes2) {
          var renderLane = getHighestPriorityLane(renderLanes2);
          var lane;
          switch (renderLane) {
            case InputContinuousLane:
              lane = InputContinuousHydrationLane;
              break;
            case DefaultLane:
              lane = DefaultHydrationLane;
              break;
            case TransitionLane1:
            case TransitionLane2:
            case TransitionLane3:
            case TransitionLane4:
            case TransitionLane5:
            case TransitionLane6:
            case TransitionLane7:
            case TransitionLane8:
            case TransitionLane9:
            case TransitionLane10:
            case TransitionLane11:
            case TransitionLane12:
            case TransitionLane13:
            case TransitionLane14:
            case TransitionLane15:
            case TransitionLane16:
            case RetryLane1:
            case RetryLane2:
            case RetryLane3:
            case RetryLane4:
            case RetryLane5:
              lane = TransitionHydrationLane;
              break;
            case IdleLane:
              lane = IdleHydrationLane;
              break;
            default:
              lane = NoLane;
              break;
          }
          if ((lane & (root3.suspendedLanes | renderLanes2)) !== NoLane) {
            return NoLane;
          }
          return lane;
        }
        function addFiberToLanesMap(root3, fiber, lanes) {
          if (!isDevToolsPresent) {
            return;
          }
          var pendingUpdatersLaneMap = root3.pendingUpdatersLaneMap;
          while (lanes > 0) {
            var index3 = laneToIndex(lanes);
            var lane = 1 << index3;
            var updaters = pendingUpdatersLaneMap[index3];
            updaters.add(fiber);
            lanes &= ~lane;
          }
        }
        function movePendingFibersToMemoized(root3, lanes) {
          if (!isDevToolsPresent) {
            return;
          }
          var pendingUpdatersLaneMap = root3.pendingUpdatersLaneMap;
          var memoizedUpdaters = root3.memoizedUpdaters;
          while (lanes > 0) {
            var index3 = laneToIndex(lanes);
            var lane = 1 << index3;
            var updaters = pendingUpdatersLaneMap[index3];
            if (updaters.size > 0) {
              updaters.forEach(function(fiber) {
                var alternate = fiber.alternate;
                if (alternate === null || !memoizedUpdaters.has(alternate)) {
                  memoizedUpdaters.add(fiber);
                }
              });
              updaters.clear();
            }
            lanes &= ~lane;
          }
        }
        function getTransitionsForLanes(root3, lanes) {
          {
            return null;
          }
        }
        var DiscreteEventPriority = SyncLane;
        var ContinuousEventPriority = InputContinuousLane;
        var DefaultEventPriority = DefaultLane;
        var IdleEventPriority = IdleLane;
        var currentUpdatePriority = NoLane;
        function getCurrentUpdatePriority() {
          return currentUpdatePriority;
        }
        function setCurrentUpdatePriority(newPriority) {
          currentUpdatePriority = newPriority;
        }
        function runWithPriority(priority, fn) {
          var previousPriority = currentUpdatePriority;
          try {
            currentUpdatePriority = priority;
            return fn();
          } finally {
            currentUpdatePriority = previousPriority;
          }
        }
        function higherEventPriority(a3, b3) {
          return a3 !== 0 && a3 < b3 ? a3 : b3;
        }
        function lowerEventPriority(a3, b3) {
          return a3 === 0 || a3 > b3 ? a3 : b3;
        }
        function isHigherEventPriority(a3, b3) {
          return a3 !== 0 && a3 < b3;
        }
        function lanesToEventPriority(lanes) {
          var lane = getHighestPriorityLane(lanes);
          if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
            return DiscreteEventPriority;
          }
          if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
            return ContinuousEventPriority;
          }
          if (includesNonIdleWork(lane)) {
            return DefaultEventPriority;
          }
          return IdleEventPriority;
        }
        function isRootDehydrated(root3) {
          var currentState = root3.current.memoizedState;
          return currentState.isDehydrated;
        }
        var _attemptSynchronousHydration;
        function setAttemptSynchronousHydration(fn) {
          _attemptSynchronousHydration = fn;
        }
        function attemptSynchronousHydration(fiber) {
          _attemptSynchronousHydration(fiber);
        }
        var attemptContinuousHydration;
        function setAttemptContinuousHydration(fn) {
          attemptContinuousHydration = fn;
        }
        var attemptHydrationAtCurrentPriority;
        function setAttemptHydrationAtCurrentPriority(fn) {
          attemptHydrationAtCurrentPriority = fn;
        }
        var getCurrentUpdatePriority$1;
        function setGetCurrentUpdatePriority(fn) {
          getCurrentUpdatePriority$1 = fn;
        }
        var attemptHydrationAtPriority;
        function setAttemptHydrationAtPriority(fn) {
          attemptHydrationAtPriority = fn;
        }
        var hasScheduledReplayAttempt = false;
        var queuedDiscreteEvents = [];
        var queuedFocus = null;
        var queuedDrag = null;
        var queuedMouse = null;
        var queuedPointers = /* @__PURE__ */ new Map();
        var queuedPointerCaptures = /* @__PURE__ */ new Map();
        var queuedExplicitHydrationTargets = [];
        var discreteReplayableEvents = [
          "mousedown",
          "mouseup",
          "touchcancel",
          "touchend",
          "touchstart",
          "auxclick",
          "dblclick",
          "pointercancel",
          "pointerdown",
          "pointerup",
          "dragend",
          "dragstart",
          "drop",
          "compositionend",
          "compositionstart",
          "keydown",
          "keypress",
          "keyup",
          "input",
          "textInput",
          // Intentionally camelCase
          "copy",
          "cut",
          "paste",
          "click",
          "change",
          "contextmenu",
          "reset",
          "submit"
        ];
        function isDiscreteEventThatRequiresHydration(eventType) {
          return discreteReplayableEvents.indexOf(eventType) > -1;
        }
        function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          return {
            blockedOn,
            domEventName,
            eventSystemFlags,
            nativeEvent,
            targetContainers: [targetContainer]
          };
        }
        function clearIfContinuousEvent(domEventName, nativeEvent) {
          switch (domEventName) {
            case "focusin":
            case "focusout":
              queuedFocus = null;
              break;
            case "dragenter":
            case "dragleave":
              queuedDrag = null;
              break;
            case "mouseover":
            case "mouseout":
              queuedMouse = null;
              break;
            case "pointerover":
            case "pointerout": {
              var pointerId = nativeEvent.pointerId;
              queuedPointers.delete(pointerId);
              break;
            }
            case "gotpointercapture":
            case "lostpointercapture": {
              var _pointerId = nativeEvent.pointerId;
              queuedPointerCaptures.delete(_pointerId);
              break;
            }
          }
        }
        function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
            var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
            if (blockedOn !== null) {
              var _fiber2 = getInstanceFromNode(blockedOn);
              if (_fiber2 !== null) {
                attemptContinuousHydration(_fiber2);
              }
            }
            return queuedEvent;
          }
          existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
          var targetContainers = existingQueuedEvent.targetContainers;
          if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
            targetContainers.push(targetContainer);
          }
          return existingQueuedEvent;
        }
        function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          switch (domEventName) {
            case "focusin": {
              var focusEvent = nativeEvent;
              queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
              return true;
            }
            case "dragenter": {
              var dragEvent = nativeEvent;
              queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
              return true;
            }
            case "mouseover": {
              var mouseEvent = nativeEvent;
              queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
              return true;
            }
            case "pointerover": {
              var pointerEvent = nativeEvent;
              var pointerId = pointerEvent.pointerId;
              queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
              return true;
            }
            case "gotpointercapture": {
              var _pointerEvent = nativeEvent;
              var _pointerId2 = _pointerEvent.pointerId;
              queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
              return true;
            }
          }
          return false;
        }
        function attemptExplicitHydrationTarget(queuedTarget) {
          var targetInst = getClosestInstanceFromNode(queuedTarget.target);
          if (targetInst !== null) {
            var nearestMounted = getNearestMountedFiber(targetInst);
            if (nearestMounted !== null) {
              var tag = nearestMounted.tag;
              if (tag === SuspenseComponent) {
                var instance = getSuspenseInstanceFromFiber(nearestMounted);
                if (instance !== null) {
                  queuedTarget.blockedOn = instance;
                  attemptHydrationAtPriority(queuedTarget.priority, function() {
                    attemptHydrationAtCurrentPriority(nearestMounted);
                  });
                  return;
                }
              } else if (tag === HostRoot) {
                var root3 = nearestMounted.stateNode;
                if (isRootDehydrated(root3)) {
                  queuedTarget.blockedOn = getContainerFromFiber(nearestMounted);
                  return;
                }
              }
            }
          }
          queuedTarget.blockedOn = null;
        }
        function queueExplicitHydrationTarget(target) {
          var updatePriority = getCurrentUpdatePriority$1();
          var queuedTarget = {
            blockedOn: null,
            target,
            priority: updatePriority
          };
          var i3 = 0;
          for (; i3 < queuedExplicitHydrationTargets.length; i3++) {
            if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i3].priority)) {
              break;
            }
          }
          queuedExplicitHydrationTargets.splice(i3, 0, queuedTarget);
          if (i3 === 0) {
            attemptExplicitHydrationTarget(queuedTarget);
          }
        }
        function attemptReplayContinuousQueuedEvent(queuedEvent) {
          if (queuedEvent.blockedOn !== null) {
            return false;
          }
          var targetContainers = queuedEvent.targetContainers;
          while (targetContainers.length > 0) {
            var targetContainer = targetContainers[0];
            var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);
            if (nextBlockedOn === null) {
              {
                var nativeEvent = queuedEvent.nativeEvent;
                var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
                setReplayingEvent(nativeEventClone);
                nativeEvent.target.dispatchEvent(nativeEventClone);
                resetReplayingEvent();
              }
            } else {
              var _fiber3 = getInstanceFromNode(nextBlockedOn);
              if (_fiber3 !== null) {
                attemptContinuousHydration(_fiber3);
              }
              queuedEvent.blockedOn = nextBlockedOn;
              return false;
            }
            targetContainers.shift();
          }
          return true;
        }
        function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
          if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
            map.delete(key);
          }
        }
        function replayUnblockedEvents() {
          hasScheduledReplayAttempt = false;
          if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
            queuedFocus = null;
          }
          if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
            queuedDrag = null;
          }
          if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
            queuedMouse = null;
          }
          queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
          queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
        }
        function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
          if (queuedEvent.blockedOn === unblocked) {
            queuedEvent.blockedOn = null;
            if (!hasScheduledReplayAttempt) {
              hasScheduledReplayAttempt = true;
              Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
            }
          }
        }
        function retryIfBlockedOn(unblocked) {
          if (queuedDiscreteEvents.length > 0) {
            scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked);
            for (var i3 = 1; i3 < queuedDiscreteEvents.length; i3++) {
              var queuedEvent = queuedDiscreteEvents[i3];
              if (queuedEvent.blockedOn === unblocked) {
                queuedEvent.blockedOn = null;
              }
            }
          }
          if (queuedFocus !== null) {
            scheduleCallbackIfUnblocked(queuedFocus, unblocked);
          }
          if (queuedDrag !== null) {
            scheduleCallbackIfUnblocked(queuedDrag, unblocked);
          }
          if (queuedMouse !== null) {
            scheduleCallbackIfUnblocked(queuedMouse, unblocked);
          }
          var unblock = function(queuedEvent2) {
            return scheduleCallbackIfUnblocked(queuedEvent2, unblocked);
          };
          queuedPointers.forEach(unblock);
          queuedPointerCaptures.forEach(unblock);
          for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
            var queuedTarget = queuedExplicitHydrationTargets[_i];
            if (queuedTarget.blockedOn === unblocked) {
              queuedTarget.blockedOn = null;
            }
          }
          while (queuedExplicitHydrationTargets.length > 0) {
            var nextExplicitTarget = queuedExplicitHydrationTargets[0];
            if (nextExplicitTarget.blockedOn !== null) {
              break;
            } else {
              attemptExplicitHydrationTarget(nextExplicitTarget);
              if (nextExplicitTarget.blockedOn === null) {
                queuedExplicitHydrationTargets.shift();
              }
            }
          }
        }
        var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
        var _enabled = true;
        function setEnabled(enabled) {
          _enabled = !!enabled;
        }
        function isEnabled() {
          return _enabled;
        }
        function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
          var eventPriority = getEventPriority(domEventName);
          var listenerWrapper;
          switch (eventPriority) {
            case DiscreteEventPriority:
              listenerWrapper = dispatchDiscreteEvent;
              break;
            case ContinuousEventPriority:
              listenerWrapper = dispatchContinuousEvent;
              break;
            case DefaultEventPriority:
            default:
              listenerWrapper = dispatchEvent;
              break;
          }
          return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
        }
        function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
          var previousPriority = getCurrentUpdatePriority();
          var prevTransition = ReactCurrentBatchConfig.transition;
          ReactCurrentBatchConfig.transition = null;
          try {
            setCurrentUpdatePriority(DiscreteEventPriority);
            dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig.transition = prevTransition;
          }
        }
        function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
          var previousPriority = getCurrentUpdatePriority();
          var prevTransition = ReactCurrentBatchConfig.transition;
          ReactCurrentBatchConfig.transition = null;
          try {
            setCurrentUpdatePriority(ContinuousEventPriority);
            dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig.transition = prevTransition;
          }
        }
        function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          if (!_enabled) {
            return;
          }
          {
            dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
          }
        }
        function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
          if (blockedOn === null) {
            dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
            clearIfContinuousEvent(domEventName, nativeEvent);
            return;
          }
          if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
            nativeEvent.stopPropagation();
            return;
          }
          clearIfContinuousEvent(domEventName, nativeEvent);
          if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
            while (blockedOn !== null) {
              var fiber = getInstanceFromNode(blockedOn);
              if (fiber !== null) {
                attemptSynchronousHydration(fiber);
              }
              var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
              if (nextBlockedOn === null) {
                dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
              }
              if (nextBlockedOn === blockedOn) {
                break;
              }
              blockedOn = nextBlockedOn;
            }
            if (blockedOn !== null) {
              nativeEvent.stopPropagation();
            }
            return;
          }
          dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
        }
        var return_targetInst = null;
        function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
          return_targetInst = null;
          var nativeEventTarget = getEventTarget(nativeEvent);
          var targetInst = getClosestInstanceFromNode(nativeEventTarget);
          if (targetInst !== null) {
            var nearestMounted = getNearestMountedFiber(targetInst);
            if (nearestMounted === null) {
              targetInst = null;
            } else {
              var tag = nearestMounted.tag;
              if (tag === SuspenseComponent) {
                var instance = getSuspenseInstanceFromFiber(nearestMounted);
                if (instance !== null) {
                  return instance;
                }
                targetInst = null;
              } else if (tag === HostRoot) {
                var root3 = nearestMounted.stateNode;
                if (isRootDehydrated(root3)) {
                  return getContainerFromFiber(nearestMounted);
                }
                targetInst = null;
              } else if (nearestMounted !== targetInst) {
                targetInst = null;
              }
            }
          }
          return_targetInst = targetInst;
          return null;
        }
        function getEventPriority(domEventName) {
          switch (domEventName) {
            case "cancel":
            case "click":
            case "close":
            case "contextmenu":
            case "copy":
            case "cut":
            case "auxclick":
            case "dblclick":
            case "dragend":
            case "dragstart":
            case "drop":
            case "focusin":
            case "focusout":
            case "input":
            case "invalid":
            case "keydown":
            case "keypress":
            case "keyup":
            case "mousedown":
            case "mouseup":
            case "paste":
            case "pause":
            case "play":
            case "pointercancel":
            case "pointerdown":
            case "pointerup":
            case "ratechange":
            case "reset":
            case "resize":
            case "seeked":
            case "submit":
            case "touchcancel":
            case "touchend":
            case "touchstart":
            case "volumechange":
            case "change":
            case "selectionchange":
            case "textInput":
            case "compositionstart":
            case "compositionend":
            case "compositionupdate":
            case "beforeblur":
            case "afterblur":
            case "beforeinput":
            case "blur":
            case "fullscreenchange":
            case "focus":
            case "hashchange":
            case "popstate":
            case "select":
            case "selectstart":
              return DiscreteEventPriority;
            case "drag":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "mousemove":
            case "mouseout":
            case "mouseover":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "scroll":
            case "toggle":
            case "touchmove":
            case "wheel":
            case "mouseenter":
            case "mouseleave":
            case "pointerenter":
            case "pointerleave":
              return ContinuousEventPriority;
            case "message": {
              var schedulerPriority = getCurrentPriorityLevel();
              switch (schedulerPriority) {
                case ImmediatePriority:
                  return DiscreteEventPriority;
                case UserBlockingPriority:
                  return ContinuousEventPriority;
                case NormalPriority:
                case LowPriority:
                  return DefaultEventPriority;
                case IdlePriority:
                  return IdleEventPriority;
                default:
                  return DefaultEventPriority;
              }
            }
            default:
              return DefaultEventPriority;
          }
        }
        function addEventBubbleListener(target, eventType, listener) {
          target.addEventListener(eventType, listener, false);
          return listener;
        }
        function addEventCaptureListener(target, eventType, listener) {
          target.addEventListener(eventType, listener, true);
          return listener;
        }
        function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
          target.addEventListener(eventType, listener, {
            capture: true,
            passive
          });
          return listener;
        }
        function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
          target.addEventListener(eventType, listener, {
            passive
          });
          return listener;
        }
        var root2 = null;
        var startText = null;
        var fallbackText = null;
        function initialize(nativeEventTarget) {
          root2 = nativeEventTarget;
          startText = getText2();
          return true;
        }
        function reset() {
          root2 = null;
          startText = null;
          fallbackText = null;
        }
        function getData() {
          if (fallbackText) {
            return fallbackText;
          }
          var start;
          var startValue = startText;
          var startLength = startValue.length;
          var end;
          var endValue = getText2();
          var endLength = endValue.length;
          for (start = 0; start < startLength; start++) {
            if (startValue[start] !== endValue[start]) {
              break;
            }
          }
          var minEnd = startLength - start;
          for (end = 1; end <= minEnd; end++) {
            if (startValue[startLength - end] !== endValue[endLength - end]) {
              break;
            }
          }
          var sliceTail = end > 1 ? 1 - end : void 0;
          fallbackText = endValue.slice(start, sliceTail);
          return fallbackText;
        }
        function getText2() {
          if ("value" in root2) {
            return root2.value;
          }
          return root2.textContent;
        }
        function getEventCharCode(nativeEvent) {
          var charCode;
          var keyCode = nativeEvent.keyCode;
          if ("charCode" in nativeEvent) {
            charCode = nativeEvent.charCode;
            if (charCode === 0 && keyCode === 13) {
              charCode = 13;
            }
          } else {
            charCode = keyCode;
          }
          if (charCode === 10) {
            charCode = 13;
          }
          if (charCode >= 32 || charCode === 13) {
            return charCode;
          }
          return 0;
        }
        function functionThatReturnsTrue() {
          return true;
        }
        function functionThatReturnsFalse() {
          return false;
        }
        function createSyntheticEvent(Interface) {
          function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
            this._reactName = reactName;
            this._targetInst = targetInst;
            this.type = reactEventType;
            this.nativeEvent = nativeEvent;
            this.target = nativeEventTarget;
            this.currentTarget = null;
            for (var _propName in Interface) {
              if (!Interface.hasOwnProperty(_propName)) {
                continue;
              }
              var normalize = Interface[_propName];
              if (normalize) {
                this[_propName] = normalize(nativeEvent);
              } else {
                this[_propName] = nativeEvent[_propName];
              }
            }
            var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
            if (defaultPrevented) {
              this.isDefaultPrevented = functionThatReturnsTrue;
            } else {
              this.isDefaultPrevented = functionThatReturnsFalse;
            }
            this.isPropagationStopped = functionThatReturnsFalse;
            return this;
          }
          assign(SyntheticBaseEvent.prototype, {
            preventDefault: function() {
              this.defaultPrevented = true;
              var event = this.nativeEvent;
              if (!event) {
                return;
              }
              if (event.preventDefault) {
                event.preventDefault();
              } else if (typeof event.returnValue !== "unknown") {
                event.returnValue = false;
              }
              this.isDefaultPrevented = functionThatReturnsTrue;
            },
            stopPropagation: function() {
              var event = this.nativeEvent;
              if (!event) {
                return;
              }
              if (event.stopPropagation) {
                event.stopPropagation();
              } else if (typeof event.cancelBubble !== "unknown") {
                event.cancelBubble = true;
              }
              this.isPropagationStopped = functionThatReturnsTrue;
            },
            /**
             * We release all dispatched `SyntheticEvent`s after each event loop, adding
             * them back into the pool. This allows a way to hold onto a reference that
             * won't be added back into the pool.
             */
            persist: function() {
            },
            /**
             * Checks if this event should be released back into the pool.
             *
             * @return {boolean} True if this should not be released, false otherwise.
             */
            isPersistent: functionThatReturnsTrue
          });
          return SyntheticBaseEvent;
        }
        var EventInterface = {
          eventPhase: 0,
          bubbles: 0,
          cancelable: 0,
          timeStamp: function(event) {
            return event.timeStamp || Date.now();
          },
          defaultPrevented: 0,
          isTrusted: 0
        };
        var SyntheticEvent = createSyntheticEvent(EventInterface);
        var UIEventInterface = assign({}, EventInterface, {
          view: 0,
          detail: 0
        });
        var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
        var lastMovementX;
        var lastMovementY;
        var lastMouseEvent;
        function updateMouseMovementPolyfillState(event) {
          if (event !== lastMouseEvent) {
            if (lastMouseEvent && event.type === "mousemove") {
              lastMovementX = event.screenX - lastMouseEvent.screenX;
              lastMovementY = event.screenY - lastMouseEvent.screenY;
            } else {
              lastMovementX = 0;
              lastMovementY = 0;
            }
            lastMouseEvent = event;
          }
        }
        var MouseEventInterface = assign({}, UIEventInterface, {
          screenX: 0,
          screenY: 0,
          clientX: 0,
          clientY: 0,
          pageX: 0,
          pageY: 0,
          ctrlKey: 0,
          shiftKey: 0,
          altKey: 0,
          metaKey: 0,
          getModifierState: getEventModifierState,
          button: 0,
          buttons: 0,
          relatedTarget: function(event) {
            if (event.relatedTarget === void 0)
              return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
            return event.relatedTarget;
          },
          movementX: function(event) {
            if ("movementX" in event) {
              return event.movementX;
            }
            updateMouseMovementPolyfillState(event);
            return lastMovementX;
          },
          movementY: function(event) {
            if ("movementY" in event) {
              return event.movementY;
            }
            return lastMovementY;
          }
        });
        var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
        var DragEventInterface = assign({}, MouseEventInterface, {
          dataTransfer: 0
        });
        var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
        var FocusEventInterface = assign({}, UIEventInterface, {
          relatedTarget: 0
        });
        var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
        var AnimationEventInterface = assign({}, EventInterface, {
          animationName: 0,
          elapsedTime: 0,
          pseudoElement: 0
        });
        var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
        var ClipboardEventInterface = assign({}, EventInterface, {
          clipboardData: function(event) {
            return "clipboardData" in event ? event.clipboardData : window.clipboardData;
          }
        });
        var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
        var CompositionEventInterface = assign({}, EventInterface, {
          data: 0
        });
        var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
        var SyntheticInputEvent = SyntheticCompositionEvent;
        var normalizeKey = {
          Esc: "Escape",
          Spacebar: " ",
          Left: "ArrowLeft",
          Up: "ArrowUp",
          Right: "ArrowRight",
          Down: "ArrowDown",
          Del: "Delete",
          Win: "OS",
          Menu: "ContextMenu",
          Apps: "ContextMenu",
          Scroll: "ScrollLock",
          MozPrintableKey: "Unidentified"
        };
        var translateToKey = {
          "8": "Backspace",
          "9": "Tab",
          "12": "Clear",
          "13": "Enter",
          "16": "Shift",
          "17": "Control",
          "18": "Alt",
          "19": "Pause",
          "20": "CapsLock",
          "27": "Escape",
          "32": " ",
          "33": "PageUp",
          "34": "PageDown",
          "35": "End",
          "36": "Home",
          "37": "ArrowLeft",
          "38": "ArrowUp",
          "39": "ArrowRight",
          "40": "ArrowDown",
          "45": "Insert",
          "46": "Delete",
          "112": "F1",
          "113": "F2",
          "114": "F3",
          "115": "F4",
          "116": "F5",
          "117": "F6",
          "118": "F7",
          "119": "F8",
          "120": "F9",
          "121": "F10",
          "122": "F11",
          "123": "F12",
          "144": "NumLock",
          "145": "ScrollLock",
          "224": "Meta"
        };
        function getEventKey(nativeEvent) {
          if (nativeEvent.key) {
            var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
            if (key !== "Unidentified") {
              return key;
            }
          }
          if (nativeEvent.type === "keypress") {
            var charCode = getEventCharCode(nativeEvent);
            return charCode === 13 ? "Enter" : String.fromCharCode(charCode);
          }
          if (nativeEvent.type === "keydown" || nativeEvent.type === "keyup") {
            return translateToKey[nativeEvent.keyCode] || "Unidentified";
          }
          return "";
        }
        var modifierKeyToProp = {
          Alt: "altKey",
          Control: "ctrlKey",
          Meta: "metaKey",
          Shift: "shiftKey"
        };
        function modifierStateGetter(keyArg) {
          var syntheticEvent = this;
          var nativeEvent = syntheticEvent.nativeEvent;
          if (nativeEvent.getModifierState) {
            return nativeEvent.getModifierState(keyArg);
          }
          var keyProp = modifierKeyToProp[keyArg];
          return keyProp ? !!nativeEvent[keyProp] : false;
        }
        function getEventModifierState(nativeEvent) {
          return modifierStateGetter;
        }
        var KeyboardEventInterface = assign({}, UIEventInterface, {
          key: getEventKey,
          code: 0,
          location: 0,
          ctrlKey: 0,
          shiftKey: 0,
          altKey: 0,
          metaKey: 0,
          repeat: 0,
          locale: 0,
          getModifierState: getEventModifierState,
          // Legacy Interface
          charCode: function(event) {
            if (event.type === "keypress") {
              return getEventCharCode(event);
            }
            return 0;
          },
          keyCode: function(event) {
            if (event.type === "keydown" || event.type === "keyup") {
              return event.keyCode;
            }
            return 0;
          },
          which: function(event) {
            if (event.type === "keypress") {
              return getEventCharCode(event);
            }
            if (event.type === "keydown" || event.type === "keyup") {
              return event.keyCode;
            }
            return 0;
          }
        });
        var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
        var PointerEventInterface = assign({}, MouseEventInterface, {
          pointerId: 0,
          width: 0,
          height: 0,
          pressure: 0,
          tangentialPressure: 0,
          tiltX: 0,
          tiltY: 0,
          twist: 0,
          pointerType: 0,
          isPrimary: 0
        });
        var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
        var TouchEventInterface = assign({}, UIEventInterface, {
          touches: 0,
          targetTouches: 0,
          changedTouches: 0,
          altKey: 0,
          metaKey: 0,
          ctrlKey: 0,
          shiftKey: 0,
          getModifierState: getEventModifierState
        });
        var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
        var TransitionEventInterface = assign({}, EventInterface, {
          propertyName: 0,
          elapsedTime: 0,
          pseudoElement: 0
        });
        var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
        var WheelEventInterface = assign({}, MouseEventInterface, {
          deltaX: function(event) {
            return "deltaX" in event ? event.deltaX : (
              // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
              "wheelDeltaX" in event ? -event.wheelDeltaX : 0
            );
          },
          deltaY: function(event) {
            return "deltaY" in event ? event.deltaY : (
              // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
              "wheelDeltaY" in event ? -event.wheelDeltaY : (
                // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
                "wheelDelta" in event ? -event.wheelDelta : 0
              )
            );
          },
          deltaZ: 0,
          // Browsers without "deltaMode" is reporting in raw wheel delta where one
          // notch on the scroll is always +/- 120, roughly equivalent to pixels.
          // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
          // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
          deltaMode: 0
        });
        var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
        var END_KEYCODES = [9, 13, 27, 32];
        var START_KEYCODE = 229;
        var canUseCompositionEvent = canUseDOM && "CompositionEvent" in window;
        var documentMode = null;
        if (canUseDOM && "documentMode" in document) {
          documentMode = document.documentMode;
        }
        var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode;
        var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
        var SPACEBAR_CODE = 32;
        var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
        function registerEvents() {
          registerTwoPhaseEvent("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
          registerTwoPhaseEvent("onCompositionEnd", ["compositionend", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
          registerTwoPhaseEvent("onCompositionStart", ["compositionstart", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
          registerTwoPhaseEvent("onCompositionUpdate", ["compositionupdate", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
        }
        var hasSpaceKeypress = false;
        function isKeypressCommand(nativeEvent) {
          return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
          !(nativeEvent.ctrlKey && nativeEvent.altKey);
        }
        function getCompositionEventType(domEventName) {
          switch (domEventName) {
            case "compositionstart":
              return "onCompositionStart";
            case "compositionend":
              return "onCompositionEnd";
            case "compositionupdate":
              return "onCompositionUpdate";
          }
        }
        function isFallbackCompositionStart(domEventName, nativeEvent) {
          return domEventName === "keydown" && nativeEvent.keyCode === START_KEYCODE;
        }
        function isFallbackCompositionEnd(domEventName, nativeEvent) {
          switch (domEventName) {
            case "keyup":
              return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
            case "keydown":
              return nativeEvent.keyCode !== START_KEYCODE;
            case "keypress":
            case "mousedown":
            case "focusout":
              return true;
            default:
              return false;
          }
        }
        function getDataFromCustomEvent(nativeEvent) {
          var detail = nativeEvent.detail;
          if (typeof detail === "object" && "data" in detail) {
            return detail.data;
          }
          return null;
        }
        function isUsingKoreanIME(nativeEvent) {
          return nativeEvent.locale === "ko";
        }
        var isComposing = false;
        function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
          var eventType;
          var fallbackData;
          if (canUseCompositionEvent) {
            eventType = getCompositionEventType(domEventName);
          } else if (!isComposing) {
            if (isFallbackCompositionStart(domEventName, nativeEvent)) {
              eventType = "onCompositionStart";
            }
          } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
            eventType = "onCompositionEnd";
          }
          if (!eventType) {
            return null;
          }
          if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
            if (!isComposing && eventType === "onCompositionStart") {
              isComposing = initialize(nativeEventTarget);
            } else if (eventType === "onCompositionEnd") {
              if (isComposing) {
                fallbackData = getData();
              }
            }
          }
          var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
          if (listeners.length > 0) {
            var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
            dispatchQueue.push({
              event,
              listeners
            });
            if (fallbackData) {
              event.data = fallbackData;
            } else {
              var customData = getDataFromCustomEvent(nativeEvent);
              if (customData !== null) {
                event.data = customData;
              }
            }
          }
        }
        function getNativeBeforeInputChars(domEventName, nativeEvent) {
          switch (domEventName) {
            case "compositionend":
              return getDataFromCustomEvent(nativeEvent);
            case "keypress":
              var which = nativeEvent.which;
              if (which !== SPACEBAR_CODE) {
                return null;
              }
              hasSpaceKeypress = true;
              return SPACEBAR_CHAR;
            case "textInput":
              var chars = nativeEvent.data;
              if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
                return null;
              }
              return chars;
            default:
              return null;
          }
        }
        function getFallbackBeforeInputChars(domEventName, nativeEvent) {
          if (isComposing) {
            if (domEventName === "compositionend" || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
              var chars = getData();
              reset();
              isComposing = false;
              return chars;
            }
            return null;
          }
          switch (domEventName) {
            case "paste":
              return null;
            case "keypress":
              if (!isKeypressCommand(nativeEvent)) {
                if (nativeEvent.char && nativeEvent.char.length > 1) {
                  return nativeEvent.char;
                } else if (nativeEvent.which) {
                  return String.fromCharCode(nativeEvent.which);
                }
              }
              return null;
            case "compositionend":
              return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
            default:
              return null;
          }
        }
        function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
          var chars;
          if (canUseTextInputEvent) {
            chars = getNativeBeforeInputChars(domEventName, nativeEvent);
          } else {
            chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
          }
          if (!chars) {
            return null;
          }
          var listeners = accumulateTwoPhaseListeners(targetInst, "onBeforeInput");
          if (listeners.length > 0) {
            var event = new SyntheticInputEvent("onBeforeInput", "beforeinput", null, nativeEvent, nativeEventTarget);
            dispatchQueue.push({
              event,
              listeners
            });
            event.data = chars;
          }
        }
        function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
          extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
        }
        var supportedInputTypes = {
          color: true,
          date: true,
          datetime: true,
          "datetime-local": true,
          email: true,
          month: true,
          number: true,
          password: true,
          range: true,
          search: true,
          tel: true,
          text: true,
          time: true,
          url: true,
          week: true
        };
        function isTextInputElement(elem) {
          var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
          if (nodeName === "input") {
            return !!supportedInputTypes[elem.type];
          }
          if (nodeName === "textarea") {
            return true;
          }
          return false;
        }
        function isEventSupported(eventNameSuffix) {
          if (!canUseDOM) {
            return false;
          }
          var eventName = "on" + eventNameSuffix;
          var isSupported = eventName in document;
          if (!isSupported) {
            var element = document.createElement("div");
            element.setAttribute(eventName, "return;");
            isSupported = typeof element[eventName] === "function";
          }
          return isSupported;
        }
        function registerEvents$1() {
          registerTwoPhaseEvent("onChange", ["change", "click", "focusin", "focusout", "input", "keydown", "keyup", "selectionchange"]);
        }
        function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
          enqueueStateRestore(target);
          var listeners = accumulateTwoPhaseListeners(inst, "onChange");
          if (listeners.length > 0) {
            var event = new SyntheticEvent("onChange", "change", null, nativeEvent, target);
            dispatchQueue.push({
              event,
              listeners
            });
          }
        }
        var activeElement = null;
        var activeElementInst = null;
        function shouldUseChangeEvent(elem) {
          var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
          return nodeName === "select" || nodeName === "input" && elem.type === "file";
        }
        function manualDispatchChangeEvent(nativeEvent) {
          var dispatchQueue = [];
          createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
          batchedUpdates(runEventInBatch, dispatchQueue);
        }
        function runEventInBatch(dispatchQueue) {
          processDispatchQueue(dispatchQueue, 0);
        }
        function getInstIfValueChanged(targetInst) {
          var targetNode = getNodeFromInstance(targetInst);
          if (updateValueIfChanged(targetNode)) {
            return targetInst;
          }
        }
        function getTargetInstForChangeEvent(domEventName, targetInst) {
          if (domEventName === "change") {
            return targetInst;
          }
        }
        var isInputEventSupported = false;
        if (canUseDOM) {
          isInputEventSupported = isEventSupported("input") && (!document.documentMode || document.documentMode > 9);
        }
        function startWatchingForValueChange(target, targetInst) {
          activeElement = target;
          activeElementInst = targetInst;
          activeElement.attachEvent("onpropertychange", handlePropertyChange);
        }
        function stopWatchingForValueChange() {
          if (!activeElement) {
            return;
          }
          activeElement.detachEvent("onpropertychange", handlePropertyChange);
          activeElement = null;
          activeElementInst = null;
        }
        function handlePropertyChange(nativeEvent) {
          if (nativeEvent.propertyName !== "value") {
            return;
          }
          if (getInstIfValueChanged(activeElementInst)) {
            manualDispatchChangeEvent(nativeEvent);
          }
        }
        function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
          if (domEventName === "focusin") {
            stopWatchingForValueChange();
            startWatchingForValueChange(target, targetInst);
          } else if (domEventName === "focusout") {
            stopWatchingForValueChange();
          }
        }
        function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
          if (domEventName === "selectionchange" || domEventName === "keyup" || domEventName === "keydown") {
            return getInstIfValueChanged(activeElementInst);
          }
        }
        function shouldUseClickEvent(elem) {
          var nodeName = elem.nodeName;
          return nodeName && nodeName.toLowerCase() === "input" && (elem.type === "checkbox" || elem.type === "radio");
        }
        function getTargetInstForClickEvent(domEventName, targetInst) {
          if (domEventName === "click") {
            return getInstIfValueChanged(targetInst);
          }
        }
        function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
          if (domEventName === "input" || domEventName === "change") {
            return getInstIfValueChanged(targetInst);
          }
        }
        function handleControlledInputBlur(node) {
          var state = node._wrapperState;
          if (!state || !state.controlled || node.type !== "number") {
            return;
          }
          {
            setDefaultValue(node, "number", node.value);
          }
        }
        function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
          var getTargetInstFunc, handleEventFunc;
          if (shouldUseChangeEvent(targetNode)) {
            getTargetInstFunc = getTargetInstForChangeEvent;
          } else if (isTextInputElement(targetNode)) {
            if (isInputEventSupported) {
              getTargetInstFunc = getTargetInstForInputOrChangeEvent;
            } else {
              getTargetInstFunc = getTargetInstForInputEventPolyfill;
              handleEventFunc = handleEventsForInputEventPolyfill;
            }
          } else if (shouldUseClickEvent(targetNode)) {
            getTargetInstFunc = getTargetInstForClickEvent;
          }
          if (getTargetInstFunc) {
            var inst = getTargetInstFunc(domEventName, targetInst);
            if (inst) {
              createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
              return;
            }
          }
          if (handleEventFunc) {
            handleEventFunc(domEventName, targetNode, targetInst);
          }
          if (domEventName === "focusout") {
            handleControlledInputBlur(targetNode);
          }
        }
        function registerEvents$2() {
          registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
          registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
          registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
          registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
        }
        function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          var isOverEvent = domEventName === "mouseover" || domEventName === "pointerover";
          var isOutEvent = domEventName === "mouseout" || domEventName === "pointerout";
          if (isOverEvent && !isReplayingEvent(nativeEvent)) {
            var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
            if (related) {
              if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
                return;
              }
            }
          }
          if (!isOutEvent && !isOverEvent) {
            return;
          }
          var win;
          if (nativeEventTarget.window === nativeEventTarget) {
            win = nativeEventTarget;
          } else {
            var doc = nativeEventTarget.ownerDocument;
            if (doc) {
              win = doc.defaultView || doc.parentWindow;
            } else {
              win = window;
            }
          }
          var from;
          var to;
          if (isOutEvent) {
            var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
            from = targetInst;
            to = _related ? getClosestInstanceFromNode(_related) : null;
            if (to !== null) {
              var nearestMounted = getNearestMountedFiber(to);
              if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
                to = null;
              }
            }
          } else {
            from = null;
            to = targetInst;
          }
          if (from === to) {
            return;
          }
          var SyntheticEventCtor = SyntheticMouseEvent;
          var leaveEventType = "onMouseLeave";
          var enterEventType = "onMouseEnter";
          var eventTypePrefix = "mouse";
          if (domEventName === "pointerout" || domEventName === "pointerover") {
            SyntheticEventCtor = SyntheticPointerEvent;
            leaveEventType = "onPointerLeave";
            enterEventType = "onPointerEnter";
            eventTypePrefix = "pointer";
          }
          var fromNode = from == null ? win : getNodeFromInstance(from);
          var toNode = to == null ? win : getNodeFromInstance(to);
          var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + "leave", from, nativeEvent, nativeEventTarget);
          leave.target = fromNode;
          leave.relatedTarget = toNode;
          var enter = null;
          var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
          if (nativeTargetInst === targetInst) {
            var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + "enter", to, nativeEvent, nativeEventTarget);
            enterEvent.target = toNode;
            enterEvent.relatedTarget = fromNode;
            enter = enterEvent;
          }
          accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
        }
        function is(x2, y2) {
          return x2 === y2 && (x2 !== 0 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
        }
        var objectIs = typeof Object.is === "function" ? Object.is : is;
        function shallowEqual(objA, objB) {
          if (objectIs(objA, objB)) {
            return true;
          }
          if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
            return false;
          }
          var keysA = Object.keys(objA);
          var keysB = Object.keys(objB);
          if (keysA.length !== keysB.length) {
            return false;
          }
          for (var i3 = 0; i3 < keysA.length; i3++) {
            var currentKey = keysA[i3];
            if (!hasOwnProperty3.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
              return false;
            }
          }
          return true;
        }
        function getLeafNode(node) {
          while (node && node.firstChild) {
            node = node.firstChild;
          }
          return node;
        }
        function getSiblingNode(node) {
          while (node) {
            if (node.nextSibling) {
              return node.nextSibling;
            }
            node = node.parentNode;
          }
        }
        function getNodeForCharacterOffset(root3, offset5) {
          var node = getLeafNode(root3);
          var nodeStart = 0;
          var nodeEnd = 0;
          while (node) {
            if (node.nodeType === TEXT_NODE) {
              nodeEnd = nodeStart + node.textContent.length;
              if (nodeStart <= offset5 && nodeEnd >= offset5) {
                return {
                  node,
                  offset: offset5 - nodeStart
                };
              }
              nodeStart = nodeEnd;
            }
            node = getLeafNode(getSiblingNode(node));
          }
        }
        function getOffsets(outerNode) {
          var ownerDocument = outerNode.ownerDocument;
          var win = ownerDocument && ownerDocument.defaultView || window;
          var selection = win.getSelection && win.getSelection();
          if (!selection || selection.rangeCount === 0) {
            return null;
          }
          var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset;
          try {
            anchorNode.nodeType;
            focusNode.nodeType;
          } catch (e3) {
            return null;
          }
          return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
        }
        function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
          var length = 0;
          var start = -1;
          var end = -1;
          var indexWithinAnchor = 0;
          var indexWithinFocus = 0;
          var node = outerNode;
          var parentNode = null;
          outer:
            while (true) {
              var next = null;
              while (true) {
                if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
                  start = length + anchorOffset;
                }
                if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
                  end = length + focusOffset;
                }
                if (node.nodeType === TEXT_NODE) {
                  length += node.nodeValue.length;
                }
                if ((next = node.firstChild) === null) {
                  break;
                }
                parentNode = node;
                node = next;
              }
              while (true) {
                if (node === outerNode) {
                  break outer;
                }
                if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
                  start = length;
                }
                if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
                  end = length;
                }
                if ((next = node.nextSibling) !== null) {
                  break;
                }
                node = parentNode;
                parentNode = node.parentNode;
              }
              node = next;
            }
          if (start === -1 || end === -1) {
            return null;
          }
          return {
            start,
            end
          };
        }
        function setOffsets(node, offsets) {
          var doc = node.ownerDocument || document;
          var win = doc && doc.defaultView || window;
          if (!win.getSelection) {
            return;
          }
          var selection = win.getSelection();
          var length = node.textContent.length;
          var start = Math.min(offsets.start, length);
          var end = offsets.end === void 0 ? start : Math.min(offsets.end, length);
          if (!selection.extend && start > end) {
            var temp = end;
            end = start;
            start = temp;
          }
          var startMarker = getNodeForCharacterOffset(node, start);
          var endMarker = getNodeForCharacterOffset(node, end);
          if (startMarker && endMarker) {
            if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
              return;
            }
            var range = doc.createRange();
            range.setStart(startMarker.node, startMarker.offset);
            selection.removeAllRanges();
            if (start > end) {
              selection.addRange(range);
              selection.extend(endMarker.node, endMarker.offset);
            } else {
              range.setEnd(endMarker.node, endMarker.offset);
              selection.addRange(range);
            }
          }
        }
        function isTextNode(node) {
          return node && node.nodeType === TEXT_NODE;
        }
        function containsNode(outerNode, innerNode) {
          if (!outerNode || !innerNode) {
            return false;
          } else if (outerNode === innerNode) {
            return true;
          } else if (isTextNode(outerNode)) {
            return false;
          } else if (isTextNode(innerNode)) {
            return containsNode(outerNode, innerNode.parentNode);
          } else if ("contains" in outerNode) {
            return outerNode.contains(innerNode);
          } else if (outerNode.compareDocumentPosition) {
            return !!(outerNode.compareDocumentPosition(innerNode) & 16);
          } else {
            return false;
          }
        }
        function isInDocument(node) {
          return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
        }
        function isSameOriginFrame(iframe) {
          try {
            return typeof iframe.contentWindow.location.href === "string";
          } catch (err) {
            return false;
          }
        }
        function getActiveElementDeep() {
          var win = window;
          var element = getActiveElement();
          while (element instanceof win.HTMLIFrameElement) {
            if (isSameOriginFrame(element)) {
              win = element.contentWindow;
            } else {
              return element;
            }
            element = getActiveElement(win.document);
          }
          return element;
        }
        function hasSelectionCapabilities(elem) {
          var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
          return nodeName && (nodeName === "input" && (elem.type === "text" || elem.type === "search" || elem.type === "tel" || elem.type === "url" || elem.type === "password") || nodeName === "textarea" || elem.contentEditable === "true");
        }
        function getSelectionInformation() {
          var focusedElem = getActiveElementDeep();
          return {
            focusedElem,
            selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
          };
        }
        function restoreSelection(priorSelectionInformation) {
          var curFocusedElem = getActiveElementDeep();
          var priorFocusedElem = priorSelectionInformation.focusedElem;
          var priorSelectionRange = priorSelectionInformation.selectionRange;
          if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
            if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
              setSelection(priorFocusedElem, priorSelectionRange);
            }
            var ancestors = [];
            var ancestor = priorFocusedElem;
            while (ancestor = ancestor.parentNode) {
              if (ancestor.nodeType === ELEMENT_NODE) {
                ancestors.push({
                  element: ancestor,
                  left: ancestor.scrollLeft,
                  top: ancestor.scrollTop
                });
              }
            }
            if (typeof priorFocusedElem.focus === "function") {
              priorFocusedElem.focus();
            }
            for (var i3 = 0; i3 < ancestors.length; i3++) {
              var info = ancestors[i3];
              info.element.scrollLeft = info.left;
              info.element.scrollTop = info.top;
            }
          }
        }
        function getSelection(input) {
          var selection;
          if ("selectionStart" in input) {
            selection = {
              start: input.selectionStart,
              end: input.selectionEnd
            };
          } else {
            selection = getOffsets(input);
          }
          return selection || {
            start: 0,
            end: 0
          };
        }
        function setSelection(input, offsets) {
          var start = offsets.start;
          var end = offsets.end;
          if (end === void 0) {
            end = start;
          }
          if ("selectionStart" in input) {
            input.selectionStart = start;
            input.selectionEnd = Math.min(end, input.value.length);
          } else {
            setOffsets(input, offsets);
          }
        }
        var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && document.documentMode <= 11;
        function registerEvents$3() {
          registerTwoPhaseEvent("onSelect", ["focusout", "contextmenu", "dragend", "focusin", "keydown", "keyup", "mousedown", "mouseup", "selectionchange"]);
        }
        var activeElement$1 = null;
        var activeElementInst$1 = null;
        var lastSelection = null;
        var mouseDown = false;
        function getSelection$1(node) {
          if ("selectionStart" in node && hasSelectionCapabilities(node)) {
            return {
              start: node.selectionStart,
              end: node.selectionEnd
            };
          } else {
            var win = node.ownerDocument && node.ownerDocument.defaultView || window;
            var selection = win.getSelection();
            return {
              anchorNode: selection.anchorNode,
              anchorOffset: selection.anchorOffset,
              focusNode: selection.focusNode,
              focusOffset: selection.focusOffset
            };
          }
        }
        function getEventTargetDocument(eventTarget) {
          return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
        }
        function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
          var doc = getEventTargetDocument(nativeEventTarget);
          if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
            return;
          }
          var currentSelection = getSelection$1(activeElement$1);
          if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
            lastSelection = currentSelection;
            var listeners = accumulateTwoPhaseListeners(activeElementInst$1, "onSelect");
            if (listeners.length > 0) {
              var event = new SyntheticEvent("onSelect", "select", null, nativeEvent, nativeEventTarget);
              dispatchQueue.push({
                event,
                listeners
              });
              event.target = activeElement$1;
            }
          }
        }
        function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
          switch (domEventName) {
            case "focusin":
              if (isTextInputElement(targetNode) || targetNode.contentEditable === "true") {
                activeElement$1 = targetNode;
                activeElementInst$1 = targetInst;
                lastSelection = null;
              }
              break;
            case "focusout":
              activeElement$1 = null;
              activeElementInst$1 = null;
              lastSelection = null;
              break;
            case "mousedown":
              mouseDown = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              mouseDown = false;
              constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
              break;
            case "selectionchange":
              if (skipSelectionChangeEvent) {
                break;
              }
            case "keydown":
            case "keyup":
              constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
          }
        }
        function makePrefixMap(styleProp, eventName) {
          var prefixes2 = {};
          prefixes2[styleProp.toLowerCase()] = eventName.toLowerCase();
          prefixes2["Webkit" + styleProp] = "webkit" + eventName;
          prefixes2["Moz" + styleProp] = "moz" + eventName;
          return prefixes2;
        }
        var vendorPrefixes = {
          animationend: makePrefixMap("Animation", "AnimationEnd"),
          animationiteration: makePrefixMap("Animation", "AnimationIteration"),
          animationstart: makePrefixMap("Animation", "AnimationStart"),
          transitionend: makePrefixMap("Transition", "TransitionEnd")
        };
        var prefixedEventNames = {};
        var style = {};
        if (canUseDOM) {
          style = document.createElement("div").style;
          if (!("AnimationEvent" in window)) {
            delete vendorPrefixes.animationend.animation;
            delete vendorPrefixes.animationiteration.animation;
            delete vendorPrefixes.animationstart.animation;
          }
          if (!("TransitionEvent" in window)) {
            delete vendorPrefixes.transitionend.transition;
          }
        }
        function getVendorPrefixedEventName(eventName) {
          if (prefixedEventNames[eventName]) {
            return prefixedEventNames[eventName];
          } else if (!vendorPrefixes[eventName]) {
            return eventName;
          }
          var prefixMap = vendorPrefixes[eventName];
          for (var styleProp in prefixMap) {
            if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
              return prefixedEventNames[eventName] = prefixMap[styleProp];
            }
          }
          return eventName;
        }
        var ANIMATION_END = getVendorPrefixedEventName("animationend");
        var ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration");
        var ANIMATION_START = getVendorPrefixedEventName("animationstart");
        var TRANSITION_END = getVendorPrefixedEventName("transitionend");
        var topLevelEventsToReactNames = /* @__PURE__ */ new Map();
        var simpleEventPluginEvents = ["abort", "auxClick", "cancel", "canPlay", "canPlayThrough", "click", "close", "contextMenu", "copy", "cut", "drag", "dragEnd", "dragEnter", "dragExit", "dragLeave", "dragOver", "dragStart", "drop", "durationChange", "emptied", "encrypted", "ended", "error", "gotPointerCapture", "input", "invalid", "keyDown", "keyPress", "keyUp", "load", "loadedData", "loadedMetadata", "loadStart", "lostPointerCapture", "mouseDown", "mouseMove", "mouseOut", "mouseOver", "mouseUp", "paste", "pause", "play", "playing", "pointerCancel", "pointerDown", "pointerMove", "pointerOut", "pointerOver", "pointerUp", "progress", "rateChange", "reset", "resize", "seeked", "seeking", "stalled", "submit", "suspend", "timeUpdate", "touchCancel", "touchEnd", "touchStart", "volumeChange", "scroll", "toggle", "touchMove", "waiting", "wheel"];
        function registerSimpleEvent(domEventName, reactName) {
          topLevelEventsToReactNames.set(domEventName, reactName);
          registerTwoPhaseEvent(reactName, [domEventName]);
        }
        function registerSimpleEvents() {
          for (var i3 = 0; i3 < simpleEventPluginEvents.length; i3++) {
            var eventName = simpleEventPluginEvents[i3];
            var domEventName = eventName.toLowerCase();
            var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
            registerSimpleEvent(domEventName, "on" + capitalizedEvent);
          }
          registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
          registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
          registerSimpleEvent(ANIMATION_START, "onAnimationStart");
          registerSimpleEvent("dblclick", "onDoubleClick");
          registerSimpleEvent("focusin", "onFocus");
          registerSimpleEvent("focusout", "onBlur");
          registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
        }
        function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          var reactName = topLevelEventsToReactNames.get(domEventName);
          if (reactName === void 0) {
            return;
          }
          var SyntheticEventCtor = SyntheticEvent;
          var reactEventType = domEventName;
          switch (domEventName) {
            case "keypress":
              if (getEventCharCode(nativeEvent) === 0) {
                return;
              }
            case "keydown":
            case "keyup":
              SyntheticEventCtor = SyntheticKeyboardEvent;
              break;
            case "focusin":
              reactEventType = "focus";
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "focusout":
              reactEventType = "blur";
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "beforeblur":
            case "afterblur":
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "click":
              if (nativeEvent.button === 2) {
                return;
              }
            case "auxclick":
            case "dblclick":
            case "mousedown":
            case "mousemove":
            case "mouseup":
            case "mouseout":
            case "mouseover":
            case "contextmenu":
              SyntheticEventCtor = SyntheticMouseEvent;
              break;
            case "drag":
            case "dragend":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "dragstart":
            case "drop":
              SyntheticEventCtor = SyntheticDragEvent;
              break;
            case "touchcancel":
            case "touchend":
            case "touchmove":
            case "touchstart":
              SyntheticEventCtor = SyntheticTouchEvent;
              break;
            case ANIMATION_END:
            case ANIMATION_ITERATION:
            case ANIMATION_START:
              SyntheticEventCtor = SyntheticAnimationEvent;
              break;
            case TRANSITION_END:
              SyntheticEventCtor = SyntheticTransitionEvent;
              break;
            case "scroll":
              SyntheticEventCtor = SyntheticUIEvent;
              break;
            case "wheel":
              SyntheticEventCtor = SyntheticWheelEvent;
              break;
            case "copy":
            case "cut":
            case "paste":
              SyntheticEventCtor = SyntheticClipboardEvent;
              break;
            case "gotpointercapture":
            case "lostpointercapture":
            case "pointercancel":
            case "pointerdown":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "pointerup":
              SyntheticEventCtor = SyntheticPointerEvent;
              break;
          }
          var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
          {
            var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
            // nonDelegatedEvents list in DOMPluginEventSystem.
            // Then we can remove this special list.
            // This is a breaking change that can wait until React 18.
            domEventName === "scroll";
            var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);
            if (_listeners.length > 0) {
              var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);
              dispatchQueue.push({
                event: _event,
                listeners: _listeners
              });
            }
          }
        }
        registerSimpleEvents();
        registerEvents$2();
        registerEvents$1();
        registerEvents$3();
        registerEvents();
        function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
          extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
          var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0;
          if (shouldProcessPolyfillPlugins) {
            extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
            extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
            extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
            extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
          }
        }
        var mediaEventTypes = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "encrypted", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "resize", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"];
        var nonDelegatedEvents = new Set(["cancel", "close", "invalid", "load", "scroll", "toggle"].concat(mediaEventTypes));
        function executeDispatch(event, listener, currentTarget) {
          var type = event.type || "unknown-event";
          event.currentTarget = currentTarget;
          invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event);
          event.currentTarget = null;
        }
        function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
          var previousInstance;
          if (inCapturePhase) {
            for (var i3 = dispatchListeners.length - 1; i3 >= 0; i3--) {
              var _dispatchListeners$i = dispatchListeners[i3], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener;
              if (instance !== previousInstance && event.isPropagationStopped()) {
                return;
              }
              executeDispatch(event, listener, currentTarget);
              previousInstance = instance;
            }
          } else {
            for (var _i = 0; _i < dispatchListeners.length; _i++) {
              var _dispatchListeners$_i = dispatchListeners[_i], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener;
              if (_instance !== previousInstance && event.isPropagationStopped()) {
                return;
              }
              executeDispatch(event, _listener, _currentTarget);
              previousInstance = _instance;
            }
          }
        }
        function processDispatchQueue(dispatchQueue, eventSystemFlags) {
          var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
          for (var i3 = 0; i3 < dispatchQueue.length; i3++) {
            var _dispatchQueue$i = dispatchQueue[i3], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners;
            processDispatchQueueItemsInOrder(event, listeners, inCapturePhase);
          }
          rethrowCaughtError();
        }
        function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
          var nativeEventTarget = getEventTarget(nativeEvent);
          var dispatchQueue = [];
          extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
          processDispatchQueue(dispatchQueue, eventSystemFlags);
        }
        function listenToNonDelegatedEvent(domEventName, targetElement) {
          {
            if (!nonDelegatedEvents.has(domEventName)) {
              error('Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.', domEventName);
            }
          }
          var isCapturePhaseListener = false;
          var listenerSet = getEventListenerSet(targetElement);
          var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);
          if (!listenerSet.has(listenerSetKey)) {
            addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
            listenerSet.add(listenerSetKey);
          }
        }
        function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
          {
            if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
              error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.', domEventName);
            }
          }
          var eventSystemFlags = 0;
          if (isCapturePhaseListener) {
            eventSystemFlags |= IS_CAPTURE_PHASE;
          }
          addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
        }
        var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
        function listenToAllSupportedEvents(rootContainerElement) {
          if (!rootContainerElement[listeningMarker]) {
            rootContainerElement[listeningMarker] = true;
            allNativeEvents.forEach(function(domEventName) {
              if (domEventName !== "selectionchange") {
                if (!nonDelegatedEvents.has(domEventName)) {
                  listenToNativeEvent(domEventName, false, rootContainerElement);
                }
                listenToNativeEvent(domEventName, true, rootContainerElement);
              }
            });
            var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
            if (ownerDocument !== null) {
              if (!ownerDocument[listeningMarker]) {
                ownerDocument[listeningMarker] = true;
                listenToNativeEvent("selectionchange", false, ownerDocument);
              }
            }
          }
        }
        function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
          var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags);
          var isPassiveListener = void 0;
          if (passiveBrowserEventsSupported) {
            if (domEventName === "touchstart" || domEventName === "touchmove" || domEventName === "wheel") {
              isPassiveListener = true;
            }
          }
          targetContainer = targetContainer;
          var unsubscribeListener;
          if (isCapturePhaseListener) {
            if (isPassiveListener !== void 0) {
              unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
            } else {
              unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
            }
          } else {
            if (isPassiveListener !== void 0) {
              unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
            } else {
              unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
            }
          }
        }
        function isMatchingRootContainer(grandContainer, targetContainer) {
          return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
        }
        function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
          var ancestorInst = targetInst;
          if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
            var targetContainerNode = targetContainer;
            if (targetInst !== null) {
              var node = targetInst;
              mainLoop:
                while (true) {
                  if (node === null) {
                    return;
                  }
                  var nodeTag = node.tag;
                  if (nodeTag === HostRoot || nodeTag === HostPortal) {
                    var container = node.stateNode.containerInfo;
                    if (isMatchingRootContainer(container, targetContainerNode)) {
                      break;
                    }
                    if (nodeTag === HostPortal) {
                      var grandNode = node.return;
                      while (grandNode !== null) {
                        var grandTag = grandNode.tag;
                        if (grandTag === HostRoot || grandTag === HostPortal) {
                          var grandContainer = grandNode.stateNode.containerInfo;
                          if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
                            return;
                          }
                        }
                        grandNode = grandNode.return;
                      }
                    }
                    while (container !== null) {
                      var parentNode = getClosestInstanceFromNode(container);
                      if (parentNode === null) {
                        return;
                      }
                      var parentTag = parentNode.tag;
                      if (parentTag === HostComponent || parentTag === HostText) {
                        node = ancestorInst = parentNode;
                        continue mainLoop;
                      }
                      container = container.parentNode;
                    }
                  }
                  node = node.return;
                }
            }
          }
          batchedUpdates(function() {
            return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
          });
        }
        function createDispatchListener(instance, listener, currentTarget) {
          return {
            instance,
            listener,
            currentTarget
          };
        }
        function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
          var captureName = reactName !== null ? reactName + "Capture" : null;
          var reactEventName = inCapturePhase ? captureName : reactName;
          var listeners = [];
          var instance = targetFiber;
          var lastHostComponent = null;
          while (instance !== null) {
            var _instance2 = instance, stateNode = _instance2.stateNode, tag = _instance2.tag;
            if (tag === HostComponent && stateNode !== null) {
              lastHostComponent = stateNode;
              if (reactEventName !== null) {
                var listener = getListener(instance, reactEventName);
                if (listener != null) {
                  listeners.push(createDispatchListener(instance, listener, lastHostComponent));
                }
              }
            }
            if (accumulateTargetOnly) {
              break;
            }
            instance = instance.return;
          }
          return listeners;
        }
        function accumulateTwoPhaseListeners(targetFiber, reactName) {
          var captureName = reactName + "Capture";
          var listeners = [];
          var instance = targetFiber;
          while (instance !== null) {
            var _instance3 = instance, stateNode = _instance3.stateNode, tag = _instance3.tag;
            if (tag === HostComponent && stateNode !== null) {
              var currentTarget = stateNode;
              var captureListener = getListener(instance, captureName);
              if (captureListener != null) {
                listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
              }
              var bubbleListener = getListener(instance, reactName);
              if (bubbleListener != null) {
                listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
              }
            }
            instance = instance.return;
          }
          return listeners;
        }
        function getParent(inst) {
          if (inst === null) {
            return null;
          }
          do {
            inst = inst.return;
          } while (inst && inst.tag !== HostComponent);
          if (inst) {
            return inst;
          }
          return null;
        }
        function getLowestCommonAncestor(instA, instB) {
          var nodeA = instA;
          var nodeB = instB;
          var depthA = 0;
          for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
            depthA++;
          }
          var depthB = 0;
          for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
            depthB++;
          }
          while (depthA - depthB > 0) {
            nodeA = getParent(nodeA);
            depthA--;
          }
          while (depthB - depthA > 0) {
            nodeB = getParent(nodeB);
            depthB--;
          }
          var depth = depthA;
          while (depth--) {
            if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
              return nodeA;
            }
            nodeA = getParent(nodeA);
            nodeB = getParent(nodeB);
          }
          return null;
        }
        function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
          var registrationName = event._reactName;
          var listeners = [];
          var instance = target;
          while (instance !== null) {
            if (instance === common) {
              break;
            }
            var _instance4 = instance, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag;
            if (alternate !== null && alternate === common) {
              break;
            }
            if (tag === HostComponent && stateNode !== null) {
              var currentTarget = stateNode;
              if (inCapturePhase) {
                var captureListener = getListener(instance, registrationName);
                if (captureListener != null) {
                  listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
                }
              } else if (!inCapturePhase) {
                var bubbleListener = getListener(instance, registrationName);
                if (bubbleListener != null) {
                  listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
                }
              }
            }
            instance = instance.return;
          }
          if (listeners.length !== 0) {
            dispatchQueue.push({
              event,
              listeners
            });
          }
        }
        function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
          var common = from && to ? getLowestCommonAncestor(from, to) : null;
          if (from !== null) {
            accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
          }
          if (to !== null && enterEvent !== null) {
            accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
          }
        }
        function getListenerSetKey(domEventName, capture) {
          return domEventName + "__" + (capture ? "capture" : "bubble");
        }
        var didWarnInvalidHydration = false;
        var DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML";
        var SUPPRESS_CONTENT_EDITABLE_WARNING = "suppressContentEditableWarning";
        var SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning";
        var AUTOFOCUS = "autoFocus";
        var CHILDREN = "children";
        var STYLE = "style";
        var HTML$1 = "__html";
        var warnedUnknownTags;
        var validatePropertiesInDevelopment;
        var warnForPropDifference;
        var warnForExtraAttributes;
        var warnForInvalidEventListener;
        var canDiffStyleForHydrationWarning;
        var normalizeHTML;
        {
          warnedUnknownTags = {
            // There are working polyfills for <dialog>. Let people use it.
            dialog: true,
            // Electron ships a custom <webview> tag to display external web content in
            // an isolated frame and process.
            // This tag is not present in non Electron environments such as JSDom which
            // is often used for testing purposes.
            // @see https://electronjs.org/docs/api/webview-tag
            webview: true
          };
          validatePropertiesInDevelopment = function(type, props) {
            validateProperties(type, props);
            validateProperties$1(type, props);
            validateProperties$2(type, props, {
              registrationNameDependencies,
              possibleRegistrationNames
            });
          };
          canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
          warnForPropDifference = function(propName, serverValue, clientValue) {
            if (didWarnInvalidHydration) {
              return;
            }
            var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
            var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
            if (normalizedServerValue === normalizedClientValue) {
              return;
            }
            didWarnInvalidHydration = true;
            error("Prop `%s` did not match. Server: %s Client: %s", propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
          };
          warnForExtraAttributes = function(attributeNames) {
            if (didWarnInvalidHydration) {
              return;
            }
            didWarnInvalidHydration = true;
            var names = [];
            attributeNames.forEach(function(name) {
              names.push(name);
            });
            error("Extra attributes from the server: %s", names);
          };
          warnForInvalidEventListener = function(registrationName, listener) {
            if (listener === false) {
              error("Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.", registrationName, registrationName, registrationName);
            } else {
              error("Expected `%s` listener to be a function, instead got a value of `%s` type.", registrationName, typeof listener);
            }
          };
          normalizeHTML = function(parent, html) {
            var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
            testElement.innerHTML = html;
            return testElement.innerHTML;
          };
        }
        var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
        var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
        function normalizeMarkupForTextOrAttribute(markup) {
          {
            checkHtmlStringCoercion(markup);
          }
          var markupString = typeof markup === "string" ? markup : "" + markup;
          return markupString.replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
        }
        function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
          var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
          var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
          if (normalizedServerText === normalizedClientText) {
            return;
          }
          if (shouldWarnDev) {
            {
              if (!didWarnInvalidHydration) {
                didWarnInvalidHydration = true;
                error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
              }
            }
          }
          if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
            throw new Error("Text content does not match server-rendered HTML.");
          }
        }
        function getOwnerDocumentFromRootContainer(rootContainerElement) {
          return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
        }
        function noop2() {
        }
        function trapClickOnNonInteractiveElement(node) {
          node.onclick = noop2;
        }
        function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
          for (var propKey in nextProps) {
            if (!nextProps.hasOwnProperty(propKey)) {
              continue;
            }
            var nextProp = nextProps[propKey];
            if (propKey === STYLE) {
              {
                if (nextProp) {
                  Object.freeze(nextProp);
                }
              }
              setValueForStyles(domElement, nextProp);
            } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
              var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
              if (nextHtml != null) {
                setInnerHTML(domElement, nextHtml);
              }
            } else if (propKey === CHILDREN) {
              if (typeof nextProp === "string") {
                var canSetTextContent = tag !== "textarea" || nextProp !== "";
                if (canSetTextContent) {
                  setTextContent(domElement, nextProp);
                }
              } else if (typeof nextProp === "number") {
                setTextContent(domElement, "" + nextProp);
              }
            } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
              ;
            else if (propKey === AUTOFOCUS)
              ;
            else if (registrationNameDependencies.hasOwnProperty(propKey)) {
              if (nextProp != null) {
                if (typeof nextProp !== "function") {
                  warnForInvalidEventListener(propKey, nextProp);
                }
                if (propKey === "onScroll") {
                  listenToNonDelegatedEvent("scroll", domElement);
                }
              }
            } else if (nextProp != null) {
              setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
            }
          }
        }
        function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
          for (var i3 = 0; i3 < updatePayload.length; i3 += 2) {
            var propKey = updatePayload[i3];
            var propValue = updatePayload[i3 + 1];
            if (propKey === STYLE) {
              setValueForStyles(domElement, propValue);
            } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
              setInnerHTML(domElement, propValue);
            } else if (propKey === CHILDREN) {
              setTextContent(domElement, propValue);
            } else {
              setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
            }
          }
        }
        function createElement31(type, props, rootContainerElement, parentNamespace) {
          var isCustomComponentTag;
          var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
          var domElement;
          var namespaceURI = parentNamespace;
          if (namespaceURI === HTML_NAMESPACE) {
            namespaceURI = getIntrinsicNamespace(type);
          }
          if (namespaceURI === HTML_NAMESPACE) {
            {
              isCustomComponentTag = isCustomComponent(type, props);
              if (!isCustomComponentTag && type !== type.toLowerCase()) {
                error("<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.", type);
              }
            }
            if (type === "script") {
              var div = ownerDocument.createElement("div");
              div.innerHTML = "<script><\/script>";
              var firstChild = div.firstChild;
              domElement = div.removeChild(firstChild);
            } else if (typeof props.is === "string") {
              domElement = ownerDocument.createElement(type, {
                is: props.is
              });
            } else {
              domElement = ownerDocument.createElement(type);
              if (type === "select") {
                var node = domElement;
                if (props.multiple) {
                  node.multiple = true;
                } else if (props.size) {
                  node.size = props.size;
                }
              }
            }
          } else {
            domElement = ownerDocument.createElementNS(namespaceURI, type);
          }
          {
            if (namespaceURI === HTML_NAMESPACE) {
              if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === "[object HTMLUnknownElement]" && !hasOwnProperty3.call(warnedUnknownTags, type)) {
                warnedUnknownTags[type] = true;
                error("The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.", type);
              }
            }
          }
          return domElement;
        }
        function createTextNode(text, rootContainerElement) {
          return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
        }
        function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
          var isCustomComponentTag = isCustomComponent(tag, rawProps);
          {
            validatePropertiesInDevelopment(tag, rawProps);
          }
          var props;
          switch (tag) {
            case "dialog":
              listenToNonDelegatedEvent("cancel", domElement);
              listenToNonDelegatedEvent("close", domElement);
              props = rawProps;
              break;
            case "iframe":
            case "object":
            case "embed":
              listenToNonDelegatedEvent("load", domElement);
              props = rawProps;
              break;
            case "video":
            case "audio":
              for (var i3 = 0; i3 < mediaEventTypes.length; i3++) {
                listenToNonDelegatedEvent(mediaEventTypes[i3], domElement);
              }
              props = rawProps;
              break;
            case "source":
              listenToNonDelegatedEvent("error", domElement);
              props = rawProps;
              break;
            case "img":
            case "image":
            case "link":
              listenToNonDelegatedEvent("error", domElement);
              listenToNonDelegatedEvent("load", domElement);
              props = rawProps;
              break;
            case "details":
              listenToNonDelegatedEvent("toggle", domElement);
              props = rawProps;
              break;
            case "input":
              initWrapperState(domElement, rawProps);
              props = getHostProps(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
            case "option":
              validateProps(domElement, rawProps);
              props = rawProps;
              break;
            case "select":
              initWrapperState$1(domElement, rawProps);
              props = getHostProps$1(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
            case "textarea":
              initWrapperState$2(domElement, rawProps);
              props = getHostProps$2(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
            default:
              props = rawProps;
          }
          assertValidProps(tag, props);
          setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
          switch (tag) {
            case "input":
              track(domElement);
              postMountWrapper(domElement, rawProps, false);
              break;
            case "textarea":
              track(domElement);
              postMountWrapper$3(domElement);
              break;
            case "option":
              postMountWrapper$1(domElement, rawProps);
              break;
            case "select":
              postMountWrapper$2(domElement, rawProps);
              break;
            default:
              if (typeof props.onClick === "function") {
                trapClickOnNonInteractiveElement(domElement);
              }
              break;
          }
        }
        function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
          {
            validatePropertiesInDevelopment(tag, nextRawProps);
          }
          var updatePayload = null;
          var lastProps;
          var nextProps;
          switch (tag) {
            case "input":
              lastProps = getHostProps(domElement, lastRawProps);
              nextProps = getHostProps(domElement, nextRawProps);
              updatePayload = [];
              break;
            case "select":
              lastProps = getHostProps$1(domElement, lastRawProps);
              nextProps = getHostProps$1(domElement, nextRawProps);
              updatePayload = [];
              break;
            case "textarea":
              lastProps = getHostProps$2(domElement, lastRawProps);
              nextProps = getHostProps$2(domElement, nextRawProps);
              updatePayload = [];
              break;
            default:
              lastProps = lastRawProps;
              nextProps = nextRawProps;
              if (typeof lastProps.onClick !== "function" && typeof nextProps.onClick === "function") {
                trapClickOnNonInteractiveElement(domElement);
              }
              break;
          }
          assertValidProps(tag, nextProps);
          var propKey;
          var styleName;
          var styleUpdates = null;
          for (propKey in lastProps) {
            if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
              continue;
            }
            if (propKey === STYLE) {
              var lastStyle = lastProps[propKey];
              for (styleName in lastStyle) {
                if (lastStyle.hasOwnProperty(styleName)) {
                  if (!styleUpdates) {
                    styleUpdates = {};
                  }
                  styleUpdates[styleName] = "";
                }
              }
            } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN)
              ;
            else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
              ;
            else if (propKey === AUTOFOCUS)
              ;
            else if (registrationNameDependencies.hasOwnProperty(propKey)) {
              if (!updatePayload) {
                updatePayload = [];
              }
            } else {
              (updatePayload = updatePayload || []).push(propKey, null);
            }
          }
          for (propKey in nextProps) {
            var nextProp = nextProps[propKey];
            var lastProp = lastProps != null ? lastProps[propKey] : void 0;
            if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
              continue;
            }
            if (propKey === STYLE) {
              {
                if (nextProp) {
                  Object.freeze(nextProp);
                }
              }
              if (lastProp) {
                for (styleName in lastProp) {
                  if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
                    if (!styleUpdates) {
                      styleUpdates = {};
                    }
                    styleUpdates[styleName] = "";
                  }
                }
                for (styleName in nextProp) {
                  if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
                    if (!styleUpdates) {
                      styleUpdates = {};
                    }
                    styleUpdates[styleName] = nextProp[styleName];
                  }
                }
              } else {
                if (!styleUpdates) {
                  if (!updatePayload) {
                    updatePayload = [];
                  }
                  updatePayload.push(propKey, styleUpdates);
                }
                styleUpdates = nextProp;
              }
            } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
              var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
              var lastHtml = lastProp ? lastProp[HTML$1] : void 0;
              if (nextHtml != null) {
                if (lastHtml !== nextHtml) {
                  (updatePayload = updatePayload || []).push(propKey, nextHtml);
                }
              }
            } else if (propKey === CHILDREN) {
              if (typeof nextProp === "string" || typeof nextProp === "number") {
                (updatePayload = updatePayload || []).push(propKey, "" + nextProp);
              }
            } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
              ;
            else if (registrationNameDependencies.hasOwnProperty(propKey)) {
              if (nextProp != null) {
                if (typeof nextProp !== "function") {
                  warnForInvalidEventListener(propKey, nextProp);
                }
                if (propKey === "onScroll") {
                  listenToNonDelegatedEvent("scroll", domElement);
                }
              }
              if (!updatePayload && lastProp !== nextProp) {
                updatePayload = [];
              }
            } else {
              (updatePayload = updatePayload || []).push(propKey, nextProp);
            }
          }
          if (styleUpdates) {
            {
              validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
            }
            (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
          }
          return updatePayload;
        }
        function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
          if (tag === "input" && nextRawProps.type === "radio" && nextRawProps.name != null) {
            updateChecked(domElement, nextRawProps);
          }
          var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
          var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
          updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
          switch (tag) {
            case "input":
              updateWrapper(domElement, nextRawProps);
              break;
            case "textarea":
              updateWrapper$1(domElement, nextRawProps);
              break;
            case "select":
              postUpdateWrapper(domElement, nextRawProps);
              break;
          }
        }
        function getPossibleStandardName(propName) {
          {
            var lowerCasedName = propName.toLowerCase();
            if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
              return null;
            }
            return possibleStandardNames[lowerCasedName] || null;
          }
        }
        function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
          var isCustomComponentTag;
          var extraAttributeNames;
          {
            isCustomComponentTag = isCustomComponent(tag, rawProps);
            validatePropertiesInDevelopment(tag, rawProps);
          }
          switch (tag) {
            case "dialog":
              listenToNonDelegatedEvent("cancel", domElement);
              listenToNonDelegatedEvent("close", domElement);
              break;
            case "iframe":
            case "object":
            case "embed":
              listenToNonDelegatedEvent("load", domElement);
              break;
            case "video":
            case "audio":
              for (var i3 = 0; i3 < mediaEventTypes.length; i3++) {
                listenToNonDelegatedEvent(mediaEventTypes[i3], domElement);
              }
              break;
            case "source":
              listenToNonDelegatedEvent("error", domElement);
              break;
            case "img":
            case "image":
            case "link":
              listenToNonDelegatedEvent("error", domElement);
              listenToNonDelegatedEvent("load", domElement);
              break;
            case "details":
              listenToNonDelegatedEvent("toggle", domElement);
              break;
            case "input":
              initWrapperState(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
            case "option":
              validateProps(domElement, rawProps);
              break;
            case "select":
              initWrapperState$1(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
            case "textarea":
              initWrapperState$2(domElement, rawProps);
              listenToNonDelegatedEvent("invalid", domElement);
              break;
          }
          assertValidProps(tag, rawProps);
          {
            extraAttributeNames = /* @__PURE__ */ new Set();
            var attributes = domElement.attributes;
            for (var _i = 0; _i < attributes.length; _i++) {
              var name = attributes[_i].name.toLowerCase();
              switch (name) {
                case "value":
                  break;
                case "checked":
                  break;
                case "selected":
                  break;
                default:
                  extraAttributeNames.add(attributes[_i].name);
              }
            }
          }
          var updatePayload = null;
          for (var propKey in rawProps) {
            if (!rawProps.hasOwnProperty(propKey)) {
              continue;
            }
            var nextProp = rawProps[propKey];
            if (propKey === CHILDREN) {
              if (typeof nextProp === "string") {
                if (domElement.textContent !== nextProp) {
                  if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
                    checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
                  }
                  updatePayload = [CHILDREN, nextProp];
                }
              } else if (typeof nextProp === "number") {
                if (domElement.textContent !== "" + nextProp) {
                  if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
                    checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
                  }
                  updatePayload = [CHILDREN, "" + nextProp];
                }
              }
            } else if (registrationNameDependencies.hasOwnProperty(propKey)) {
              if (nextProp != null) {
                if (typeof nextProp !== "function") {
                  warnForInvalidEventListener(propKey, nextProp);
                }
                if (propKey === "onScroll") {
                  listenToNonDelegatedEvent("scroll", domElement);
                }
              }
            } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
            typeof isCustomComponentTag === "boolean") {
              var serverValue = void 0;
              var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey);
              if (rawProps[SUPPRESS_HYDRATION_WARNING] === true)
                ;
              else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
              // TODO: Only ignore them on controlled tags.
              propKey === "value" || propKey === "checked" || propKey === "selected")
                ;
              else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
                var serverHTML = domElement.innerHTML;
                var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
                if (nextHtml != null) {
                  var expectedHTML = normalizeHTML(domElement, nextHtml);
                  if (expectedHTML !== serverHTML) {
                    warnForPropDifference(propKey, serverHTML, expectedHTML);
                  }
                }
              } else if (propKey === STYLE) {
                extraAttributeNames.delete(propKey);
                if (canDiffStyleForHydrationWarning) {
                  var expectedStyle = createDangerousStringForStyles(nextProp);
                  serverValue = domElement.getAttribute("style");
                  if (expectedStyle !== serverValue) {
                    warnForPropDifference(propKey, serverValue, expectedStyle);
                  }
                }
              } else if (isCustomComponentTag && !enableCustomElementPropertySupport) {
                extraAttributeNames.delete(propKey.toLowerCase());
                serverValue = getValueForAttribute(domElement, propKey, nextProp);
                if (nextProp !== serverValue) {
                  warnForPropDifference(propKey, serverValue, nextProp);
                }
              } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
                var isMismatchDueToBadCasing = false;
                if (propertyInfo !== null) {
                  extraAttributeNames.delete(propertyInfo.attributeName);
                  serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
                } else {
                  var ownNamespace = parentNamespace;
                  if (ownNamespace === HTML_NAMESPACE) {
                    ownNamespace = getIntrinsicNamespace(tag);
                  }
                  if (ownNamespace === HTML_NAMESPACE) {
                    extraAttributeNames.delete(propKey.toLowerCase());
                  } else {
                    var standardName = getPossibleStandardName(propKey);
                    if (standardName !== null && standardName !== propKey) {
                      isMismatchDueToBadCasing = true;
                      extraAttributeNames.delete(standardName);
                    }
                    extraAttributeNames.delete(propKey);
                  }
                  serverValue = getValueForAttribute(domElement, propKey, nextProp);
                }
                var dontWarnCustomElement = enableCustomElementPropertySupport;
                if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
                  warnForPropDifference(propKey, serverValue, nextProp);
                }
              }
            }
          }
          {
            if (shouldWarnDev) {
              if (
                // $FlowFixMe - Should be inferred as not undefined.
                extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true
              ) {
                warnForExtraAttributes(extraAttributeNames);
              }
            }
          }
          switch (tag) {
            case "input":
              track(domElement);
              postMountWrapper(domElement, rawProps, true);
              break;
            case "textarea":
              track(domElement);
              postMountWrapper$3(domElement);
              break;
            case "select":
            case "option":
              break;
            default:
              if (typeof rawProps.onClick === "function") {
                trapClickOnNonInteractiveElement(domElement);
              }
              break;
          }
          return updatePayload;
        }
        function diffHydratedText(textNode, text, isConcurrentMode) {
          var isDifferent = textNode.nodeValue !== text;
          return isDifferent;
        }
        function warnForDeletedHydratableElement(parentNode, child) {
          {
            if (didWarnInvalidHydration) {
              return;
            }
            didWarnInvalidHydration = true;
            error("Did not expect server HTML to contain a <%s> in <%s>.", child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
          }
        }
        function warnForDeletedHydratableText(parentNode, child) {
          {
            if (didWarnInvalidHydration) {
              return;
            }
            didWarnInvalidHydration = true;
            error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
          }
        }
        function warnForInsertedHydratedElement(parentNode, tag, props) {
          {
            if (didWarnInvalidHydration) {
              return;
            }
            didWarnInvalidHydration = true;
            error("Expected server HTML to contain a matching <%s> in <%s>.", tag, parentNode.nodeName.toLowerCase());
          }
        }
        function warnForInsertedHydratedText(parentNode, text) {
          {
            if (text === "") {
              return;
            }
            if (didWarnInvalidHydration) {
              return;
            }
            didWarnInvalidHydration = true;
            error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
          }
        }
        function restoreControlledState$3(domElement, tag, props) {
          switch (tag) {
            case "input":
              restoreControlledState(domElement, props);
              return;
            case "textarea":
              restoreControlledState$2(domElement, props);
              return;
            case "select":
              restoreControlledState$1(domElement, props);
              return;
          }
        }
        var validateDOMNesting = function() {
        };
        var updatedAncestorInfo = function() {
        };
        {
          var specialTags = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp"];
          var inScopeTags = [
            "applet",
            "caption",
            "html",
            "table",
            "td",
            "th",
            "marquee",
            "object",
            "template",
            // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
            // TODO: Distinguish by namespace here -- for <title>, including it here
            // errs on the side of fewer warnings
            "foreignObject",
            "desc",
            "title"
          ];
          var buttonScopeTags = inScopeTags.concat(["button"]);
          var impliedEndTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"];
          var emptyAncestorInfo = {
            current: null,
            formTag: null,
            aTagInScope: null,
            buttonTagInScope: null,
            nobrTagInScope: null,
            pTagInButtonScope: null,
            listItemTagAutoclosing: null,
            dlItemTagAutoclosing: null
          };
          updatedAncestorInfo = function(oldInfo, tag) {
            var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
            var info = {
              tag
            };
            if (inScopeTags.indexOf(tag) !== -1) {
              ancestorInfo.aTagInScope = null;
              ancestorInfo.buttonTagInScope = null;
              ancestorInfo.nobrTagInScope = null;
            }
            if (buttonScopeTags.indexOf(tag) !== -1) {
              ancestorInfo.pTagInButtonScope = null;
            }
            if (specialTags.indexOf(tag) !== -1 && tag !== "address" && tag !== "div" && tag !== "p") {
              ancestorInfo.listItemTagAutoclosing = null;
              ancestorInfo.dlItemTagAutoclosing = null;
            }
            ancestorInfo.current = info;
            if (tag === "form") {
              ancestorInfo.formTag = info;
            }
            if (tag === "a") {
              ancestorInfo.aTagInScope = info;
            }
            if (tag === "button") {
              ancestorInfo.buttonTagInScope = info;
            }
            if (tag === "nobr") {
              ancestorInfo.nobrTagInScope = info;
            }
            if (tag === "p") {
              ancestorInfo.pTagInButtonScope = info;
            }
            if (tag === "li") {
              ancestorInfo.listItemTagAutoclosing = info;
            }
            if (tag === "dd" || tag === "dt") {
              ancestorInfo.dlItemTagAutoclosing = info;
            }
            return ancestorInfo;
          };
          var isTagValidWithParent = function(tag, parentTag) {
            switch (parentTag) {
              case "select":
                return tag === "option" || tag === "optgroup" || tag === "#text";
              case "optgroup":
                return tag === "option" || tag === "#text";
              case "option":
                return tag === "#text";
              case "tr":
                return tag === "th" || tag === "td" || tag === "style" || tag === "script" || tag === "template";
              case "tbody":
              case "thead":
              case "tfoot":
                return tag === "tr" || tag === "style" || tag === "script" || tag === "template";
              case "colgroup":
                return tag === "col" || tag === "template";
              case "table":
                return tag === "caption" || tag === "colgroup" || tag === "tbody" || tag === "tfoot" || tag === "thead" || tag === "style" || tag === "script" || tag === "template";
              case "head":
                return tag === "base" || tag === "basefont" || tag === "bgsound" || tag === "link" || tag === "meta" || tag === "title" || tag === "noscript" || tag === "noframes" || tag === "style" || tag === "script" || tag === "template";
              case "html":
                return tag === "head" || tag === "body" || tag === "frameset";
              case "frameset":
                return tag === "frame";
              case "#document":
                return tag === "html";
            }
            switch (tag) {
              case "h1":
              case "h2":
              case "h3":
              case "h4":
              case "h5":
              case "h6":
                return parentTag !== "h1" && parentTag !== "h2" && parentTag !== "h3" && parentTag !== "h4" && parentTag !== "h5" && parentTag !== "h6";
              case "rp":
              case "rt":
                return impliedEndTags.indexOf(parentTag) === -1;
              case "body":
              case "caption":
              case "col":
              case "colgroup":
              case "frameset":
              case "frame":
              case "head":
              case "html":
              case "tbody":
              case "td":
              case "tfoot":
              case "th":
              case "thead":
              case "tr":
                return parentTag == null;
            }
            return true;
          };
          var findInvalidAncestorForTag = function(tag, ancestorInfo) {
            switch (tag) {
              case "address":
              case "article":
              case "aside":
              case "blockquote":
              case "center":
              case "details":
              case "dialog":
              case "dir":
              case "div":
              case "dl":
              case "fieldset":
              case "figcaption":
              case "figure":
              case "footer":
              case "header":
              case "hgroup":
              case "main":
              case "menu":
              case "nav":
              case "ol":
              case "p":
              case "section":
              case "summary":
              case "ul":
              case "pre":
              case "listing":
              case "table":
              case "hr":
              case "xmp":
              case "h1":
              case "h2":
              case "h3":
              case "h4":
              case "h5":
              case "h6":
                return ancestorInfo.pTagInButtonScope;
              case "form":
                return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
              case "li":
                return ancestorInfo.listItemTagAutoclosing;
              case "dd":
              case "dt":
                return ancestorInfo.dlItemTagAutoclosing;
              case "button":
                return ancestorInfo.buttonTagInScope;
              case "a":
                return ancestorInfo.aTagInScope;
              case "nobr":
                return ancestorInfo.nobrTagInScope;
            }
            return null;
          };
          var didWarn$1 = {};
          validateDOMNesting = function(childTag, childText, ancestorInfo) {
            ancestorInfo = ancestorInfo || emptyAncestorInfo;
            var parentInfo = ancestorInfo.current;
            var parentTag = parentInfo && parentInfo.tag;
            if (childText != null) {
              if (childTag != null) {
                error("validateDOMNesting: when childText is passed, childTag should be null");
              }
              childTag = "#text";
            }
            var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
            var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
            var invalidParentOrAncestor = invalidParent || invalidAncestor;
            if (!invalidParentOrAncestor) {
              return;
            }
            var ancestorTag = invalidParentOrAncestor.tag;
            var warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag;
            if (didWarn$1[warnKey]) {
              return;
            }
            didWarn$1[warnKey] = true;
            var tagDisplayName = childTag;
            var whitespaceInfo = "";
            if (childTag === "#text") {
              if (/\S/.test(childText)) {
                tagDisplayName = "Text nodes";
              } else {
                tagDisplayName = "Whitespace text nodes";
                whitespaceInfo = " Make sure you don't have any extra whitespace between tags on each line of your source code.";
              }
            } else {
              tagDisplayName = "<" + childTag + ">";
            }
            if (invalidParent) {
              var info = "";
              if (ancestorTag === "table" && childTag === "tr") {
                info += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser.";
              }
              error("validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s", tagDisplayName, ancestorTag, whitespaceInfo, info);
            } else {
              error("validateDOMNesting(...): %s cannot appear as a descendant of <%s>.", tagDisplayName, ancestorTag);
            }
          };
        }
        var SUPPRESS_HYDRATION_WARNING$1 = "suppressHydrationWarning";
        var SUSPENSE_START_DATA = "$";
        var SUSPENSE_END_DATA = "/$";
        var SUSPENSE_PENDING_START_DATA = "$?";
        var SUSPENSE_FALLBACK_START_DATA = "$!";
        var STYLE$1 = "style";
        var eventsEnabled = null;
        var selectionInformation = null;
        function getRootHostContext(rootContainerInstance) {
          var type;
          var namespace;
          var nodeType = rootContainerInstance.nodeType;
          switch (nodeType) {
            case DOCUMENT_NODE:
            case DOCUMENT_FRAGMENT_NODE: {
              type = nodeType === DOCUMENT_NODE ? "#document" : "#fragment";
              var root3 = rootContainerInstance.documentElement;
              namespace = root3 ? root3.namespaceURI : getChildNamespace(null, "");
              break;
            }
            default: {
              var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
              var ownNamespace = container.namespaceURI || null;
              type = container.tagName;
              namespace = getChildNamespace(ownNamespace, type);
              break;
            }
          }
          {
            var validatedTag = type.toLowerCase();
            var ancestorInfo = updatedAncestorInfo(null, validatedTag);
            return {
              namespace,
              ancestorInfo
            };
          }
        }
        function getChildHostContext(parentHostContext, type, rootContainerInstance) {
          {
            var parentHostContextDev = parentHostContext;
            var namespace = getChildNamespace(parentHostContextDev.namespace, type);
            var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
            return {
              namespace,
              ancestorInfo
            };
          }
        }
        function getPublicInstance(instance) {
          return instance;
        }
        function prepareForCommit(containerInfo) {
          eventsEnabled = isEnabled();
          selectionInformation = getSelectionInformation();
          var activeInstance = null;
          setEnabled(false);
          return activeInstance;
        }
        function resetAfterCommit(containerInfo) {
          restoreSelection(selectionInformation);
          setEnabled(eventsEnabled);
          eventsEnabled = null;
          selectionInformation = null;
        }
        function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
          var parentNamespace;
          {
            var hostContextDev = hostContext;
            validateDOMNesting(type, null, hostContextDev.ancestorInfo);
            if (typeof props.children === "string" || typeof props.children === "number") {
              var string = "" + props.children;
              var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
              validateDOMNesting(null, string, ownAncestorInfo);
            }
            parentNamespace = hostContextDev.namespace;
          }
          var domElement = createElement31(type, props, rootContainerInstance, parentNamespace);
          precacheFiberNode(internalInstanceHandle, domElement);
          updateFiberProps(domElement, props);
          return domElement;
        }
        function appendInitialChild(parentInstance, child) {
          parentInstance.appendChild(child);
        }
        function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
          setInitialProperties(domElement, type, props, rootContainerInstance);
          switch (type) {
            case "button":
            case "input":
            case "select":
            case "textarea":
              return !!props.autoFocus;
            case "img":
              return true;
            default:
              return false;
          }
        }
        function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
          {
            var hostContextDev = hostContext;
            if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === "string" || typeof newProps.children === "number")) {
              var string = "" + newProps.children;
              var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
              validateDOMNesting(null, string, ownAncestorInfo);
            }
          }
          return diffProperties(domElement, type, oldProps, newProps);
        }
        function shouldSetTextContent(type, props) {
          return type === "textarea" || type === "noscript" || typeof props.children === "string" || typeof props.children === "number" || typeof props.dangerouslySetInnerHTML === "object" && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
        }
        function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
          {
            var hostContextDev = hostContext;
            validateDOMNesting(null, text, hostContextDev.ancestorInfo);
          }
          var textNode = createTextNode(text, rootContainerInstance);
          precacheFiberNode(internalInstanceHandle, textNode);
          return textNode;
        }
        function getCurrentEventPriority() {
          var currentEvent = window.event;
          if (currentEvent === void 0) {
            return DefaultEventPriority;
          }
          return getEventPriority(currentEvent.type);
        }
        var scheduleTimeout = typeof setTimeout === "function" ? setTimeout : void 0;
        var cancelTimeout = typeof clearTimeout === "function" ? clearTimeout : void 0;
        var noTimeout = -1;
        var localPromise = typeof Promise === "function" ? Promise : void 0;
        var scheduleMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : typeof localPromise !== "undefined" ? function(callback) {
          return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
        } : scheduleTimeout;
        function handleErrorInNextTick(error2) {
          setTimeout(function() {
            throw error2;
          });
        }
        function commitMount(domElement, type, newProps, internalInstanceHandle) {
          switch (type) {
            case "button":
            case "input":
            case "select":
            case "textarea":
              if (newProps.autoFocus) {
                domElement.focus();
              }
              return;
            case "img": {
              if (newProps.src) {
                domElement.src = newProps.src;
              }
              return;
            }
          }
        }
        function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
          updateProperties(domElement, updatePayload, type, oldProps, newProps);
          updateFiberProps(domElement, newProps);
        }
        function resetTextContent(domElement) {
          setTextContent(domElement, "");
        }
        function commitTextUpdate(textInstance, oldText, newText) {
          textInstance.nodeValue = newText;
        }
        function appendChild(parentInstance, child) {
          parentInstance.appendChild(child);
        }
        function appendChildToContainer(container, child) {
          var parentNode;
          if (container.nodeType === COMMENT_NODE) {
            parentNode = container.parentNode;
            parentNode.insertBefore(child, container);
          } else {
            parentNode = container;
            parentNode.appendChild(child);
          }
          var reactRootContainer = container._reactRootContainer;
          if ((reactRootContainer === null || reactRootContainer === void 0) && parentNode.onclick === null) {
            trapClickOnNonInteractiveElement(parentNode);
          }
        }
        function insertBefore(parentInstance, child, beforeChild) {
          parentInstance.insertBefore(child, beforeChild);
        }
        function insertInContainerBefore(container, child, beforeChild) {
          if (container.nodeType === COMMENT_NODE) {
            container.parentNode.insertBefore(child, beforeChild);
          } else {
            container.insertBefore(child, beforeChild);
          }
        }
        function removeChild(parentInstance, child) {
          parentInstance.removeChild(child);
        }
        function removeChildFromContainer(container, child) {
          if (container.nodeType === COMMENT_NODE) {
            container.parentNode.removeChild(child);
          } else {
            container.removeChild(child);
          }
        }
        function clearSuspenseBoundary(parentInstance, suspenseInstance) {
          var node = suspenseInstance;
          var depth = 0;
          do {
            var nextNode = node.nextSibling;
            parentInstance.removeChild(node);
            if (nextNode && nextNode.nodeType === COMMENT_NODE) {
              var data = nextNode.data;
              if (data === SUSPENSE_END_DATA) {
                if (depth === 0) {
                  parentInstance.removeChild(nextNode);
                  retryIfBlockedOn(suspenseInstance);
                  return;
                } else {
                  depth--;
                }
              } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
                depth++;
              }
            }
            node = nextNode;
          } while (node);
          retryIfBlockedOn(suspenseInstance);
        }
        function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
          if (container.nodeType === COMMENT_NODE) {
            clearSuspenseBoundary(container.parentNode, suspenseInstance);
          } else if (container.nodeType === ELEMENT_NODE) {
            clearSuspenseBoundary(container, suspenseInstance);
          }
          retryIfBlockedOn(container);
        }
        function hideInstance(instance) {
          instance = instance;
          var style2 = instance.style;
          if (typeof style2.setProperty === "function") {
            style2.setProperty("display", "none", "important");
          } else {
            style2.display = "none";
          }
        }
        function hideTextInstance(textInstance) {
          textInstance.nodeValue = "";
        }
        function unhideInstance(instance, props) {
          instance = instance;
          var styleProp = props[STYLE$1];
          var display = styleProp !== void 0 && styleProp !== null && styleProp.hasOwnProperty("display") ? styleProp.display : null;
          instance.style.display = dangerousStyleValue("display", display);
        }
        function unhideTextInstance(textInstance, text) {
          textInstance.nodeValue = text;
        }
        function clearContainer(container) {
          if (container.nodeType === ELEMENT_NODE) {
            container.textContent = "";
          } else if (container.nodeType === DOCUMENT_NODE) {
            if (container.documentElement) {
              container.removeChild(container.documentElement);
            }
          }
        }
        function canHydrateInstance(instance, type, props) {
          if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
            return null;
          }
          return instance;
        }
        function canHydrateTextInstance(instance, text) {
          if (text === "" || instance.nodeType !== TEXT_NODE) {
            return null;
          }
          return instance;
        }
        function canHydrateSuspenseInstance(instance) {
          if (instance.nodeType !== COMMENT_NODE) {
            return null;
          }
          return instance;
        }
        function isSuspenseInstancePending(instance) {
          return instance.data === SUSPENSE_PENDING_START_DATA;
        }
        function isSuspenseInstanceFallback(instance) {
          return instance.data === SUSPENSE_FALLBACK_START_DATA;
        }
        function getSuspenseInstanceFallbackErrorDetails(instance) {
          var dataset = instance.nextSibling && instance.nextSibling.dataset;
          var digest, message, stack;
          if (dataset) {
            digest = dataset.dgst;
            {
              message = dataset.msg;
              stack = dataset.stck;
            }
          }
          {
            return {
              message,
              digest,
              stack
            };
          }
        }
        function registerSuspenseInstanceRetry(instance, callback) {
          instance._reactRetry = callback;
        }
        function getNextHydratable(node) {
          for (; node != null; node = node.nextSibling) {
            var nodeType = node.nodeType;
            if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
              break;
            }
            if (nodeType === COMMENT_NODE) {
              var nodeData = node.data;
              if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
                break;
              }
              if (nodeData === SUSPENSE_END_DATA) {
                return null;
              }
            }
          }
          return node;
        }
        function getNextHydratableSibling(instance) {
          return getNextHydratable(instance.nextSibling);
        }
        function getFirstHydratableChild(parentInstance) {
          return getNextHydratable(parentInstance.firstChild);
        }
        function getFirstHydratableChildWithinContainer(parentContainer) {
          return getNextHydratable(parentContainer.firstChild);
        }
        function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
          return getNextHydratable(parentInstance.nextSibling);
        }
        function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
          precacheFiberNode(internalInstanceHandle, instance);
          updateFiberProps(instance, props);
          var parentNamespace;
          {
            var hostContextDev = hostContext;
            parentNamespace = hostContextDev.namespace;
          }
          var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
          return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
        }
        function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
          precacheFiberNode(internalInstanceHandle, textInstance);
          var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
          return diffHydratedText(textInstance, text);
        }
        function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
          precacheFiberNode(internalInstanceHandle, suspenseInstance);
        }
        function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
          var node = suspenseInstance.nextSibling;
          var depth = 0;
          while (node) {
            if (node.nodeType === COMMENT_NODE) {
              var data = node.data;
              if (data === SUSPENSE_END_DATA) {
                if (depth === 0) {
                  return getNextHydratableSibling(node);
                } else {
                  depth--;
                }
              } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
                depth++;
              }
            }
            node = node.nextSibling;
          }
          return null;
        }
        function getParentSuspenseInstance(targetInstance) {
          var node = targetInstance.previousSibling;
          var depth = 0;
          while (node) {
            if (node.nodeType === COMMENT_NODE) {
              var data = node.data;
              if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
                if (depth === 0) {
                  return node;
                } else {
                  depth--;
                }
              } else if (data === SUSPENSE_END_DATA) {
                depth++;
              }
            }
            node = node.previousSibling;
          }
          return null;
        }
        function commitHydratedContainer(container) {
          retryIfBlockedOn(container);
        }
        function commitHydratedSuspenseInstance(suspenseInstance) {
          retryIfBlockedOn(suspenseInstance);
        }
        function shouldDeleteUnhydratedTailInstances(parentType) {
          return parentType !== "head" && parentType !== "body";
        }
        function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
          var shouldWarnDev = true;
          checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
        }
        function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
          if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
            var shouldWarnDev = true;
            checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
          }
        }
        function didNotHydrateInstanceWithinContainer(parentContainer, instance) {
          {
            if (instance.nodeType === ELEMENT_NODE) {
              warnForDeletedHydratableElement(parentContainer, instance);
            } else if (instance.nodeType === COMMENT_NODE)
              ;
            else {
              warnForDeletedHydratableText(parentContainer, instance);
            }
          }
        }
        function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) {
          {
            var parentNode = parentInstance.parentNode;
            if (parentNode !== null) {
              if (instance.nodeType === ELEMENT_NODE) {
                warnForDeletedHydratableElement(parentNode, instance);
              } else if (instance.nodeType === COMMENT_NODE)
                ;
              else {
                warnForDeletedHydratableText(parentNode, instance);
              }
            }
          }
        }
        function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) {
          {
            if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
              if (instance.nodeType === ELEMENT_NODE) {
                warnForDeletedHydratableElement(parentInstance, instance);
              } else if (instance.nodeType === COMMENT_NODE)
                ;
              else {
                warnForDeletedHydratableText(parentInstance, instance);
              }
            }
          }
        }
        function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) {
          {
            warnForInsertedHydratedElement(parentContainer, type);
          }
        }
        function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
          {
            warnForInsertedHydratedText(parentContainer, text);
          }
        }
        function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) {
          {
            var parentNode = parentInstance.parentNode;
            if (parentNode !== null)
              warnForInsertedHydratedElement(parentNode, type);
          }
        }
        function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
          {
            var parentNode = parentInstance.parentNode;
            if (parentNode !== null)
              warnForInsertedHydratedText(parentNode, text);
          }
        }
        function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) {
          {
            if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
              warnForInsertedHydratedElement(parentInstance, type);
            }
          }
        }
        function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
          {
            if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
              warnForInsertedHydratedText(parentInstance, text);
            }
          }
        }
        function errorHydratingContainer(parentContainer) {
          {
            error("An error occurred during hydration. The server HTML was replaced with client content in <%s>.", parentContainer.nodeName.toLowerCase());
          }
        }
        function preparePortalMount(portalInstance) {
          listenToAllSupportedEvents(portalInstance);
        }
        var randomKey = Math.random().toString(36).slice(2);
        var internalInstanceKey = "__reactFiber$" + randomKey;
        var internalPropsKey = "__reactProps$" + randomKey;
        var internalContainerInstanceKey = "__reactContainer$" + randomKey;
        var internalEventHandlersKey = "__reactEvents$" + randomKey;
        var internalEventHandlerListenersKey = "__reactListeners$" + randomKey;
        var internalEventHandlesSetKey = "__reactHandles$" + randomKey;
        function detachDeletedInstance(node) {
          delete node[internalInstanceKey];
          delete node[internalPropsKey];
          delete node[internalEventHandlersKey];
          delete node[internalEventHandlerListenersKey];
          delete node[internalEventHandlesSetKey];
        }
        function precacheFiberNode(hostInst, node) {
          node[internalInstanceKey] = hostInst;
        }
        function markContainerAsRoot(hostRoot, node) {
          node[internalContainerInstanceKey] = hostRoot;
        }
        function unmarkContainerAsRoot(node) {
          node[internalContainerInstanceKey] = null;
        }
        function isContainerMarkedAsRoot(node) {
          return !!node[internalContainerInstanceKey];
        }
        function getClosestInstanceFromNode(targetNode) {
          var targetInst = targetNode[internalInstanceKey];
          if (targetInst) {
            return targetInst;
          }
          var parentNode = targetNode.parentNode;
          while (parentNode) {
            targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
            if (targetInst) {
              var alternate = targetInst.alternate;
              if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
                var suspenseInstance = getParentSuspenseInstance(targetNode);
                while (suspenseInstance !== null) {
                  var targetSuspenseInst = suspenseInstance[internalInstanceKey];
                  if (targetSuspenseInst) {
                    return targetSuspenseInst;
                  }
                  suspenseInstance = getParentSuspenseInstance(suspenseInstance);
                }
              }
              return targetInst;
            }
            targetNode = parentNode;
            parentNode = targetNode.parentNode;
          }
          return null;
        }
        function getInstanceFromNode(node) {
          var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
          if (inst) {
            if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
              return inst;
            } else {
              return null;
            }
          }
          return null;
        }
        function getNodeFromInstance(inst) {
          if (inst.tag === HostComponent || inst.tag === HostText) {
            return inst.stateNode;
          }
          throw new Error("getNodeFromInstance: Invalid argument.");
        }
        function getFiberCurrentPropsFromNode(node) {
          return node[internalPropsKey] || null;
        }
        function updateFiberProps(node, props) {
          node[internalPropsKey] = props;
        }
        function getEventListenerSet(node) {
          var elementListenerSet = node[internalEventHandlersKey];
          if (elementListenerSet === void 0) {
            elementListenerSet = node[internalEventHandlersKey] = /* @__PURE__ */ new Set();
          }
          return elementListenerSet;
        }
        var loggedTypeFailures = {};
        var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
        function setCurrentlyValidatingElement(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
            } else {
              ReactDebugCurrentFrame$1.setExtraStackFrame(null);
            }
          }
        }
        function checkPropTypes(typeSpecs, values, location2, componentName, element) {
          {
            var has3 = Function.call.bind(hasOwnProperty3);
            for (var typeSpecName in typeSpecs) {
              if (has3(typeSpecs, typeSpecName)) {
                var error$1 = void 0;
                try {
                  if (typeof typeSpecs[typeSpecName] !== "function") {
                    var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                    err.name = "Invariant Violation";
                    throw err;
                  }
                  error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
                } catch (ex) {
                  error$1 = ex;
                }
                if (error$1 && !(error$1 instanceof Error)) {
                  setCurrentlyValidatingElement(element);
                  error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1);
                  setCurrentlyValidatingElement(null);
                }
                if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                  loggedTypeFailures[error$1.message] = true;
                  setCurrentlyValidatingElement(element);
                  error("Failed %s type: %s", location2, error$1.message);
                  setCurrentlyValidatingElement(null);
                }
              }
            }
          }
        }
        var valueStack = [];
        var fiberStack;
        {
          fiberStack = [];
        }
        var index2 = -1;
        function createCursor(defaultValue) {
          return {
            current: defaultValue
          };
        }
        function pop(cursor, fiber) {
          if (index2 < 0) {
            {
              error("Unexpected pop.");
            }
            return;
          }
          {
            if (fiber !== fiberStack[index2]) {
              error("Unexpected Fiber popped.");
            }
          }
          cursor.current = valueStack[index2];
          valueStack[index2] = null;
          {
            fiberStack[index2] = null;
          }
          index2--;
        }
        function push3(cursor, value, fiber) {
          index2++;
          valueStack[index2] = cursor.current;
          {
            fiberStack[index2] = fiber;
          }
          cursor.current = value;
        }
        var warnedAboutMissingGetChildContext;
        {
          warnedAboutMissingGetChildContext = {};
        }
        var emptyContextObject = {};
        {
          Object.freeze(emptyContextObject);
        }
        var contextStackCursor = createCursor(emptyContextObject);
        var didPerformWorkStackCursor = createCursor(false);
        var previousContext = emptyContextObject;
        function getUnmaskedContext(workInProgress2, Component2, didPushOwnContextIfProvider) {
          {
            if (didPushOwnContextIfProvider && isContextProvider(Component2)) {
              return previousContext;
            }
            return contextStackCursor.current;
          }
        }
        function cacheContext(workInProgress2, unmaskedContext, maskedContext) {
          {
            var instance = workInProgress2.stateNode;
            instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
            instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
          }
        }
        function getMaskedContext(workInProgress2, unmaskedContext) {
          {
            var type = workInProgress2.type;
            var contextTypes = type.contextTypes;
            if (!contextTypes) {
              return emptyContextObject;
            }
            var instance = workInProgress2.stateNode;
            if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
              return instance.__reactInternalMemoizedMaskedChildContext;
            }
            var context = {};
            for (var key in contextTypes) {
              context[key] = unmaskedContext[key];
            }
            {
              var name = getComponentNameFromFiber(workInProgress2) || "Unknown";
              checkPropTypes(contextTypes, context, "context", name);
            }
            if (instance) {
              cacheContext(workInProgress2, unmaskedContext, context);
            }
            return context;
          }
        }
        function hasContextChanged() {
          {
            return didPerformWorkStackCursor.current;
          }
        }
        function isContextProvider(type) {
          {
            var childContextTypes = type.childContextTypes;
            return childContextTypes !== null && childContextTypes !== void 0;
          }
        }
        function popContext(fiber) {
          {
            pop(didPerformWorkStackCursor, fiber);
            pop(contextStackCursor, fiber);
          }
        }
        function popTopLevelContextObject(fiber) {
          {
            pop(didPerformWorkStackCursor, fiber);
            pop(contextStackCursor, fiber);
          }
        }
        function pushTopLevelContextObject(fiber, context, didChange) {
          {
            if (contextStackCursor.current !== emptyContextObject) {
              throw new Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
            }
            push3(contextStackCursor, context, fiber);
            push3(didPerformWorkStackCursor, didChange, fiber);
          }
        }
        function processChildContext(fiber, type, parentContext) {
          {
            var instance = fiber.stateNode;
            var childContextTypes = type.childContextTypes;
            if (typeof instance.getChildContext !== "function") {
              {
                var componentName = getComponentNameFromFiber(fiber) || "Unknown";
                if (!warnedAboutMissingGetChildContext[componentName]) {
                  warnedAboutMissingGetChildContext[componentName] = true;
                  error("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.", componentName, componentName);
                }
              }
              return parentContext;
            }
            var childContext = instance.getChildContext();
            for (var contextKey in childContext) {
              if (!(contextKey in childContextTypes)) {
                throw new Error((getComponentNameFromFiber(fiber) || "Unknown") + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
              }
            }
            {
              var name = getComponentNameFromFiber(fiber) || "Unknown";
              checkPropTypes(childContextTypes, childContext, "child context", name);
            }
            return assign({}, parentContext, childContext);
          }
        }
        function pushContextProvider(workInProgress2) {
          {
            var instance = workInProgress2.stateNode;
            var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
            previousContext = contextStackCursor.current;
            push3(contextStackCursor, memoizedMergedChildContext, workInProgress2);
            push3(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2);
            return true;
          }
        }
        function invalidateContextProvider(workInProgress2, type, didChange) {
          {
            var instance = workInProgress2.stateNode;
            if (!instance) {
              throw new Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
            }
            if (didChange) {
              var mergedContext = processChildContext(workInProgress2, type, previousContext);
              instance.__reactInternalMemoizedMergedChildContext = mergedContext;
              pop(didPerformWorkStackCursor, workInProgress2);
              pop(contextStackCursor, workInProgress2);
              push3(contextStackCursor, mergedContext, workInProgress2);
              push3(didPerformWorkStackCursor, didChange, workInProgress2);
            } else {
              pop(didPerformWorkStackCursor, workInProgress2);
              push3(didPerformWorkStackCursor, didChange, workInProgress2);
            }
          }
        }
        function findCurrentUnmaskedContext(fiber) {
          {
            if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
              throw new Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");
            }
            var node = fiber;
            do {
              switch (node.tag) {
                case HostRoot:
                  return node.stateNode.context;
                case ClassComponent: {
                  var Component2 = node.type;
                  if (isContextProvider(Component2)) {
                    return node.stateNode.__reactInternalMemoizedMergedChildContext;
                  }
                  break;
                }
              }
              node = node.return;
            } while (node !== null);
            throw new Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        var LegacyRoot = 0;
        var ConcurrentRoot = 1;
        var syncQueue = null;
        var includesLegacySyncCallbacks = false;
        var isFlushingSyncQueue = false;
        function scheduleSyncCallback(callback) {
          if (syncQueue === null) {
            syncQueue = [callback];
          } else {
            syncQueue.push(callback);
          }
        }
        function scheduleLegacySyncCallback(callback) {
          includesLegacySyncCallbacks = true;
          scheduleSyncCallback(callback);
        }
        function flushSyncCallbacksOnlyInLegacyMode() {
          if (includesLegacySyncCallbacks) {
            flushSyncCallbacks();
          }
        }
        function flushSyncCallbacks() {
          if (!isFlushingSyncQueue && syncQueue !== null) {
            isFlushingSyncQueue = true;
            var i3 = 0;
            var previousUpdatePriority = getCurrentUpdatePriority();
            try {
              var isSync = true;
              var queue2 = syncQueue;
              setCurrentUpdatePriority(DiscreteEventPriority);
              for (; i3 < queue2.length; i3++) {
                var callback = queue2[i3];
                do {
                  callback = callback(isSync);
                } while (callback !== null);
              }
              syncQueue = null;
              includesLegacySyncCallbacks = false;
            } catch (error2) {
              if (syncQueue !== null) {
                syncQueue = syncQueue.slice(i3 + 1);
              }
              scheduleCallback(ImmediatePriority, flushSyncCallbacks);
              throw error2;
            } finally {
              setCurrentUpdatePriority(previousUpdatePriority);
              isFlushingSyncQueue = false;
            }
          }
          return null;
        }
        var forkStack = [];
        var forkStackIndex = 0;
        var treeForkProvider = null;
        var treeForkCount = 0;
        var idStack = [];
        var idStackIndex = 0;
        var treeContextProvider = null;
        var treeContextId = 1;
        var treeContextOverflow = "";
        function isForkedChild(workInProgress2) {
          warnIfNotHydrating();
          return (workInProgress2.flags & Forked) !== NoFlags;
        }
        function getForksAtLevel(workInProgress2) {
          warnIfNotHydrating();
          return treeForkCount;
        }
        function getTreeId() {
          var overflow = treeContextOverflow;
          var idWithLeadingBit = treeContextId;
          var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
          return id.toString(32) + overflow;
        }
        function pushTreeFork(workInProgress2, totalChildren) {
          warnIfNotHydrating();
          forkStack[forkStackIndex++] = treeForkCount;
          forkStack[forkStackIndex++] = treeForkProvider;
          treeForkProvider = workInProgress2;
          treeForkCount = totalChildren;
        }
        function pushTreeId(workInProgress2, totalChildren, index3) {
          warnIfNotHydrating();
          idStack[idStackIndex++] = treeContextId;
          idStack[idStackIndex++] = treeContextOverflow;
          idStack[idStackIndex++] = treeContextProvider;
          treeContextProvider = workInProgress2;
          var baseIdWithLeadingBit = treeContextId;
          var baseOverflow = treeContextOverflow;
          var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
          var baseId2 = baseIdWithLeadingBit & ~(1 << baseLength);
          var slot = index3 + 1;
          var length = getBitLength(totalChildren) + baseLength;
          if (length > 30) {
            var numberOfOverflowBits = baseLength - baseLength % 5;
            var newOverflowBits = (1 << numberOfOverflowBits) - 1;
            var newOverflow = (baseId2 & newOverflowBits).toString(32);
            var restOfBaseId = baseId2 >> numberOfOverflowBits;
            var restOfBaseLength = baseLength - numberOfOverflowBits;
            var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
            var restOfNewBits = slot << restOfBaseLength;
            var id = restOfNewBits | restOfBaseId;
            var overflow = newOverflow + baseOverflow;
            treeContextId = 1 << restOfLength | id;
            treeContextOverflow = overflow;
          } else {
            var newBits = slot << baseLength;
            var _id = newBits | baseId2;
            var _overflow = baseOverflow;
            treeContextId = 1 << length | _id;
            treeContextOverflow = _overflow;
          }
        }
        function pushMaterializedTreeId(workInProgress2) {
          warnIfNotHydrating();
          var returnFiber = workInProgress2.return;
          if (returnFiber !== null) {
            var numberOfForks = 1;
            var slotIndex = 0;
            pushTreeFork(workInProgress2, numberOfForks);
            pushTreeId(workInProgress2, numberOfForks, slotIndex);
          }
        }
        function getBitLength(number) {
          return 32 - clz32(number);
        }
        function getLeadingBit(id) {
          return 1 << getBitLength(id) - 1;
        }
        function popTreeContext(workInProgress2) {
          while (workInProgress2 === treeForkProvider) {
            treeForkProvider = forkStack[--forkStackIndex];
            forkStack[forkStackIndex] = null;
            treeForkCount = forkStack[--forkStackIndex];
            forkStack[forkStackIndex] = null;
          }
          while (workInProgress2 === treeContextProvider) {
            treeContextProvider = idStack[--idStackIndex];
            idStack[idStackIndex] = null;
            treeContextOverflow = idStack[--idStackIndex];
            idStack[idStackIndex] = null;
            treeContextId = idStack[--idStackIndex];
            idStack[idStackIndex] = null;
          }
        }
        function getSuspendedTreeContext() {
          warnIfNotHydrating();
          if (treeContextProvider !== null) {
            return {
              id: treeContextId,
              overflow: treeContextOverflow
            };
          } else {
            return null;
          }
        }
        function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
          warnIfNotHydrating();
          idStack[idStackIndex++] = treeContextId;
          idStack[idStackIndex++] = treeContextOverflow;
          idStack[idStackIndex++] = treeContextProvider;
          treeContextId = suspendedContext.id;
          treeContextOverflow = suspendedContext.overflow;
          treeContextProvider = workInProgress2;
        }
        function warnIfNotHydrating() {
          {
            if (!getIsHydrating()) {
              error("Expected to be hydrating. This is a bug in React. Please file an issue.");
            }
          }
        }
        var hydrationParentFiber = null;
        var nextHydratableInstance = null;
        var isHydrating = false;
        var didSuspendOrErrorDEV = false;
        var hydrationErrors = null;
        function warnIfHydrating() {
          {
            if (isHydrating) {
              error("We should not be hydrating here. This is a bug in React. Please file a bug.");
            }
          }
        }
        function markDidThrowWhileHydratingDEV() {
          {
            didSuspendOrErrorDEV = true;
          }
        }
        function didSuspendOrErrorWhileHydratingDEV() {
          {
            return didSuspendOrErrorDEV;
          }
        }
        function enterHydrationState(fiber) {
          var parentInstance = fiber.stateNode.containerInfo;
          nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
          hydrationParentFiber = fiber;
          isHydrating = true;
          hydrationErrors = null;
          didSuspendOrErrorDEV = false;
          return true;
        }
        function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {
          nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
          hydrationParentFiber = fiber;
          isHydrating = true;
          hydrationErrors = null;
          didSuspendOrErrorDEV = false;
          if (treeContext !== null) {
            restoreSuspendedTreeContext(fiber, treeContext);
          }
          return true;
        }
        function warnUnhydratedInstance(returnFiber, instance) {
          {
            switch (returnFiber.tag) {
              case HostRoot: {
                didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance);
                break;
              }
              case HostComponent: {
                var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                didNotHydrateInstance(
                  returnFiber.type,
                  returnFiber.memoizedProps,
                  returnFiber.stateNode,
                  instance,
                  // TODO: Delete this argument when we remove the legacy root API.
                  isConcurrentMode
                );
                break;
              }
              case SuspenseComponent: {
                var suspenseState = returnFiber.memoizedState;
                if (suspenseState.dehydrated !== null)
                  didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance);
                break;
              }
            }
          }
        }
        function deleteHydratableInstance(returnFiber, instance) {
          warnUnhydratedInstance(returnFiber, instance);
          var childToDelete = createFiberFromHostInstanceForDeletion();
          childToDelete.stateNode = instance;
          childToDelete.return = returnFiber;
          var deletions = returnFiber.deletions;
          if (deletions === null) {
            returnFiber.deletions = [childToDelete];
            returnFiber.flags |= ChildDeletion;
          } else {
            deletions.push(childToDelete);
          }
        }
        function warnNonhydratedInstance(returnFiber, fiber) {
          {
            if (didSuspendOrErrorDEV) {
              return;
            }
            switch (returnFiber.tag) {
              case HostRoot: {
                var parentContainer = returnFiber.stateNode.containerInfo;
                switch (fiber.tag) {
                  case HostComponent:
                    var type = fiber.type;
                    var props = fiber.pendingProps;
                    didNotFindHydratableInstanceWithinContainer(parentContainer, type);
                    break;
                  case HostText:
                    var text = fiber.pendingProps;
                    didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
                    break;
                }
                break;
              }
              case HostComponent: {
                var parentType = returnFiber.type;
                var parentProps = returnFiber.memoizedProps;
                var parentInstance = returnFiber.stateNode;
                switch (fiber.tag) {
                  case HostComponent: {
                    var _type = fiber.type;
                    var _props = fiber.pendingProps;
                    var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                    didNotFindHydratableInstance(
                      parentType,
                      parentProps,
                      parentInstance,
                      _type,
                      _props,
                      // TODO: Delete this argument when we remove the legacy root API.
                      isConcurrentMode
                    );
                    break;
                  }
                  case HostText: {
                    var _text = fiber.pendingProps;
                    var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                    didNotFindHydratableTextInstance(
                      parentType,
                      parentProps,
                      parentInstance,
                      _text,
                      // TODO: Delete this argument when we remove the legacy root API.
                      _isConcurrentMode
                    );
                    break;
                  }
                }
                break;
              }
              case SuspenseComponent: {
                var suspenseState = returnFiber.memoizedState;
                var _parentInstance = suspenseState.dehydrated;
                if (_parentInstance !== null)
                  switch (fiber.tag) {
                    case HostComponent:
                      var _type2 = fiber.type;
                      var _props2 = fiber.pendingProps;
                      didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
                      break;
                    case HostText:
                      var _text2 = fiber.pendingProps;
                      didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
                      break;
                  }
                break;
              }
              default:
                return;
            }
          }
        }
        function insertNonHydratedInstance(returnFiber, fiber) {
          fiber.flags = fiber.flags & ~Hydrating | Placement;
          warnNonhydratedInstance(returnFiber, fiber);
        }
        function tryHydrate(fiber, nextInstance) {
          switch (fiber.tag) {
            case HostComponent: {
              var type = fiber.type;
              var props = fiber.pendingProps;
              var instance = canHydrateInstance(nextInstance, type);
              if (instance !== null) {
                fiber.stateNode = instance;
                hydrationParentFiber = fiber;
                nextHydratableInstance = getFirstHydratableChild(instance);
                return true;
              }
              return false;
            }
            case HostText: {
              var text = fiber.pendingProps;
              var textInstance = canHydrateTextInstance(nextInstance, text);
              if (textInstance !== null) {
                fiber.stateNode = textInstance;
                hydrationParentFiber = fiber;
                nextHydratableInstance = null;
                return true;
              }
              return false;
            }
            case SuspenseComponent: {
              var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
              if (suspenseInstance !== null) {
                var suspenseState = {
                  dehydrated: suspenseInstance,
                  treeContext: getSuspendedTreeContext(),
                  retryLane: OffscreenLane
                };
                fiber.memoizedState = suspenseState;
                var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
                dehydratedFragment.return = fiber;
                fiber.child = dehydratedFragment;
                hydrationParentFiber = fiber;
                nextHydratableInstance = null;
                return true;
              }
              return false;
            }
            default:
              return false;
          }
        }
        function shouldClientRenderOnMismatch(fiber) {
          return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
        }
        function throwOnHydrationMismatch(fiber) {
          throw new Error("Hydration failed because the initial UI does not match what was rendered on the server.");
        }
        function tryToClaimNextHydratableInstance(fiber) {
          if (!isHydrating) {
            return;
          }
          var nextInstance = nextHydratableInstance;
          if (!nextInstance) {
            if (shouldClientRenderOnMismatch(fiber)) {
              warnNonhydratedInstance(hydrationParentFiber, fiber);
              throwOnHydrationMismatch();
            }
            insertNonHydratedInstance(hydrationParentFiber, fiber);
            isHydrating = false;
            hydrationParentFiber = fiber;
            return;
          }
          var firstAttemptedInstance = nextInstance;
          if (!tryHydrate(fiber, nextInstance)) {
            if (shouldClientRenderOnMismatch(fiber)) {
              warnNonhydratedInstance(hydrationParentFiber, fiber);
              throwOnHydrationMismatch();
            }
            nextInstance = getNextHydratableSibling(firstAttemptedInstance);
            var prevHydrationParentFiber = hydrationParentFiber;
            if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
              insertNonHydratedInstance(hydrationParentFiber, fiber);
              isHydrating = false;
              hydrationParentFiber = fiber;
              return;
            }
            deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
          }
        }
        function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
          var instance = fiber.stateNode;
          var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
          var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev);
          fiber.updateQueue = updatePayload;
          if (updatePayload !== null) {
            return true;
          }
          return false;
        }
        function prepareToHydrateHostTextInstance(fiber) {
          var textInstance = fiber.stateNode;
          var textContent = fiber.memoizedProps;
          var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
          if (shouldUpdate) {
            var returnFiber = hydrationParentFiber;
            if (returnFiber !== null) {
              switch (returnFiber.tag) {
                case HostRoot: {
                  var parentContainer = returnFiber.stateNode.containerInfo;
                  var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                  didNotMatchHydratedContainerTextInstance(
                    parentContainer,
                    textInstance,
                    textContent,
                    // TODO: Delete this argument when we remove the legacy root API.
                    isConcurrentMode
                  );
                  break;
                }
                case HostComponent: {
                  var parentType = returnFiber.type;
                  var parentProps = returnFiber.memoizedProps;
                  var parentInstance = returnFiber.stateNode;
                  var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;
                  didNotMatchHydratedTextInstance(
                    parentType,
                    parentProps,
                    parentInstance,
                    textInstance,
                    textContent,
                    // TODO: Delete this argument when we remove the legacy root API.
                    _isConcurrentMode2
                  );
                  break;
                }
              }
            }
          }
          return shouldUpdate;
        }
        function prepareToHydrateHostSuspenseInstance(fiber) {
          var suspenseState = fiber.memoizedState;
          var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
          if (!suspenseInstance) {
            throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
          }
          hydrateSuspenseInstance(suspenseInstance, fiber);
        }
        function skipPastDehydratedSuspenseInstance(fiber) {
          var suspenseState = fiber.memoizedState;
          var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
          if (!suspenseInstance) {
            throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
          }
          return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
        }
        function popToNextHostParent(fiber) {
          var parent = fiber.return;
          while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
            parent = parent.return;
          }
          hydrationParentFiber = parent;
        }
        function popHydrationState(fiber) {
          if (fiber !== hydrationParentFiber) {
            return false;
          }
          if (!isHydrating) {
            popToNextHostParent(fiber);
            isHydrating = true;
            return false;
          }
          if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
            var nextInstance = nextHydratableInstance;
            if (nextInstance) {
              if (shouldClientRenderOnMismatch(fiber)) {
                warnIfUnhydratedTailNodes(fiber);
                throwOnHydrationMismatch();
              } else {
                while (nextInstance) {
                  deleteHydratableInstance(fiber, nextInstance);
                  nextInstance = getNextHydratableSibling(nextInstance);
                }
              }
            }
          }
          popToNextHostParent(fiber);
          if (fiber.tag === SuspenseComponent) {
            nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
          } else {
            nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
          }
          return true;
        }
        function hasUnhydratedTailNodes() {
          return isHydrating && nextHydratableInstance !== null;
        }
        function warnIfUnhydratedTailNodes(fiber) {
          var nextInstance = nextHydratableInstance;
          while (nextInstance) {
            warnUnhydratedInstance(fiber, nextInstance);
            nextInstance = getNextHydratableSibling(nextInstance);
          }
        }
        function resetHydrationState() {
          hydrationParentFiber = null;
          nextHydratableInstance = null;
          isHydrating = false;
          didSuspendOrErrorDEV = false;
        }
        function upgradeHydrationErrorsToRecoverable() {
          if (hydrationErrors !== null) {
            queueRecoverableErrors(hydrationErrors);
            hydrationErrors = null;
          }
        }
        function getIsHydrating() {
          return isHydrating;
        }
        function queueHydrationError(error2) {
          if (hydrationErrors === null) {
            hydrationErrors = [error2];
          } else {
            hydrationErrors.push(error2);
          }
        }
        var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
        var NoTransition = null;
        function requestCurrentTransition() {
          return ReactCurrentBatchConfig$1.transition;
        }
        var ReactStrictModeWarnings = {
          recordUnsafeLifecycleWarnings: function(fiber, instance) {
          },
          flushPendingUnsafeLifecycleWarnings: function() {
          },
          recordLegacyContextWarning: function(fiber, instance) {
          },
          flushLegacyContextWarning: function() {
          },
          discardPendingWarnings: function() {
          }
        };
        {
          var findStrictRoot = function(fiber) {
            var maybeStrictRoot = null;
            var node = fiber;
            while (node !== null) {
              if (node.mode & StrictLegacyMode) {
                maybeStrictRoot = node;
              }
              node = node.return;
            }
            return maybeStrictRoot;
          };
          var setToSortedString = function(set2) {
            var array = [];
            set2.forEach(function(value) {
              array.push(value);
            });
            return array.sort().join(", ");
          };
          var pendingComponentWillMountWarnings = [];
          var pendingUNSAFE_ComponentWillMountWarnings = [];
          var pendingComponentWillReceivePropsWarnings = [];
          var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
          var pendingComponentWillUpdateWarnings = [];
          var pendingUNSAFE_ComponentWillUpdateWarnings = [];
          var didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
          ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
            if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
              return;
            }
            if (typeof instance.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components.
            instance.componentWillMount.__suppressDeprecationWarning !== true) {
              pendingComponentWillMountWarnings.push(fiber);
            }
            if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === "function") {
              pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
            }
            if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
              pendingComponentWillReceivePropsWarnings.push(fiber);
            }
            if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === "function") {
              pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
            }
            if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
              pendingComponentWillUpdateWarnings.push(fiber);
            }
            if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === "function") {
              pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
            }
          };
          ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
            var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
            if (pendingComponentWillMountWarnings.length > 0) {
              pendingComponentWillMountWarnings.forEach(function(fiber) {
                componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingComponentWillMountWarnings = [];
            }
            var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
            if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
              pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
                UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingUNSAFE_ComponentWillMountWarnings = [];
            }
            var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
            if (pendingComponentWillReceivePropsWarnings.length > 0) {
              pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
                componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingComponentWillReceivePropsWarnings = [];
            }
            var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
            if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
              pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) {
                UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
            }
            var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
            if (pendingComponentWillUpdateWarnings.length > 0) {
              pendingComponentWillUpdateWarnings.forEach(function(fiber) {
                componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingComponentWillUpdateWarnings = [];
            }
            var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
            if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
              pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
                UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutUnsafeLifecycles.add(fiber.type);
              });
              pendingUNSAFE_ComponentWillUpdateWarnings = [];
            }
            if (UNSAFE_componentWillMountUniqueNames.size > 0) {
              var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
              error("Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s", sortedNames);
            }
            if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
              var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
              error("Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n\nPlease update the following components: %s", _sortedNames);
            }
            if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
              var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
              error("Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s", _sortedNames2);
            }
            if (componentWillMountUniqueNames.size > 0) {
              var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
              warn2("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames3);
            }
            if (componentWillReceivePropsUniqueNames.size > 0) {
              var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
              warn2("componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames4);
            }
            if (componentWillUpdateUniqueNames.size > 0) {
              var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
              warn2("componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames5);
            }
          };
          var pendingLegacyContextWarning = /* @__PURE__ */ new Map();
          var didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
          ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
            var strictRoot = findStrictRoot(fiber);
            if (strictRoot === null) {
              error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.");
              return;
            }
            if (didWarnAboutLegacyContext.has(fiber.type)) {
              return;
            }
            var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
            if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === "function") {
              if (warningsForRoot === void 0) {
                warningsForRoot = [];
                pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
              }
              warningsForRoot.push(fiber);
            }
          };
          ReactStrictModeWarnings.flushLegacyContextWarning = function() {
            pendingLegacyContextWarning.forEach(function(fiberArray, strictRoot) {
              if (fiberArray.length === 0) {
                return;
              }
              var firstFiber = fiberArray[0];
              var uniqueNames = /* @__PURE__ */ new Set();
              fiberArray.forEach(function(fiber) {
                uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
                didWarnAboutLegacyContext.add(fiber.type);
              });
              var sortedNames = setToSortedString(uniqueNames);
              try {
                setCurrentFiber(firstFiber);
                error("Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", sortedNames);
              } finally {
                resetCurrentFiber();
              }
            });
          };
          ReactStrictModeWarnings.discardPendingWarnings = function() {
            pendingComponentWillMountWarnings = [];
            pendingUNSAFE_ComponentWillMountWarnings = [];
            pendingComponentWillReceivePropsWarnings = [];
            pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
            pendingComponentWillUpdateWarnings = [];
            pendingUNSAFE_ComponentWillUpdateWarnings = [];
            pendingLegacyContextWarning = /* @__PURE__ */ new Map();
          };
        }
        function resolveDefaultProps(Component2, baseProps) {
          if (Component2 && Component2.defaultProps) {
            var props = assign({}, baseProps);
            var defaultProps2 = Component2.defaultProps;
            for (var propName in defaultProps2) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps2[propName];
              }
            }
            return props;
          }
          return baseProps;
        }
        var valueCursor = createCursor(null);
        var rendererSigil;
        {
          rendererSigil = {};
        }
        var currentlyRenderingFiber = null;
        var lastContextDependency = null;
        var lastFullyObservedContext = null;
        var isDisallowedContextReadInDEV = false;
        function resetContextDependencies() {
          currentlyRenderingFiber = null;
          lastContextDependency = null;
          lastFullyObservedContext = null;
          {
            isDisallowedContextReadInDEV = false;
          }
        }
        function enterDisallowedContextReadInDEV() {
          {
            isDisallowedContextReadInDEV = true;
          }
        }
        function exitDisallowedContextReadInDEV() {
          {
            isDisallowedContextReadInDEV = false;
          }
        }
        function pushProvider(providerFiber, context, nextValue) {
          {
            push3(valueCursor, context._currentValue, providerFiber);
            context._currentValue = nextValue;
            {
              if (context._currentRenderer !== void 0 && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
                error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.");
              }
              context._currentRenderer = rendererSigil;
            }
          }
        }
        function popProvider(context, providerFiber) {
          var currentValue = valueCursor.current;
          pop(valueCursor, providerFiber);
          {
            {
              context._currentValue = currentValue;
            }
          }
        }
        function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
          var node = parent;
          while (node !== null) {
            var alternate = node.alternate;
            if (!isSubsetOfLanes(node.childLanes, renderLanes2)) {
              node.childLanes = mergeLanes(node.childLanes, renderLanes2);
              if (alternate !== null) {
                alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
              }
            } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) {
              alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
            }
            if (node === propagationRoot) {
              break;
            }
            node = node.return;
          }
          {
            if (node !== propagationRoot) {
              error("Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
        }
        function propagateContextChange(workInProgress2, context, renderLanes2) {
          {
            propagateContextChange_eager(workInProgress2, context, renderLanes2);
          }
        }
        function propagateContextChange_eager(workInProgress2, context, renderLanes2) {
          var fiber = workInProgress2.child;
          if (fiber !== null) {
            fiber.return = workInProgress2;
          }
          while (fiber !== null) {
            var nextFiber = void 0;
            var list = fiber.dependencies;
            if (list !== null) {
              nextFiber = fiber.child;
              var dependency = list.firstContext;
              while (dependency !== null) {
                if (dependency.context === context) {
                  if (fiber.tag === ClassComponent) {
                    var lane = pickArbitraryLane(renderLanes2);
                    var update2 = createUpdate(NoTimestamp, lane);
                    update2.tag = ForceUpdate;
                    var updateQueue = fiber.updateQueue;
                    if (updateQueue === null)
                      ;
                    else {
                      var sharedQueue = updateQueue.shared;
                      var pending = sharedQueue.pending;
                      if (pending === null) {
                        update2.next = update2;
                      } else {
                        update2.next = pending.next;
                        pending.next = update2;
                      }
                      sharedQueue.pending = update2;
                    }
                  }
                  fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
                  var alternate = fiber.alternate;
                  if (alternate !== null) {
                    alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
                  }
                  scheduleContextWorkOnParentPath(fiber.return, renderLanes2, workInProgress2);
                  list.lanes = mergeLanes(list.lanes, renderLanes2);
                  break;
                }
                dependency = dependency.next;
              }
            } else if (fiber.tag === ContextProvider) {
              nextFiber = fiber.type === workInProgress2.type ? null : fiber.child;
            } else if (fiber.tag === DehydratedFragment) {
              var parentSuspense = fiber.return;
              if (parentSuspense === null) {
                throw new Error("We just came from a parent so we must have had a parent. This is a bug in React.");
              }
              parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes2);
              var _alternate = parentSuspense.alternate;
              if (_alternate !== null) {
                _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes2);
              }
              scheduleContextWorkOnParentPath(parentSuspense, renderLanes2, workInProgress2);
              nextFiber = fiber.sibling;
            } else {
              nextFiber = fiber.child;
            }
            if (nextFiber !== null) {
              nextFiber.return = fiber;
            } else {
              nextFiber = fiber;
              while (nextFiber !== null) {
                if (nextFiber === workInProgress2) {
                  nextFiber = null;
                  break;
                }
                var sibling = nextFiber.sibling;
                if (sibling !== null) {
                  sibling.return = nextFiber.return;
                  nextFiber = sibling;
                  break;
                }
                nextFiber = nextFiber.return;
              }
            }
            fiber = nextFiber;
          }
        }
        function prepareToReadContext(workInProgress2, renderLanes2) {
          currentlyRenderingFiber = workInProgress2;
          lastContextDependency = null;
          lastFullyObservedContext = null;
          var dependencies = workInProgress2.dependencies;
          if (dependencies !== null) {
            {
              var firstContext = dependencies.firstContext;
              if (firstContext !== null) {
                if (includesSomeLane(dependencies.lanes, renderLanes2)) {
                  markWorkInProgressReceivedUpdate();
                }
                dependencies.firstContext = null;
              }
            }
          }
        }
        function readContext(context) {
          {
            if (isDisallowedContextReadInDEV) {
              error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
            }
          }
          var value = context._currentValue;
          if (lastFullyObservedContext === context)
            ;
          else {
            var contextItem = {
              context,
              memoizedValue: value,
              next: null
            };
            if (lastContextDependency === null) {
              if (currentlyRenderingFiber === null) {
                throw new Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
              }
              lastContextDependency = contextItem;
              currentlyRenderingFiber.dependencies = {
                lanes: NoLanes,
                firstContext: contextItem
              };
            } else {
              lastContextDependency = lastContextDependency.next = contextItem;
            }
          }
          return value;
        }
        var concurrentQueues = null;
        function pushConcurrentUpdateQueue(queue2) {
          if (concurrentQueues === null) {
            concurrentQueues = [queue2];
          } else {
            concurrentQueues.push(queue2);
          }
        }
        function finishQueueingConcurrentUpdates() {
          if (concurrentQueues !== null) {
            for (var i3 = 0; i3 < concurrentQueues.length; i3++) {
              var queue2 = concurrentQueues[i3];
              var lastInterleavedUpdate = queue2.interleaved;
              if (lastInterleavedUpdate !== null) {
                queue2.interleaved = null;
                var firstInterleavedUpdate = lastInterleavedUpdate.next;
                var lastPendingUpdate = queue2.pending;
                if (lastPendingUpdate !== null) {
                  var firstPendingUpdate = lastPendingUpdate.next;
                  lastPendingUpdate.next = firstInterleavedUpdate;
                  lastInterleavedUpdate.next = firstPendingUpdate;
                }
                queue2.pending = lastInterleavedUpdate;
              }
            }
            concurrentQueues = null;
          }
        }
        function enqueueConcurrentHookUpdate(fiber, queue2, update2, lane) {
          var interleaved = queue2.interleaved;
          if (interleaved === null) {
            update2.next = update2;
            pushConcurrentUpdateQueue(queue2);
          } else {
            update2.next = interleaved.next;
            interleaved.next = update2;
          }
          queue2.interleaved = update2;
          return markUpdateLaneFromFiberToRoot(fiber, lane);
        }
        function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue2, update2, lane) {
          var interleaved = queue2.interleaved;
          if (interleaved === null) {
            update2.next = update2;
            pushConcurrentUpdateQueue(queue2);
          } else {
            update2.next = interleaved.next;
            interleaved.next = update2;
          }
          queue2.interleaved = update2;
        }
        function enqueueConcurrentClassUpdate(fiber, queue2, update2, lane) {
          var interleaved = queue2.interleaved;
          if (interleaved === null) {
            update2.next = update2;
            pushConcurrentUpdateQueue(queue2);
          } else {
            update2.next = interleaved.next;
            interleaved.next = update2;
          }
          queue2.interleaved = update2;
          return markUpdateLaneFromFiberToRoot(fiber, lane);
        }
        function enqueueConcurrentRenderForLane(fiber, lane) {
          return markUpdateLaneFromFiberToRoot(fiber, lane);
        }
        var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;
        function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
          sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
          var alternate = sourceFiber.alternate;
          if (alternate !== null) {
            alternate.lanes = mergeLanes(alternate.lanes, lane);
          }
          {
            if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
              warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
            }
          }
          var node = sourceFiber;
          var parent = sourceFiber.return;
          while (parent !== null) {
            parent.childLanes = mergeLanes(parent.childLanes, lane);
            alternate = parent.alternate;
            if (alternate !== null) {
              alternate.childLanes = mergeLanes(alternate.childLanes, lane);
            } else {
              {
                if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
                  warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
                }
              }
            }
            node = parent;
            parent = parent.return;
          }
          if (node.tag === HostRoot) {
            var root3 = node.stateNode;
            return root3;
          } else {
            return null;
          }
        }
        var UpdateState = 0;
        var ReplaceState = 1;
        var ForceUpdate = 2;
        var CaptureUpdate = 3;
        var hasForceUpdate = false;
        var didWarnUpdateInsideUpdate;
        var currentlyProcessingQueue;
        {
          didWarnUpdateInsideUpdate = false;
          currentlyProcessingQueue = null;
        }
        function initializeUpdateQueue(fiber) {
          var queue2 = {
            baseState: fiber.memoizedState,
            firstBaseUpdate: null,
            lastBaseUpdate: null,
            shared: {
              pending: null,
              interleaved: null,
              lanes: NoLanes
            },
            effects: null
          };
          fiber.updateQueue = queue2;
        }
        function cloneUpdateQueue(current2, workInProgress2) {
          var queue2 = workInProgress2.updateQueue;
          var currentQueue = current2.updateQueue;
          if (queue2 === currentQueue) {
            var clone3 = {
              baseState: currentQueue.baseState,
              firstBaseUpdate: currentQueue.firstBaseUpdate,
              lastBaseUpdate: currentQueue.lastBaseUpdate,
              shared: currentQueue.shared,
              effects: currentQueue.effects
            };
            workInProgress2.updateQueue = clone3;
          }
        }
        function createUpdate(eventTime, lane) {
          var update2 = {
            eventTime,
            lane,
            tag: UpdateState,
            payload: null,
            callback: null,
            next: null
          };
          return update2;
        }
        function enqueueUpdate(fiber, update2, lane) {
          var updateQueue = fiber.updateQueue;
          if (updateQueue === null) {
            return null;
          }
          var sharedQueue = updateQueue.shared;
          {
            if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
              error("An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.");
              didWarnUpdateInsideUpdate = true;
            }
          }
          if (isUnsafeClassRenderPhaseUpdate()) {
            var pending = sharedQueue.pending;
            if (pending === null) {
              update2.next = update2;
            } else {
              update2.next = pending.next;
              pending.next = update2;
            }
            sharedQueue.pending = update2;
            return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
          } else {
            return enqueueConcurrentClassUpdate(fiber, sharedQueue, update2, lane);
          }
        }
        function entangleTransitions(root3, fiber, lane) {
          var updateQueue = fiber.updateQueue;
          if (updateQueue === null) {
            return;
          }
          var sharedQueue = updateQueue.shared;
          if (isTransitionLane(lane)) {
            var queueLanes = sharedQueue.lanes;
            queueLanes = intersectLanes(queueLanes, root3.pendingLanes);
            var newQueueLanes = mergeLanes(queueLanes, lane);
            sharedQueue.lanes = newQueueLanes;
            markRootEntangled(root3, newQueueLanes);
          }
        }
        function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
          var queue2 = workInProgress2.updateQueue;
          var current2 = workInProgress2.alternate;
          if (current2 !== null) {
            var currentQueue = current2.updateQueue;
            if (queue2 === currentQueue) {
              var newFirst = null;
              var newLast = null;
              var firstBaseUpdate = queue2.firstBaseUpdate;
              if (firstBaseUpdate !== null) {
                var update2 = firstBaseUpdate;
                do {
                  var clone3 = {
                    eventTime: update2.eventTime,
                    lane: update2.lane,
                    tag: update2.tag,
                    payload: update2.payload,
                    callback: update2.callback,
                    next: null
                  };
                  if (newLast === null) {
                    newFirst = newLast = clone3;
                  } else {
                    newLast.next = clone3;
                    newLast = clone3;
                  }
                  update2 = update2.next;
                } while (update2 !== null);
                if (newLast === null) {
                  newFirst = newLast = capturedUpdate;
                } else {
                  newLast.next = capturedUpdate;
                  newLast = capturedUpdate;
                }
              } else {
                newFirst = newLast = capturedUpdate;
              }
              queue2 = {
                baseState: currentQueue.baseState,
                firstBaseUpdate: newFirst,
                lastBaseUpdate: newLast,
                shared: currentQueue.shared,
                effects: currentQueue.effects
              };
              workInProgress2.updateQueue = queue2;
              return;
            }
          }
          var lastBaseUpdate = queue2.lastBaseUpdate;
          if (lastBaseUpdate === null) {
            queue2.firstBaseUpdate = capturedUpdate;
          } else {
            lastBaseUpdate.next = capturedUpdate;
          }
          queue2.lastBaseUpdate = capturedUpdate;
        }
        function getStateFromUpdate(workInProgress2, queue2, update2, prevState, nextProps, instance) {
          switch (update2.tag) {
            case ReplaceState: {
              var payload = update2.payload;
              if (typeof payload === "function") {
                {
                  enterDisallowedContextReadInDEV();
                }
                var nextState = payload.call(instance, prevState, nextProps);
                {
                  if (workInProgress2.mode & StrictLegacyMode) {
                    setIsStrictModeForDevtools(true);
                    try {
                      payload.call(instance, prevState, nextProps);
                    } finally {
                      setIsStrictModeForDevtools(false);
                    }
                  }
                  exitDisallowedContextReadInDEV();
                }
                return nextState;
              }
              return payload;
            }
            case CaptureUpdate: {
              workInProgress2.flags = workInProgress2.flags & ~ShouldCapture | DidCapture;
            }
            case UpdateState: {
              var _payload = update2.payload;
              var partialState;
              if (typeof _payload === "function") {
                {
                  enterDisallowedContextReadInDEV();
                }
                partialState = _payload.call(instance, prevState, nextProps);
                {
                  if (workInProgress2.mode & StrictLegacyMode) {
                    setIsStrictModeForDevtools(true);
                    try {
                      _payload.call(instance, prevState, nextProps);
                    } finally {
                      setIsStrictModeForDevtools(false);
                    }
                  }
                  exitDisallowedContextReadInDEV();
                }
              } else {
                partialState = _payload;
              }
              if (partialState === null || partialState === void 0) {
                return prevState;
              }
              return assign({}, prevState, partialState);
            }
            case ForceUpdate: {
              hasForceUpdate = true;
              return prevState;
            }
          }
          return prevState;
        }
        function processUpdateQueue(workInProgress2, props, instance, renderLanes2) {
          var queue2 = workInProgress2.updateQueue;
          hasForceUpdate = false;
          {
            currentlyProcessingQueue = queue2.shared;
          }
          var firstBaseUpdate = queue2.firstBaseUpdate;
          var lastBaseUpdate = queue2.lastBaseUpdate;
          var pendingQueue = queue2.shared.pending;
          if (pendingQueue !== null) {
            queue2.shared.pending = null;
            var lastPendingUpdate = pendingQueue;
            var firstPendingUpdate = lastPendingUpdate.next;
            lastPendingUpdate.next = null;
            if (lastBaseUpdate === null) {
              firstBaseUpdate = firstPendingUpdate;
            } else {
              lastBaseUpdate.next = firstPendingUpdate;
            }
            lastBaseUpdate = lastPendingUpdate;
            var current2 = workInProgress2.alternate;
            if (current2 !== null) {
              var currentQueue = current2.updateQueue;
              var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
              if (currentLastBaseUpdate !== lastBaseUpdate) {
                if (currentLastBaseUpdate === null) {
                  currentQueue.firstBaseUpdate = firstPendingUpdate;
                } else {
                  currentLastBaseUpdate.next = firstPendingUpdate;
                }
                currentQueue.lastBaseUpdate = lastPendingUpdate;
              }
            }
          }
          if (firstBaseUpdate !== null) {
            var newState = queue2.baseState;
            var newLanes = NoLanes;
            var newBaseState = null;
            var newFirstBaseUpdate = null;
            var newLastBaseUpdate = null;
            var update2 = firstBaseUpdate;
            do {
              var updateLane = update2.lane;
              var updateEventTime = update2.eventTime;
              if (!isSubsetOfLanes(renderLanes2, updateLane)) {
                var clone3 = {
                  eventTime: updateEventTime,
                  lane: updateLane,
                  tag: update2.tag,
                  payload: update2.payload,
                  callback: update2.callback,
                  next: null
                };
                if (newLastBaseUpdate === null) {
                  newFirstBaseUpdate = newLastBaseUpdate = clone3;
                  newBaseState = newState;
                } else {
                  newLastBaseUpdate = newLastBaseUpdate.next = clone3;
                }
                newLanes = mergeLanes(newLanes, updateLane);
              } else {
                if (newLastBaseUpdate !== null) {
                  var _clone = {
                    eventTime: updateEventTime,
                    // This update is going to be committed so we never want uncommit
                    // it. Using NoLane works because 0 is a subset of all bitmasks, so
                    // this will never be skipped by the check above.
                    lane: NoLane,
                    tag: update2.tag,
                    payload: update2.payload,
                    callback: update2.callback,
                    next: null
                  };
                  newLastBaseUpdate = newLastBaseUpdate.next = _clone;
                }
                newState = getStateFromUpdate(workInProgress2, queue2, update2, newState, props, instance);
                var callback = update2.callback;
                if (callback !== null && // If the update was already committed, we should not queue its
                // callback again.
                update2.lane !== NoLane) {
                  workInProgress2.flags |= Callback;
                  var effects = queue2.effects;
                  if (effects === null) {
                    queue2.effects = [update2];
                  } else {
                    effects.push(update2);
                  }
                }
              }
              update2 = update2.next;
              if (update2 === null) {
                pendingQueue = queue2.shared.pending;
                if (pendingQueue === null) {
                  break;
                } else {
                  var _lastPendingUpdate = pendingQueue;
                  var _firstPendingUpdate = _lastPendingUpdate.next;
                  _lastPendingUpdate.next = null;
                  update2 = _firstPendingUpdate;
                  queue2.lastBaseUpdate = _lastPendingUpdate;
                  queue2.shared.pending = null;
                }
              }
            } while (true);
            if (newLastBaseUpdate === null) {
              newBaseState = newState;
            }
            queue2.baseState = newBaseState;
            queue2.firstBaseUpdate = newFirstBaseUpdate;
            queue2.lastBaseUpdate = newLastBaseUpdate;
            var lastInterleaved = queue2.shared.interleaved;
            if (lastInterleaved !== null) {
              var interleaved = lastInterleaved;
              do {
                newLanes = mergeLanes(newLanes, interleaved.lane);
                interleaved = interleaved.next;
              } while (interleaved !== lastInterleaved);
            } else if (firstBaseUpdate === null) {
              queue2.shared.lanes = NoLanes;
            }
            markSkippedUpdateLanes(newLanes);
            workInProgress2.lanes = newLanes;
            workInProgress2.memoizedState = newState;
          }
          {
            currentlyProcessingQueue = null;
          }
        }
        function callCallback(callback, context) {
          if (typeof callback !== "function") {
            throw new Error("Invalid argument passed as callback. Expected a function. Instead " + ("received: " + callback));
          }
          callback.call(context);
        }
        function resetHasForceUpdateBeforeProcessing() {
          hasForceUpdate = false;
        }
        function checkHasForceUpdateAfterProcessing() {
          return hasForceUpdate;
        }
        function commitUpdateQueue(finishedWork, finishedQueue, instance) {
          var effects = finishedQueue.effects;
          finishedQueue.effects = null;
          if (effects !== null) {
            for (var i3 = 0; i3 < effects.length; i3++) {
              var effect = effects[i3];
              var callback = effect.callback;
              if (callback !== null) {
                effect.callback = null;
                callCallback(callback, instance);
              }
            }
          }
        }
        var fakeInternalInstance = {};
        var emptyRefsObject = new React145.Component().refs;
        var didWarnAboutStateAssignmentForComponent;
        var didWarnAboutUninitializedState;
        var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
        var didWarnAboutLegacyLifecyclesAndDerivedState;
        var didWarnAboutUndefinedDerivedState;
        var warnOnUndefinedDerivedState;
        var warnOnInvalidCallback;
        var didWarnAboutDirectlyAssigningPropsToState;
        var didWarnAboutContextTypeAndContextTypes;
        var didWarnAboutInvalidateContextType;
        {
          didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
          didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
          didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
          didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
          didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
          didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
          didWarnAboutContextTypeAndContextTypes = /* @__PURE__ */ new Set();
          didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
          var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
          warnOnInvalidCallback = function(callback, callerName) {
            if (callback === null || typeof callback === "function") {
              return;
            }
            var key = callerName + "_" + callback;
            if (!didWarnOnInvalidCallback.has(key)) {
              didWarnOnInvalidCallback.add(key);
              error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
            }
          };
          warnOnUndefinedDerivedState = function(type, partialState) {
            if (partialState === void 0) {
              var componentName = getComponentNameFromType(type) || "Component";
              if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
                didWarnAboutUndefinedDerivedState.add(componentName);
                error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", componentName);
              }
            }
          };
          Object.defineProperty(fakeInternalInstance, "_processChildContext", {
            enumerable: false,
            value: function() {
              throw new Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).");
            }
          });
          Object.freeze(fakeInternalInstance);
        }
        function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
          var prevState = workInProgress2.memoizedState;
          var partialState = getDerivedStateFromProps(nextProps, prevState);
          {
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                partialState = getDerivedStateFromProps(nextProps, prevState);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            warnOnUndefinedDerivedState(ctor, partialState);
          }
          var memoizedState = partialState === null || partialState === void 0 ? prevState : assign({}, prevState, partialState);
          workInProgress2.memoizedState = memoizedState;
          if (workInProgress2.lanes === NoLanes) {
            var updateQueue = workInProgress2.updateQueue;
            updateQueue.baseState = memoizedState;
          }
        }
        var classComponentUpdater = {
          isMounted,
          enqueueSetState: function(inst, payload, callback) {
            var fiber = get4(inst);
            var eventTime = requestEventTime();
            var lane = requestUpdateLane(fiber);
            var update2 = createUpdate(eventTime, lane);
            update2.payload = payload;
            if (callback !== void 0 && callback !== null) {
              {
                warnOnInvalidCallback(callback, "setState");
              }
              update2.callback = callback;
            }
            var root3 = enqueueUpdate(fiber, update2, lane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
              entangleTransitions(root3, fiber, lane);
            }
            {
              markStateUpdateScheduled(fiber, lane);
            }
          },
          enqueueReplaceState: function(inst, payload, callback) {
            var fiber = get4(inst);
            var eventTime = requestEventTime();
            var lane = requestUpdateLane(fiber);
            var update2 = createUpdate(eventTime, lane);
            update2.tag = ReplaceState;
            update2.payload = payload;
            if (callback !== void 0 && callback !== null) {
              {
                warnOnInvalidCallback(callback, "replaceState");
              }
              update2.callback = callback;
            }
            var root3 = enqueueUpdate(fiber, update2, lane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
              entangleTransitions(root3, fiber, lane);
            }
            {
              markStateUpdateScheduled(fiber, lane);
            }
          },
          enqueueForceUpdate: function(inst, callback) {
            var fiber = get4(inst);
            var eventTime = requestEventTime();
            var lane = requestUpdateLane(fiber);
            var update2 = createUpdate(eventTime, lane);
            update2.tag = ForceUpdate;
            if (callback !== void 0 && callback !== null) {
              {
                warnOnInvalidCallback(callback, "forceUpdate");
              }
              update2.callback = callback;
            }
            var root3 = enqueueUpdate(fiber, update2, lane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
              entangleTransitions(root3, fiber, lane);
            }
            {
              markForceUpdateScheduled(fiber, lane);
            }
          }
        };
        function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
          var instance = workInProgress2.stateNode;
          if (typeof instance.shouldComponentUpdate === "function") {
            var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
            {
              if (workInProgress2.mode & StrictLegacyMode) {
                setIsStrictModeForDevtools(true);
                try {
                  shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
                } finally {
                  setIsStrictModeForDevtools(false);
                }
              }
              if (shouldUpdate === void 0) {
                error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentNameFromType(ctor) || "Component");
              }
            }
            return shouldUpdate;
          }
          if (ctor.prototype && ctor.prototype.isPureReactComponent) {
            return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
          }
          return true;
        }
        function checkClassInstance(workInProgress2, ctor, newProps) {
          var instance = workInProgress2.stateNode;
          {
            var name = getComponentNameFromType(ctor) || "Component";
            var renderPresent = instance.render;
            if (!renderPresent) {
              if (ctor.prototype && typeof ctor.prototype.render === "function") {
                error("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?", name);
              } else {
                error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name);
              }
            }
            if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
              error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", name);
            }
            if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
              error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", name);
            }
            if (instance.propTypes) {
              error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name);
            }
            if (instance.contextType) {
              error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name);
            }
            {
              if (instance.contextTypes) {
                error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name);
              }
              if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
                didWarnAboutContextTypeAndContextTypes.add(ctor);
                error("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.", name);
              }
            }
            if (typeof instance.componentShouldUpdate === "function") {
              error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", name);
            }
            if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== "undefined") {
              error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentNameFromType(ctor) || "A pure component");
            }
            if (typeof instance.componentDidUnmount === "function") {
              error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", name);
            }
            if (typeof instance.componentDidReceiveProps === "function") {
              error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", name);
            }
            if (typeof instance.componentWillRecieveProps === "function") {
              error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name);
            }
            if (typeof instance.UNSAFE_componentWillRecieveProps === "function") {
              error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name);
            }
            var hasMutatedProps = instance.props !== newProps;
            if (instance.props !== void 0 && hasMutatedProps) {
              error("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", name, name);
            }
            if (instance.defaultProps) {
              error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", name, name);
            }
            if (typeof instance.getSnapshotBeforeUpdate === "function" && typeof instance.componentDidUpdate !== "function" && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
              didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
              error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentNameFromType(ctor));
            }
            if (typeof instance.getDerivedStateFromProps === "function") {
              error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
            }
            if (typeof instance.getDerivedStateFromError === "function") {
              error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
            }
            if (typeof ctor.getSnapshotBeforeUpdate === "function") {
              error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", name);
            }
            var _state = instance.state;
            if (_state && (typeof _state !== "object" || isArray2(_state))) {
              error("%s.state: must be set to an object or null", name);
            }
            if (typeof instance.getChildContext === "function" && typeof ctor.childContextTypes !== "object") {
              error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name);
            }
          }
        }
        function adoptClassInstance(workInProgress2, instance) {
          instance.updater = classComponentUpdater;
          workInProgress2.stateNode = instance;
          set(instance, workInProgress2);
          {
            instance._reactInternalInstance = fakeInternalInstance;
          }
        }
        function constructClassInstance(workInProgress2, ctor, props) {
          var isLegacyContextConsumer = false;
          var unmaskedContext = emptyContextObject;
          var context = emptyContextObject;
          var contextType = ctor.contextType;
          {
            if ("contextType" in ctor) {
              var isValid2 = (
                // Allow null for conditional declaration
                contextType === null || contextType !== void 0 && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === void 0
              );
              if (!isValid2 && !didWarnAboutInvalidateContextType.has(ctor)) {
                didWarnAboutInvalidateContextType.add(ctor);
                var addendum = "";
                if (contextType === void 0) {
                  addendum = " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.";
                } else if (typeof contextType !== "object") {
                  addendum = " However, it is set to a " + typeof contextType + ".";
                } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
                  addendum = " Did you accidentally pass the Context.Provider instead?";
                } else if (contextType._context !== void 0) {
                  addendum = " Did you accidentally pass the Context.Consumer instead?";
                } else {
                  addendum = " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}.";
                }
                error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentNameFromType(ctor) || "Component", addendum);
              }
            }
          }
          if (typeof contextType === "object" && contextType !== null) {
            context = readContext(contextType);
          } else {
            unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
            var contextTypes = ctor.contextTypes;
            isLegacyContextConsumer = contextTypes !== null && contextTypes !== void 0;
            context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject;
          }
          var instance = new ctor(props, context);
          {
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                instance = new ctor(props, context);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
          }
          var state = workInProgress2.memoizedState = instance.state !== null && instance.state !== void 0 ? instance.state : null;
          adoptClassInstance(workInProgress2, instance);
          {
            if (typeof ctor.getDerivedStateFromProps === "function" && state === null) {
              var componentName = getComponentNameFromType(ctor) || "Component";
              if (!didWarnAboutUninitializedState.has(componentName)) {
                didWarnAboutUninitializedState.add(componentName);
                error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", componentName, instance.state === null ? "null" : "undefined", componentName);
              }
            }
            if (typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function") {
              var foundWillMountName = null;
              var foundWillReceivePropsName = null;
              var foundWillUpdateName = null;
              if (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true) {
                foundWillMountName = "componentWillMount";
              } else if (typeof instance.UNSAFE_componentWillMount === "function") {
                foundWillMountName = "UNSAFE_componentWillMount";
              }
              if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
                foundWillReceivePropsName = "componentWillReceiveProps";
              } else if (typeof instance.UNSAFE_componentWillReceiveProps === "function") {
                foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps";
              }
              if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
                foundWillUpdateName = "componentWillUpdate";
              } else if (typeof instance.UNSAFE_componentWillUpdate === "function") {
                foundWillUpdateName = "UNSAFE_componentWillUpdate";
              }
              if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
                var _componentName = getComponentNameFromType(ctor) || "Component";
                var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
                if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
                  didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
                  error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : "");
                }
              }
            }
          }
          if (isLegacyContextConsumer) {
            cacheContext(workInProgress2, unmaskedContext, context);
          }
          return instance;
        }
        function callComponentWillMount(workInProgress2, instance) {
          var oldState = instance.state;
          if (typeof instance.componentWillMount === "function") {
            instance.componentWillMount();
          }
          if (typeof instance.UNSAFE_componentWillMount === "function") {
            instance.UNSAFE_componentWillMount();
          }
          if (oldState !== instance.state) {
            {
              error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentNameFromFiber(workInProgress2) || "Component");
            }
            classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
          }
        }
        function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
          var oldState = instance.state;
          if (typeof instance.componentWillReceiveProps === "function") {
            instance.componentWillReceiveProps(newProps, nextContext);
          }
          if (typeof instance.UNSAFE_componentWillReceiveProps === "function") {
            instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
          }
          if (instance.state !== oldState) {
            {
              var componentName = getComponentNameFromFiber(workInProgress2) || "Component";
              if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
                didWarnAboutStateAssignmentForComponent.add(componentName);
                error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", componentName);
              }
            }
            classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
          }
        }
        function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
          {
            checkClassInstance(workInProgress2, ctor, newProps);
          }
          var instance = workInProgress2.stateNode;
          instance.props = newProps;
          instance.state = workInProgress2.memoizedState;
          instance.refs = emptyRefsObject;
          initializeUpdateQueue(workInProgress2);
          var contextType = ctor.contextType;
          if (typeof contextType === "object" && contextType !== null) {
            instance.context = readContext(contextType);
          } else {
            var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
            instance.context = getMaskedContext(workInProgress2, unmaskedContext);
          }
          {
            if (instance.state === newProps) {
              var componentName = getComponentNameFromType(ctor) || "Component";
              if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
                didWarnAboutDirectlyAssigningPropsToState.add(componentName);
                error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", componentName);
              }
            }
            if (workInProgress2.mode & StrictLegacyMode) {
              ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance);
            }
            {
              ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance);
            }
          }
          instance.state = workInProgress2.memoizedState;
          var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
          if (typeof getDerivedStateFromProps === "function") {
            applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
            instance.state = workInProgress2.memoizedState;
          }
          if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) {
            callComponentWillMount(workInProgress2, instance);
            processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
            instance.state = workInProgress2.memoizedState;
          }
          if (typeof instance.componentDidMount === "function") {
            var fiberFlags = Update;
            {
              fiberFlags |= LayoutStatic;
            }
            if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
              fiberFlags |= MountLayoutDev;
            }
            workInProgress2.flags |= fiberFlags;
          }
        }
        function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
          var instance = workInProgress2.stateNode;
          var oldProps = workInProgress2.memoizedProps;
          instance.props = oldProps;
          var oldContext = instance.context;
          var contextType = ctor.contextType;
          var nextContext = emptyContextObject;
          if (typeof contextType === "object" && contextType !== null) {
            nextContext = readContext(contextType);
          } else {
            var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
            nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext);
          }
          var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
          var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function";
          if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) {
            if (oldProps !== newProps || oldContext !== nextContext) {
              callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext);
            }
          }
          resetHasForceUpdateBeforeProcessing();
          var oldState = workInProgress2.memoizedState;
          var newState = instance.state = oldState;
          processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
          newState = workInProgress2.memoizedState;
          if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
            if (typeof instance.componentDidMount === "function") {
              var fiberFlags = Update;
              {
                fiberFlags |= LayoutStatic;
              }
              if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
                fiberFlags |= MountLayoutDev;
              }
              workInProgress2.flags |= fiberFlags;
            }
            return false;
          }
          if (typeof getDerivedStateFromProps === "function") {
            applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
            newState = workInProgress2.memoizedState;
          }
          var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext);
          if (shouldUpdate) {
            if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) {
              if (typeof instance.componentWillMount === "function") {
                instance.componentWillMount();
              }
              if (typeof instance.UNSAFE_componentWillMount === "function") {
                instance.UNSAFE_componentWillMount();
              }
            }
            if (typeof instance.componentDidMount === "function") {
              var _fiberFlags = Update;
              {
                _fiberFlags |= LayoutStatic;
              }
              if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
                _fiberFlags |= MountLayoutDev;
              }
              workInProgress2.flags |= _fiberFlags;
            }
          } else {
            if (typeof instance.componentDidMount === "function") {
              var _fiberFlags2 = Update;
              {
                _fiberFlags2 |= LayoutStatic;
              }
              if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
                _fiberFlags2 |= MountLayoutDev;
              }
              workInProgress2.flags |= _fiberFlags2;
            }
            workInProgress2.memoizedProps = newProps;
            workInProgress2.memoizedState = newState;
          }
          instance.props = newProps;
          instance.state = newState;
          instance.context = nextContext;
          return shouldUpdate;
        }
        function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) {
          var instance = workInProgress2.stateNode;
          cloneUpdateQueue(current2, workInProgress2);
          var unresolvedOldProps = workInProgress2.memoizedProps;
          var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps);
          instance.props = oldProps;
          var unresolvedNewProps = workInProgress2.pendingProps;
          var oldContext = instance.context;
          var contextType = ctor.contextType;
          var nextContext = emptyContextObject;
          if (typeof contextType === "object" && contextType !== null) {
            nextContext = readContext(contextType);
          } else {
            var nextUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
            nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext);
          }
          var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
          var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function";
          if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) {
            if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
              callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext);
            }
          }
          resetHasForceUpdateBeforeProcessing();
          var oldState = workInProgress2.memoizedState;
          var newState = instance.state = oldState;
          processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
          newState = workInProgress2.memoizedState;
          if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !enableLazyContextPropagation) {
            if (typeof instance.componentDidUpdate === "function") {
              if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
                workInProgress2.flags |= Update;
              }
            }
            if (typeof instance.getSnapshotBeforeUpdate === "function") {
              if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
                workInProgress2.flags |= Snapshot;
              }
            }
            return false;
          }
          if (typeof getDerivedStateFromProps === "function") {
            applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
            newState = workInProgress2.memoizedState;
          }
          var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
          // both before and after `shouldComponentUpdate` has been called. Not ideal,
          // but I'm loath to refactor this function. This only happens for memoized
          // components so it's not that common.
          enableLazyContextPropagation;
          if (shouldUpdate) {
            if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === "function" || typeof instance.componentWillUpdate === "function")) {
              if (typeof instance.componentWillUpdate === "function") {
                instance.componentWillUpdate(newProps, newState, nextContext);
              }
              if (typeof instance.UNSAFE_componentWillUpdate === "function") {
                instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
              }
            }
            if (typeof instance.componentDidUpdate === "function") {
              workInProgress2.flags |= Update;
            }
            if (typeof instance.getSnapshotBeforeUpdate === "function") {
              workInProgress2.flags |= Snapshot;
            }
          } else {
            if (typeof instance.componentDidUpdate === "function") {
              if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
                workInProgress2.flags |= Update;
              }
            }
            if (typeof instance.getSnapshotBeforeUpdate === "function") {
              if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
                workInProgress2.flags |= Snapshot;
              }
            }
            workInProgress2.memoizedProps = newProps;
            workInProgress2.memoizedState = newState;
          }
          instance.props = newProps;
          instance.state = newState;
          instance.context = nextContext;
          return shouldUpdate;
        }
        var didWarnAboutMaps;
        var didWarnAboutGenerators;
        var didWarnAboutStringRefs;
        var ownerHasKeyUseWarning;
        var ownerHasFunctionTypeWarning;
        var warnForMissingKey = function(child, returnFiber) {
        };
        {
          didWarnAboutMaps = false;
          didWarnAboutGenerators = false;
          didWarnAboutStringRefs = {};
          ownerHasKeyUseWarning = {};
          ownerHasFunctionTypeWarning = {};
          warnForMissingKey = function(child, returnFiber) {
            if (child === null || typeof child !== "object") {
              return;
            }
            if (!child._store || child._store.validated || child.key != null) {
              return;
            }
            if (typeof child._store !== "object") {
              throw new Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
            }
            child._store.validated = true;
            var componentName = getComponentNameFromFiber(returnFiber) || "Component";
            if (ownerHasKeyUseWarning[componentName]) {
              return;
            }
            ownerHasKeyUseWarning[componentName] = true;
            error('Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.');
          };
        }
        function coerceRef(returnFiber, current2, element) {
          var mixedRef = element.ref;
          if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") {
            {
              if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
              // because these cannot be automatically converted to an arrow function
              // using a codemod. Therefore, we don't have to warn about string refs again.
              !(element._owner && element._self && element._owner.stateNode !== element._self)) {
                var componentName = getComponentNameFromFiber(returnFiber) || "Component";
                if (!didWarnAboutStringRefs[componentName]) {
                  {
                    error('A string ref, "%s", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', mixedRef);
                  }
                  didWarnAboutStringRefs[componentName] = true;
                }
              }
            }
            if (element._owner) {
              var owner = element._owner;
              var inst;
              if (owner) {
                var ownerFiber = owner;
                if (ownerFiber.tag !== ClassComponent) {
                  throw new Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref");
                }
                inst = ownerFiber.stateNode;
              }
              if (!inst) {
                throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
              }
              var resolvedInst = inst;
              {
                checkPropStringCoercion(mixedRef, "ref");
              }
              var stringRef = "" + mixedRef;
              if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) {
                return current2.ref;
              }
              var ref = function(value) {
                var refs = resolvedInst.refs;
                if (refs === emptyRefsObject) {
                  refs = resolvedInst.refs = {};
                }
                if (value === null) {
                  delete refs[stringRef];
                } else {
                  refs[stringRef] = value;
                }
              };
              ref._stringRef = stringRef;
              return ref;
            } else {
              if (typeof mixedRef !== "string") {
                throw new Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
              }
              if (!element._owner) {
                throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information.");
              }
            }
          }
          return mixedRef;
        }
        function throwOnInvalidObjectType(returnFiber, newChild) {
          var childString = Object.prototype.toString.call(newChild);
          throw new Error("Objects are not valid as a React child (found: " + (childString === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : childString) + "). If you meant to render a collection of children, use an array instead.");
        }
        function warnOnFunctionType(returnFiber) {
          {
            var componentName = getComponentNameFromFiber(returnFiber) || "Component";
            if (ownerHasFunctionTypeWarning[componentName]) {
              return;
            }
            ownerHasFunctionTypeWarning[componentName] = true;
            error("Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.");
          }
        }
        function resolveLazy(lazyType2) {
          var payload = lazyType2._payload;
          var init = lazyType2._init;
          return init(payload);
        }
        function ChildReconciler(shouldTrackSideEffects) {
          function deleteChild(returnFiber, childToDelete) {
            if (!shouldTrackSideEffects) {
              return;
            }
            var deletions = returnFiber.deletions;
            if (deletions === null) {
              returnFiber.deletions = [childToDelete];
              returnFiber.flags |= ChildDeletion;
            } else {
              deletions.push(childToDelete);
            }
          }
          function deleteRemainingChildren(returnFiber, currentFirstChild) {
            if (!shouldTrackSideEffects) {
              return null;
            }
            var childToDelete = currentFirstChild;
            while (childToDelete !== null) {
              deleteChild(returnFiber, childToDelete);
              childToDelete = childToDelete.sibling;
            }
            return null;
          }
          function mapRemainingChildren(returnFiber, currentFirstChild) {
            var existingChildren = /* @__PURE__ */ new Map();
            var existingChild = currentFirstChild;
            while (existingChild !== null) {
              if (existingChild.key !== null) {
                existingChildren.set(existingChild.key, existingChild);
              } else {
                existingChildren.set(existingChild.index, existingChild);
              }
              existingChild = existingChild.sibling;
            }
            return existingChildren;
          }
          function useFiber(fiber, pendingProps) {
            var clone3 = createWorkInProgress(fiber, pendingProps);
            clone3.index = 0;
            clone3.sibling = null;
            return clone3;
          }
          function placeChild(newFiber, lastPlacedIndex, newIndex) {
            newFiber.index = newIndex;
            if (!shouldTrackSideEffects) {
              newFiber.flags |= Forked;
              return lastPlacedIndex;
            }
            var current2 = newFiber.alternate;
            if (current2 !== null) {
              var oldIndex = current2.index;
              if (oldIndex < lastPlacedIndex) {
                newFiber.flags |= Placement;
                return lastPlacedIndex;
              } else {
                return oldIndex;
              }
            } else {
              newFiber.flags |= Placement;
              return lastPlacedIndex;
            }
          }
          function placeSingleChild(newFiber) {
            if (shouldTrackSideEffects && newFiber.alternate === null) {
              newFiber.flags |= Placement;
            }
            return newFiber;
          }
          function updateTextNode(returnFiber, current2, textContent, lanes) {
            if (current2 === null || current2.tag !== HostText) {
              var created = createFiberFromText(textContent, returnFiber.mode, lanes);
              created.return = returnFiber;
              return created;
            } else {
              var existing = useFiber(current2, textContent);
              existing.return = returnFiber;
              return existing;
            }
          }
          function updateElement(returnFiber, current2, element, lanes) {
            var elementType = element.type;
            if (elementType === REACT_FRAGMENT_TYPE) {
              return updateFragment2(returnFiber, current2, element.props.children, lanes, element.key);
            }
            if (current2 !== null) {
              if (current2.elementType === elementType || // Keep this check inline so it only runs on the false path:
              isCompatibleFamilyForHotReloading(current2, element) || // Lazy types should reconcile their resolved type.
              // We need to do this after the Hot Reloading check above,
              // because hot reloading has different semantics than prod because
              // it doesn't resuspend. So we can't let the call below suspend.
              typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type) {
                var existing = useFiber(current2, element.props);
                existing.ref = coerceRef(returnFiber, current2, element);
                existing.return = returnFiber;
                {
                  existing._debugSource = element._source;
                  existing._debugOwner = element._owner;
                }
                return existing;
              }
            }
            var created = createFiberFromElement(element, returnFiber.mode, lanes);
            created.ref = coerceRef(returnFiber, current2, element);
            created.return = returnFiber;
            return created;
          }
          function updatePortal(returnFiber, current2, portal, lanes) {
            if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) {
              var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
              created.return = returnFiber;
              return created;
            } else {
              var existing = useFiber(current2, portal.children || []);
              existing.return = returnFiber;
              return existing;
            }
          }
          function updateFragment2(returnFiber, current2, fragment, lanes, key) {
            if (current2 === null || current2.tag !== Fragment21) {
              var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
              created.return = returnFiber;
              return created;
            } else {
              var existing = useFiber(current2, fragment);
              existing.return = returnFiber;
              return existing;
            }
          }
          function createChild(returnFiber, newChild, lanes) {
            if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
              var created = createFiberFromText("" + newChild, returnFiber.mode, lanes);
              created.return = returnFiber;
              return created;
            }
            if (typeof newChild === "object" && newChild !== null) {
              switch (newChild.$$typeof) {
                case REACT_ELEMENT_TYPE: {
                  var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
                  _created.ref = coerceRef(returnFiber, null, newChild);
                  _created.return = returnFiber;
                  return _created;
                }
                case REACT_PORTAL_TYPE: {
                  var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
                  _created2.return = returnFiber;
                  return _created2;
                }
                case REACT_LAZY_TYPE: {
                  var payload = newChild._payload;
                  var init = newChild._init;
                  return createChild(returnFiber, init(payload), lanes);
                }
              }
              if (isArray2(newChild) || getIteratorFn(newChild)) {
                var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
                _created3.return = returnFiber;
                return _created3;
              }
              throwOnInvalidObjectType(returnFiber, newChild);
            }
            {
              if (typeof newChild === "function") {
                warnOnFunctionType(returnFiber);
              }
            }
            return null;
          }
          function updateSlot(returnFiber, oldFiber, newChild, lanes) {
            var key = oldFiber !== null ? oldFiber.key : null;
            if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
              if (key !== null) {
                return null;
              }
              return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
            }
            if (typeof newChild === "object" && newChild !== null) {
              switch (newChild.$$typeof) {
                case REACT_ELEMENT_TYPE: {
                  if (newChild.key === key) {
                    return updateElement(returnFiber, oldFiber, newChild, lanes);
                  } else {
                    return null;
                  }
                }
                case REACT_PORTAL_TYPE: {
                  if (newChild.key === key) {
                    return updatePortal(returnFiber, oldFiber, newChild, lanes);
                  } else {
                    return null;
                  }
                }
                case REACT_LAZY_TYPE: {
                  var payload = newChild._payload;
                  var init = newChild._init;
                  return updateSlot(returnFiber, oldFiber, init(payload), lanes);
                }
              }
              if (isArray2(newChild) || getIteratorFn(newChild)) {
                if (key !== null) {
                  return null;
                }
                return updateFragment2(returnFiber, oldFiber, newChild, lanes, null);
              }
              throwOnInvalidObjectType(returnFiber, newChild);
            }
            {
              if (typeof newChild === "function") {
                warnOnFunctionType(returnFiber);
              }
            }
            return null;
          }
          function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
            if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
              var matchedFiber = existingChildren.get(newIdx) || null;
              return updateTextNode(returnFiber, matchedFiber, "" + newChild, lanes);
            }
            if (typeof newChild === "object" && newChild !== null) {
              switch (newChild.$$typeof) {
                case REACT_ELEMENT_TYPE: {
                  var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
                  return updateElement(returnFiber, _matchedFiber, newChild, lanes);
                }
                case REACT_PORTAL_TYPE: {
                  var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
                  return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
                }
                case REACT_LAZY_TYPE:
                  var payload = newChild._payload;
                  var init = newChild._init;
                  return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes);
              }
              if (isArray2(newChild) || getIteratorFn(newChild)) {
                var _matchedFiber3 = existingChildren.get(newIdx) || null;
                return updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null);
              }
              throwOnInvalidObjectType(returnFiber, newChild);
            }
            {
              if (typeof newChild === "function") {
                warnOnFunctionType(returnFiber);
              }
            }
            return null;
          }
          function warnOnInvalidKey(child, knownKeys, returnFiber) {
            {
              if (typeof child !== "object" || child === null) {
                return knownKeys;
              }
              switch (child.$$typeof) {
                case REACT_ELEMENT_TYPE:
                case REACT_PORTAL_TYPE:
                  warnForMissingKey(child, returnFiber);
                  var key = child.key;
                  if (typeof key !== "string") {
                    break;
                  }
                  if (knownKeys === null) {
                    knownKeys = /* @__PURE__ */ new Set();
                    knownKeys.add(key);
                    break;
                  }
                  if (!knownKeys.has(key)) {
                    knownKeys.add(key);
                    break;
                  }
                  error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key);
                  break;
                case REACT_LAZY_TYPE:
                  var payload = child._payload;
                  var init = child._init;
                  warnOnInvalidKey(init(payload), knownKeys, returnFiber);
                  break;
              }
            }
            return knownKeys;
          }
          function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
            {
              var knownKeys = null;
              for (var i3 = 0; i3 < newChildren.length; i3++) {
                var child = newChildren[i3];
                knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
              }
            }
            var resultingFirstChild = null;
            var previousNewFiber = null;
            var oldFiber = currentFirstChild;
            var lastPlacedIndex = 0;
            var newIdx = 0;
            var nextOldFiber = null;
            for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
              if (oldFiber.index > newIdx) {
                nextOldFiber = oldFiber;
                oldFiber = null;
              } else {
                nextOldFiber = oldFiber.sibling;
              }
              var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
              if (newFiber === null) {
                if (oldFiber === null) {
                  oldFiber = nextOldFiber;
                }
                break;
              }
              if (shouldTrackSideEffects) {
                if (oldFiber && newFiber.alternate === null) {
                  deleteChild(returnFiber, oldFiber);
                }
              }
              lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = newFiber;
              } else {
                previousNewFiber.sibling = newFiber;
              }
              previousNewFiber = newFiber;
              oldFiber = nextOldFiber;
            }
            if (newIdx === newChildren.length) {
              deleteRemainingChildren(returnFiber, oldFiber);
              if (getIsHydrating()) {
                var numberOfForks = newIdx;
                pushTreeFork(returnFiber, numberOfForks);
              }
              return resultingFirstChild;
            }
            if (oldFiber === null) {
              for (; newIdx < newChildren.length; newIdx++) {
                var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
                if (_newFiber === null) {
                  continue;
                }
                lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
                if (previousNewFiber === null) {
                  resultingFirstChild = _newFiber;
                } else {
                  previousNewFiber.sibling = _newFiber;
                }
                previousNewFiber = _newFiber;
              }
              if (getIsHydrating()) {
                var _numberOfForks = newIdx;
                pushTreeFork(returnFiber, _numberOfForks);
              }
              return resultingFirstChild;
            }
            var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
            for (; newIdx < newChildren.length; newIdx++) {
              var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
              if (_newFiber2 !== null) {
                if (shouldTrackSideEffects) {
                  if (_newFiber2.alternate !== null) {
                    existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
                  }
                }
                lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
                if (previousNewFiber === null) {
                  resultingFirstChild = _newFiber2;
                } else {
                  previousNewFiber.sibling = _newFiber2;
                }
                previousNewFiber = _newFiber2;
              }
            }
            if (shouldTrackSideEffects) {
              existingChildren.forEach(function(child2) {
                return deleteChild(returnFiber, child2);
              });
            }
            if (getIsHydrating()) {
              var _numberOfForks2 = newIdx;
              pushTreeFork(returnFiber, _numberOfForks2);
            }
            return resultingFirstChild;
          }
          function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
            var iteratorFn = getIteratorFn(newChildrenIterable);
            if (typeof iteratorFn !== "function") {
              throw new Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
            }
            {
              if (typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag
              newChildrenIterable[Symbol.toStringTag] === "Generator") {
                if (!didWarnAboutGenerators) {
                  error("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers.");
                }
                didWarnAboutGenerators = true;
              }
              if (newChildrenIterable.entries === iteratorFn) {
                if (!didWarnAboutMaps) {
                  error("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
                }
                didWarnAboutMaps = true;
              }
              var _newChildren = iteratorFn.call(newChildrenIterable);
              if (_newChildren) {
                var knownKeys = null;
                var _step = _newChildren.next();
                for (; !_step.done; _step = _newChildren.next()) {
                  var child = _step.value;
                  knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
                }
              }
            }
            var newChildren = iteratorFn.call(newChildrenIterable);
            if (newChildren == null) {
              throw new Error("An iterable object provided no iterator.");
            }
            var resultingFirstChild = null;
            var previousNewFiber = null;
            var oldFiber = currentFirstChild;
            var lastPlacedIndex = 0;
            var newIdx = 0;
            var nextOldFiber = null;
            var step = newChildren.next();
            for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
              if (oldFiber.index > newIdx) {
                nextOldFiber = oldFiber;
                oldFiber = null;
              } else {
                nextOldFiber = oldFiber.sibling;
              }
              var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
              if (newFiber === null) {
                if (oldFiber === null) {
                  oldFiber = nextOldFiber;
                }
                break;
              }
              if (shouldTrackSideEffects) {
                if (oldFiber && newFiber.alternate === null) {
                  deleteChild(returnFiber, oldFiber);
                }
              }
              lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = newFiber;
              } else {
                previousNewFiber.sibling = newFiber;
              }
              previousNewFiber = newFiber;
              oldFiber = nextOldFiber;
            }
            if (step.done) {
              deleteRemainingChildren(returnFiber, oldFiber);
              if (getIsHydrating()) {
                var numberOfForks = newIdx;
                pushTreeFork(returnFiber, numberOfForks);
              }
              return resultingFirstChild;
            }
            if (oldFiber === null) {
              for (; !step.done; newIdx++, step = newChildren.next()) {
                var _newFiber3 = createChild(returnFiber, step.value, lanes);
                if (_newFiber3 === null) {
                  continue;
                }
                lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
                if (previousNewFiber === null) {
                  resultingFirstChild = _newFiber3;
                } else {
                  previousNewFiber.sibling = _newFiber3;
                }
                previousNewFiber = _newFiber3;
              }
              if (getIsHydrating()) {
                var _numberOfForks3 = newIdx;
                pushTreeFork(returnFiber, _numberOfForks3);
              }
              return resultingFirstChild;
            }
            var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
            for (; !step.done; newIdx++, step = newChildren.next()) {
              var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
              if (_newFiber4 !== null) {
                if (shouldTrackSideEffects) {
                  if (_newFiber4.alternate !== null) {
                    existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
                  }
                }
                lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
                if (previousNewFiber === null) {
                  resultingFirstChild = _newFiber4;
                } else {
                  previousNewFiber.sibling = _newFiber4;
                }
                previousNewFiber = _newFiber4;
              }
            }
            if (shouldTrackSideEffects) {
              existingChildren.forEach(function(child2) {
                return deleteChild(returnFiber, child2);
              });
            }
            if (getIsHydrating()) {
              var _numberOfForks4 = newIdx;
              pushTreeFork(returnFiber, _numberOfForks4);
            }
            return resultingFirstChild;
          }
          function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
            if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
              deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
              var existing = useFiber(currentFirstChild, textContent);
              existing.return = returnFiber;
              return existing;
            }
            deleteRemainingChildren(returnFiber, currentFirstChild);
            var created = createFiberFromText(textContent, returnFiber.mode, lanes);
            created.return = returnFiber;
            return created;
          }
          function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
            var key = element.key;
            var child = currentFirstChild;
            while (child !== null) {
              if (child.key === key) {
                var elementType = element.type;
                if (elementType === REACT_FRAGMENT_TYPE) {
                  if (child.tag === Fragment21) {
                    deleteRemainingChildren(returnFiber, child.sibling);
                    var existing = useFiber(child, element.props.children);
                    existing.return = returnFiber;
                    {
                      existing._debugSource = element._source;
                      existing._debugOwner = element._owner;
                    }
                    return existing;
                  }
                } else {
                  if (child.elementType === elementType || // Keep this check inline so it only runs on the false path:
                  isCompatibleFamilyForHotReloading(child, element) || // Lazy types should reconcile their resolved type.
                  // We need to do this after the Hot Reloading check above,
                  // because hot reloading has different semantics than prod because
                  // it doesn't resuspend. So we can't let the call below suspend.
                  typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
                    deleteRemainingChildren(returnFiber, child.sibling);
                    var _existing = useFiber(child, element.props);
                    _existing.ref = coerceRef(returnFiber, child, element);
                    _existing.return = returnFiber;
                    {
                      _existing._debugSource = element._source;
                      _existing._debugOwner = element._owner;
                    }
                    return _existing;
                  }
                }
                deleteRemainingChildren(returnFiber, child);
                break;
              } else {
                deleteChild(returnFiber, child);
              }
              child = child.sibling;
            }
            if (element.type === REACT_FRAGMENT_TYPE) {
              var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
              created.return = returnFiber;
              return created;
            } else {
              var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
              _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
              _created4.return = returnFiber;
              return _created4;
            }
          }
          function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
            var key = portal.key;
            var child = currentFirstChild;
            while (child !== null) {
              if (child.key === key) {
                if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
                  deleteRemainingChildren(returnFiber, child.sibling);
                  var existing = useFiber(child, portal.children || []);
                  existing.return = returnFiber;
                  return existing;
                } else {
                  deleteRemainingChildren(returnFiber, child);
                  break;
                }
              } else {
                deleteChild(returnFiber, child);
              }
              child = child.sibling;
            }
            var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
            created.return = returnFiber;
            return created;
          }
          function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) {
            var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
            if (isUnkeyedTopLevelFragment) {
              newChild = newChild.props.children;
            }
            if (typeof newChild === "object" && newChild !== null) {
              switch (newChild.$$typeof) {
                case REACT_ELEMENT_TYPE:
                  return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
                case REACT_PORTAL_TYPE:
                  return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
                case REACT_LAZY_TYPE:
                  var payload = newChild._payload;
                  var init = newChild._init;
                  return reconcileChildFibers2(returnFiber, currentFirstChild, init(payload), lanes);
              }
              if (isArray2(newChild)) {
                return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
              }
              if (getIteratorFn(newChild)) {
                return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
              }
              throwOnInvalidObjectType(returnFiber, newChild);
            }
            if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
              return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, lanes));
            }
            {
              if (typeof newChild === "function") {
                warnOnFunctionType(returnFiber);
              }
            }
            return deleteRemainingChildren(returnFiber, currentFirstChild);
          }
          return reconcileChildFibers2;
        }
        var reconcileChildFibers = ChildReconciler(true);
        var mountChildFibers = ChildReconciler(false);
        function cloneChildFibers(current2, workInProgress2) {
          if (current2 !== null && workInProgress2.child !== current2.child) {
            throw new Error("Resuming work not yet implemented.");
          }
          if (workInProgress2.child === null) {
            return;
          }
          var currentChild = workInProgress2.child;
          var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
          workInProgress2.child = newChild;
          newChild.return = workInProgress2;
          while (currentChild.sibling !== null) {
            currentChild = currentChild.sibling;
            newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
            newChild.return = workInProgress2;
          }
          newChild.sibling = null;
        }
        function resetChildFibers(workInProgress2, lanes) {
          var child = workInProgress2.child;
          while (child !== null) {
            resetWorkInProgress(child, lanes);
            child = child.sibling;
          }
        }
        var NO_CONTEXT = {};
        var contextStackCursor$1 = createCursor(NO_CONTEXT);
        var contextFiberStackCursor = createCursor(NO_CONTEXT);
        var rootInstanceStackCursor = createCursor(NO_CONTEXT);
        function requiredContext(c4) {
          if (c4 === NO_CONTEXT) {
            throw new Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
          }
          return c4;
        }
        function getRootHostContainer() {
          var rootInstance = requiredContext(rootInstanceStackCursor.current);
          return rootInstance;
        }
        function pushHostContainer(fiber, nextRootInstance) {
          push3(rootInstanceStackCursor, nextRootInstance, fiber);
          push3(contextFiberStackCursor, fiber, fiber);
          push3(contextStackCursor$1, NO_CONTEXT, fiber);
          var nextRootContext = getRootHostContext(nextRootInstance);
          pop(contextStackCursor$1, fiber);
          push3(contextStackCursor$1, nextRootContext, fiber);
        }
        function popHostContainer(fiber) {
          pop(contextStackCursor$1, fiber);
          pop(contextFiberStackCursor, fiber);
          pop(rootInstanceStackCursor, fiber);
        }
        function getHostContext() {
          var context = requiredContext(contextStackCursor$1.current);
          return context;
        }
        function pushHostContext(fiber) {
          var rootInstance = requiredContext(rootInstanceStackCursor.current);
          var context = requiredContext(contextStackCursor$1.current);
          var nextContext = getChildHostContext(context, fiber.type);
          if (context === nextContext) {
            return;
          }
          push3(contextFiberStackCursor, fiber, fiber);
          push3(contextStackCursor$1, nextContext, fiber);
        }
        function popHostContext(fiber) {
          if (contextFiberStackCursor.current !== fiber) {
            return;
          }
          pop(contextStackCursor$1, fiber);
          pop(contextFiberStackCursor, fiber);
        }
        var DefaultSuspenseContext = 0;
        var SubtreeSuspenseContextMask = 1;
        var InvisibleParentSuspenseContext = 1;
        var ForceSuspenseFallback = 2;
        var suspenseStackCursor = createCursor(DefaultSuspenseContext);
        function hasSuspenseContext(parentContext, flag) {
          return (parentContext & flag) !== 0;
        }
        function setDefaultShallowSuspenseContext(parentContext) {
          return parentContext & SubtreeSuspenseContextMask;
        }
        function setShallowSuspenseContext(parentContext, shallowContext) {
          return parentContext & SubtreeSuspenseContextMask | shallowContext;
        }
        function addSubtreeSuspenseContext(parentContext, subtreeContext) {
          return parentContext | subtreeContext;
        }
        function pushSuspenseContext(fiber, newContext) {
          push3(suspenseStackCursor, newContext, fiber);
        }
        function popSuspenseContext(fiber) {
          pop(suspenseStackCursor, fiber);
        }
        function shouldCaptureSuspense(workInProgress2, hasInvisibleParent) {
          var nextState = workInProgress2.memoizedState;
          if (nextState !== null) {
            if (nextState.dehydrated !== null) {
              return true;
            }
            return false;
          }
          var props = workInProgress2.memoizedProps;
          {
            return true;
          }
        }
        function findFirstSuspended(row) {
          var node = row;
          while (node !== null) {
            if (node.tag === SuspenseComponent) {
              var state = node.memoizedState;
              if (state !== null) {
                var dehydrated = state.dehydrated;
                if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
                  return node;
                }
              }
            } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
            // keep track of whether it suspended or not.
            node.memoizedProps.revealOrder !== void 0) {
              var didSuspend = (node.flags & DidCapture) !== NoFlags;
              if (didSuspend) {
                return node;
              }
            } else if (node.child !== null) {
              node.child.return = node;
              node = node.child;
              continue;
            }
            if (node === row) {
              return null;
            }
            while (node.sibling === null) {
              if (node.return === null || node.return === row) {
                return null;
              }
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
          return null;
        }
        var NoFlags$1 = (
          /*   */
          0
        );
        var HasEffect = (
          /* */
          1
        );
        var Insertion = (
          /*  */
          2
        );
        var Layout = (
          /*    */
          4
        );
        var Passive$1 = (
          /*   */
          8
        );
        var workInProgressSources = [];
        function resetWorkInProgressVersions() {
          for (var i3 = 0; i3 < workInProgressSources.length; i3++) {
            var mutableSource = workInProgressSources[i3];
            {
              mutableSource._workInProgressVersionPrimary = null;
            }
          }
          workInProgressSources.length = 0;
        }
        function registerMutableSourceForHydration(root3, mutableSource) {
          var getVersion2 = mutableSource._getVersion;
          var version2 = getVersion2(mutableSource._source);
          if (root3.mutableSourceEagerHydrationData == null) {
            root3.mutableSourceEagerHydrationData = [mutableSource, version2];
          } else {
            root3.mutableSourceEagerHydrationData.push(mutableSource, version2);
          }
        }
        var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
        var didWarnAboutMismatchedHooksForComponent;
        var didWarnUncachedGetSnapshot;
        {
          didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
        }
        var renderLanes = NoLanes;
        var currentlyRenderingFiber$1 = null;
        var currentHook = null;
        var workInProgressHook = null;
        var didScheduleRenderPhaseUpdate = false;
        var didScheduleRenderPhaseUpdateDuringThisPass = false;
        var localIdCounter = 0;
        var globalClientIdCounter = 0;
        var RE_RENDER_LIMIT = 25;
        var currentHookNameInDev = null;
        var hookTypesDev = null;
        var hookTypesUpdateIndexDev = -1;
        var ignorePreviousDependencies = false;
        function mountHookTypesDev() {
          {
            var hookName = currentHookNameInDev;
            if (hookTypesDev === null) {
              hookTypesDev = [hookName];
            } else {
              hookTypesDev.push(hookName);
            }
          }
        }
        function updateHookTypesDev() {
          {
            var hookName = currentHookNameInDev;
            if (hookTypesDev !== null) {
              hookTypesUpdateIndexDev++;
              if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
                warnOnHookMismatchInDev(hookName);
              }
            }
          }
        }
        function checkDepsAreArrayDev(deps) {
          {
            if (deps !== void 0 && deps !== null && !isArray2(deps)) {
              error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps);
            }
          }
        }
        function warnOnHookMismatchInDev(currentHookName) {
          {
            var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);
            if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
              didWarnAboutMismatchedHooksForComponent.add(componentName);
              if (hookTypesDev !== null) {
                var table = "";
                var secondColumnStart = 30;
                for (var i3 = 0; i3 <= hookTypesUpdateIndexDev; i3++) {
                  var oldHookName = hookTypesDev[i3];
                  var newHookName = i3 === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
                  var row = i3 + 1 + ". " + oldHookName;
                  while (row.length < secondColumnStart) {
                    row += " ";
                  }
                  row += newHookName + "\n";
                  table += row;
                }
                error("React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", componentName, table);
              }
            }
          }
        }
        function throwInvalidHookError() {
          throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
        }
        function areHookInputsEqual(nextDeps, prevDeps) {
          {
            if (ignorePreviousDependencies) {
              return false;
            }
          }
          if (prevDeps === null) {
            {
              error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev);
            }
            return false;
          }
          {
            if (nextDeps.length !== prevDeps.length) {
              error("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s", currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]");
            }
          }
          for (var i3 = 0; i3 < prevDeps.length && i3 < nextDeps.length; i3++) {
            if (objectIs(nextDeps[i3], prevDeps[i3])) {
              continue;
            }
            return false;
          }
          return true;
        }
        function renderWithHooks(current2, workInProgress2, Component2, props, secondArg, nextRenderLanes) {
          renderLanes = nextRenderLanes;
          currentlyRenderingFiber$1 = workInProgress2;
          {
            hookTypesDev = current2 !== null ? current2._debugHookTypes : null;
            hookTypesUpdateIndexDev = -1;
            ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type;
          }
          workInProgress2.memoizedState = null;
          workInProgress2.updateQueue = null;
          workInProgress2.lanes = NoLanes;
          {
            if (current2 !== null && current2.memoizedState !== null) {
              ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
            } else if (hookTypesDev !== null) {
              ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
            } else {
              ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
            }
          }
          var children = Component2(props, secondArg);
          if (didScheduleRenderPhaseUpdateDuringThisPass) {
            var numberOfReRenders = 0;
            do {
              didScheduleRenderPhaseUpdateDuringThisPass = false;
              localIdCounter = 0;
              if (numberOfReRenders >= RE_RENDER_LIMIT) {
                throw new Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
              }
              numberOfReRenders += 1;
              {
                ignorePreviousDependencies = false;
              }
              currentHook = null;
              workInProgressHook = null;
              workInProgress2.updateQueue = null;
              {
                hookTypesUpdateIndexDev = -1;
              }
              ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV;
              children = Component2(props, secondArg);
            } while (didScheduleRenderPhaseUpdateDuringThisPass);
          }
          ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
          {
            workInProgress2._debugHookTypes = hookTypesDev;
          }
          var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
          renderLanes = NoLanes;
          currentlyRenderingFiber$1 = null;
          currentHook = null;
          workInProgressHook = null;
          {
            currentHookNameInDev = null;
            hookTypesDev = null;
            hookTypesUpdateIndexDev = -1;
            if (current2 !== null && (current2.flags & StaticMask) !== (workInProgress2.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
            // and creates false positives. To make this work in legacy mode, we'd
            // need to mark fibers that commit in an incomplete state, somehow. For
            // now I'll disable the warning that most of the bugs that would trigger
            // it are either exclusive to concurrent mode or exist in both.
            (current2.mode & ConcurrentMode) !== NoMode) {
              error("Internal React error: Expected static flag was missing. Please notify the React team.");
            }
          }
          didScheduleRenderPhaseUpdate = false;
          if (didRenderTooFewHooks) {
            throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
          }
          return children;
        }
        function checkDidRenderIdHook() {
          var didRenderIdHook = localIdCounter !== 0;
          localIdCounter = 0;
          return didRenderIdHook;
        }
        function bailoutHooks(current2, workInProgress2, lanes) {
          workInProgress2.updateQueue = current2.updateQueue;
          if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
            workInProgress2.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update);
          } else {
            workInProgress2.flags &= ~(Passive | Update);
          }
          current2.lanes = removeLanes(current2.lanes, lanes);
        }
        function resetHooksAfterThrow() {
          ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
          if (didScheduleRenderPhaseUpdate) {
            var hook = currentlyRenderingFiber$1.memoizedState;
            while (hook !== null) {
              var queue2 = hook.queue;
              if (queue2 !== null) {
                queue2.pending = null;
              }
              hook = hook.next;
            }
            didScheduleRenderPhaseUpdate = false;
          }
          renderLanes = NoLanes;
          currentlyRenderingFiber$1 = null;
          currentHook = null;
          workInProgressHook = null;
          {
            hookTypesDev = null;
            hookTypesUpdateIndexDev = -1;
            currentHookNameInDev = null;
            isUpdatingOpaqueValueInRenderPhase = false;
          }
          didScheduleRenderPhaseUpdateDuringThisPass = false;
          localIdCounter = 0;
        }
        function mountWorkInProgressHook() {
          var hook = {
            memoizedState: null,
            baseState: null,
            baseQueue: null,
            queue: null,
            next: null
          };
          if (workInProgressHook === null) {
            currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
          } else {
            workInProgressHook = workInProgressHook.next = hook;
          }
          return workInProgressHook;
        }
        function updateWorkInProgressHook() {
          var nextCurrentHook;
          if (currentHook === null) {
            var current2 = currentlyRenderingFiber$1.alternate;
            if (current2 !== null) {
              nextCurrentHook = current2.memoizedState;
            } else {
              nextCurrentHook = null;
            }
          } else {
            nextCurrentHook = currentHook.next;
          }
          var nextWorkInProgressHook;
          if (workInProgressHook === null) {
            nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
          } else {
            nextWorkInProgressHook = workInProgressHook.next;
          }
          if (nextWorkInProgressHook !== null) {
            workInProgressHook = nextWorkInProgressHook;
            nextWorkInProgressHook = workInProgressHook.next;
            currentHook = nextCurrentHook;
          } else {
            if (nextCurrentHook === null) {
              throw new Error("Rendered more hooks than during the previous render.");
            }
            currentHook = nextCurrentHook;
            var newHook = {
              memoizedState: currentHook.memoizedState,
              baseState: currentHook.baseState,
              baseQueue: currentHook.baseQueue,
              queue: currentHook.queue,
              next: null
            };
            if (workInProgressHook === null) {
              currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
            } else {
              workInProgressHook = workInProgressHook.next = newHook;
            }
          }
          return workInProgressHook;
        }
        function createFunctionComponentUpdateQueue() {
          return {
            lastEffect: null,
            stores: null
          };
        }
        function basicStateReducer(state, action) {
          return typeof action === "function" ? action(state) : action;
        }
        function mountReducer(reducer2, initialArg, init) {
          var hook = mountWorkInProgressHook();
          var initialState2;
          if (init !== void 0) {
            initialState2 = init(initialArg);
          } else {
            initialState2 = initialArg;
          }
          hook.memoizedState = hook.baseState = initialState2;
          var queue2 = {
            pending: null,
            interleaved: null,
            lanes: NoLanes,
            dispatch: null,
            lastRenderedReducer: reducer2,
            lastRenderedState: initialState2
          };
          hook.queue = queue2;
          var dispatch = queue2.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue2);
          return [hook.memoizedState, dispatch];
        }
        function updateReducer(reducer2, initialArg, init) {
          var hook = updateWorkInProgressHook();
          var queue2 = hook.queue;
          if (queue2 === null) {
            throw new Error("Should have a queue. This is likely a bug in React. Please file an issue.");
          }
          queue2.lastRenderedReducer = reducer2;
          var current2 = currentHook;
          var baseQueue = current2.baseQueue;
          var pendingQueue = queue2.pending;
          if (pendingQueue !== null) {
            if (baseQueue !== null) {
              var baseFirst = baseQueue.next;
              var pendingFirst = pendingQueue.next;
              baseQueue.next = pendingFirst;
              pendingQueue.next = baseFirst;
            }
            {
              if (current2.baseQueue !== baseQueue) {
                error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React.");
              }
            }
            current2.baseQueue = baseQueue = pendingQueue;
            queue2.pending = null;
          }
          if (baseQueue !== null) {
            var first = baseQueue.next;
            var newState = current2.baseState;
            var newBaseState = null;
            var newBaseQueueFirst = null;
            var newBaseQueueLast = null;
            var update2 = first;
            do {
              var updateLane = update2.lane;
              if (!isSubsetOfLanes(renderLanes, updateLane)) {
                var clone3 = {
                  lane: updateLane,
                  action: update2.action,
                  hasEagerState: update2.hasEagerState,
                  eagerState: update2.eagerState,
                  next: null
                };
                if (newBaseQueueLast === null) {
                  newBaseQueueFirst = newBaseQueueLast = clone3;
                  newBaseState = newState;
                } else {
                  newBaseQueueLast = newBaseQueueLast.next = clone3;
                }
                currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
                markSkippedUpdateLanes(updateLane);
              } else {
                if (newBaseQueueLast !== null) {
                  var _clone = {
                    // This update is going to be committed so we never want uncommit
                    // it. Using NoLane works because 0 is a subset of all bitmasks, so
                    // this will never be skipped by the check above.
                    lane: NoLane,
                    action: update2.action,
                    hasEagerState: update2.hasEagerState,
                    eagerState: update2.eagerState,
                    next: null
                  };
                  newBaseQueueLast = newBaseQueueLast.next = _clone;
                }
                if (update2.hasEagerState) {
                  newState = update2.eagerState;
                } else {
                  var action = update2.action;
                  newState = reducer2(newState, action);
                }
              }
              update2 = update2.next;
            } while (update2 !== null && update2 !== first);
            if (newBaseQueueLast === null) {
              newBaseState = newState;
            } else {
              newBaseQueueLast.next = newBaseQueueFirst;
            }
            if (!objectIs(newState, hook.memoizedState)) {
              markWorkInProgressReceivedUpdate();
            }
            hook.memoizedState = newState;
            hook.baseState = newBaseState;
            hook.baseQueue = newBaseQueueLast;
            queue2.lastRenderedState = newState;
          }
          var lastInterleaved = queue2.interleaved;
          if (lastInterleaved !== null) {
            var interleaved = lastInterleaved;
            do {
              var interleavedLane = interleaved.lane;
              currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
              markSkippedUpdateLanes(interleavedLane);
              interleaved = interleaved.next;
            } while (interleaved !== lastInterleaved);
          } else if (baseQueue === null) {
            queue2.lanes = NoLanes;
          }
          var dispatch = queue2.dispatch;
          return [hook.memoizedState, dispatch];
        }
        function rerenderReducer(reducer2, initialArg, init) {
          var hook = updateWorkInProgressHook();
          var queue2 = hook.queue;
          if (queue2 === null) {
            throw new Error("Should have a queue. This is likely a bug in React. Please file an issue.");
          }
          queue2.lastRenderedReducer = reducer2;
          var dispatch = queue2.dispatch;
          var lastRenderPhaseUpdate = queue2.pending;
          var newState = hook.memoizedState;
          if (lastRenderPhaseUpdate !== null) {
            queue2.pending = null;
            var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
            var update2 = firstRenderPhaseUpdate;
            do {
              var action = update2.action;
              newState = reducer2(newState, action);
              update2 = update2.next;
            } while (update2 !== firstRenderPhaseUpdate);
            if (!objectIs(newState, hook.memoizedState)) {
              markWorkInProgressReceivedUpdate();
            }
            hook.memoizedState = newState;
            if (hook.baseQueue === null) {
              hook.baseState = newState;
            }
            queue2.lastRenderedState = newState;
          }
          return [newState, dispatch];
        }
        function mountMutableSource(source, getSnapshot, subscribe) {
          {
            return void 0;
          }
        }
        function updateMutableSource(source, getSnapshot, subscribe) {
          {
            return void 0;
          }
        }
        function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
          var fiber = currentlyRenderingFiber$1;
          var hook = mountWorkInProgressHook();
          var nextSnapshot;
          var isHydrating2 = getIsHydrating();
          if (isHydrating2) {
            if (getServerSnapshot === void 0) {
              throw new Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
            }
            nextSnapshot = getServerSnapshot();
            {
              if (!didWarnUncachedGetSnapshot) {
                if (nextSnapshot !== getServerSnapshot()) {
                  error("The result of getServerSnapshot should be cached to avoid an infinite loop");
                  didWarnUncachedGetSnapshot = true;
                }
              }
            }
          } else {
            nextSnapshot = getSnapshot();
            {
              if (!didWarnUncachedGetSnapshot) {
                var cachedSnapshot = getSnapshot();
                if (!objectIs(nextSnapshot, cachedSnapshot)) {
                  error("The result of getSnapshot should be cached to avoid an infinite loop");
                  didWarnUncachedGetSnapshot = true;
                }
              }
            }
            var root3 = getWorkInProgressRoot();
            if (root3 === null) {
              throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
            }
            if (!includesBlockingLane(root3, renderLanes)) {
              pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
            }
          }
          hook.memoizedState = nextSnapshot;
          var inst = {
            value: nextSnapshot,
            getSnapshot
          };
          hook.queue = inst;
          mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
          fiber.flags |= Passive;
          pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null);
          return nextSnapshot;
        }
        function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
          var fiber = currentlyRenderingFiber$1;
          var hook = updateWorkInProgressHook();
          var nextSnapshot = getSnapshot();
          {
            if (!didWarnUncachedGetSnapshot) {
              var cachedSnapshot = getSnapshot();
              if (!objectIs(nextSnapshot, cachedSnapshot)) {
                error("The result of getSnapshot should be cached to avoid an infinite loop");
                didWarnUncachedGetSnapshot = true;
              }
            }
          }
          var prevSnapshot = hook.memoizedState;
          var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);
          if (snapshotChanged) {
            hook.memoizedState = nextSnapshot;
            markWorkInProgressReceivedUpdate();
          }
          var inst = hook.queue;
          updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
          if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
          // checking whether we scheduled a subscription effect above.
          workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
            fiber.flags |= Passive;
            pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null);
            var root3 = getWorkInProgressRoot();
            if (root3 === null) {
              throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
            }
            if (!includesBlockingLane(root3, renderLanes)) {
              pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
            }
          }
          return nextSnapshot;
        }
        function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
          fiber.flags |= StoreConsistency;
          var check = {
            getSnapshot,
            value: renderedSnapshot
          };
          var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
          if (componentUpdateQueue === null) {
            componentUpdateQueue = createFunctionComponentUpdateQueue();
            currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
            componentUpdateQueue.stores = [check];
          } else {
            var stores = componentUpdateQueue.stores;
            if (stores === null) {
              componentUpdateQueue.stores = [check];
            } else {
              stores.push(check);
            }
          }
        }
        function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
          inst.value = nextSnapshot;
          inst.getSnapshot = getSnapshot;
          if (checkIfSnapshotChanged(inst)) {
            forceStoreRerender(fiber);
          }
        }
        function subscribeToStore(fiber, inst, subscribe) {
          var handleStoreChange = function() {
            if (checkIfSnapshotChanged(inst)) {
              forceStoreRerender(fiber);
            }
          };
          return subscribe(handleStoreChange);
        }
        function checkIfSnapshotChanged(inst) {
          var latestGetSnapshot = inst.getSnapshot;
          var prevValue = inst.value;
          try {
            var nextValue = latestGetSnapshot();
            return !objectIs(prevValue, nextValue);
          } catch (error2) {
            return true;
          }
        }
        function forceStoreRerender(fiber) {
          var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
          if (root3 !== null) {
            scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
          }
        }
        function mountState(initialState2) {
          var hook = mountWorkInProgressHook();
          if (typeof initialState2 === "function") {
            initialState2 = initialState2();
          }
          hook.memoizedState = hook.baseState = initialState2;
          var queue2 = {
            pending: null,
            interleaved: null,
            lanes: NoLanes,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: initialState2
          };
          hook.queue = queue2;
          var dispatch = queue2.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue2);
          return [hook.memoizedState, dispatch];
        }
        function updateState(initialState2) {
          return updateReducer(basicStateReducer);
        }
        function rerenderState(initialState2) {
          return rerenderReducer(basicStateReducer);
        }
        function pushEffect(tag, create9, destroy, deps) {
          var effect = {
            tag,
            create: create9,
            destroy,
            deps,
            // Circular
            next: null
          };
          var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
          if (componentUpdateQueue === null) {
            componentUpdateQueue = createFunctionComponentUpdateQueue();
            currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
            componentUpdateQueue.lastEffect = effect.next = effect;
          } else {
            var lastEffect = componentUpdateQueue.lastEffect;
            if (lastEffect === null) {
              componentUpdateQueue.lastEffect = effect.next = effect;
            } else {
              var firstEffect = lastEffect.next;
              lastEffect.next = effect;
              effect.next = firstEffect;
              componentUpdateQueue.lastEffect = effect;
            }
          }
          return effect;
        }
        function mountRef(initialValue) {
          var hook = mountWorkInProgressHook();
          {
            var _ref2 = {
              current: initialValue
            };
            hook.memoizedState = _ref2;
            return _ref2;
          }
        }
        function updateRef(initialValue) {
          var hook = updateWorkInProgressHook();
          return hook.memoizedState;
        }
        function mountEffectImpl(fiberFlags, hookFlags, create9, deps) {
          var hook = mountWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          currentlyRenderingFiber$1.flags |= fiberFlags;
          hook.memoizedState = pushEffect(HasEffect | hookFlags, create9, void 0, nextDeps);
        }
        function updateEffectImpl(fiberFlags, hookFlags, create9, deps) {
          var hook = updateWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          var destroy = void 0;
          if (currentHook !== null) {
            var prevEffect = currentHook.memoizedState;
            destroy = prevEffect.destroy;
            if (nextDeps !== null) {
              var prevDeps = prevEffect.deps;
              if (areHookInputsEqual(nextDeps, prevDeps)) {
                hook.memoizedState = pushEffect(hookFlags, create9, destroy, nextDeps);
                return;
              }
            }
          }
          currentlyRenderingFiber$1.flags |= fiberFlags;
          hook.memoizedState = pushEffect(HasEffect | hookFlags, create9, destroy, nextDeps);
        }
        function mountEffect(create9, deps) {
          if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
            return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create9, deps);
          } else {
            return mountEffectImpl(Passive | PassiveStatic, Passive$1, create9, deps);
          }
        }
        function updateEffect(create9, deps) {
          return updateEffectImpl(Passive, Passive$1, create9, deps);
        }
        function mountInsertionEffect(create9, deps) {
          return mountEffectImpl(Update, Insertion, create9, deps);
        }
        function updateInsertionEffect(create9, deps) {
          return updateEffectImpl(Update, Insertion, create9, deps);
        }
        function mountLayoutEffect(create9, deps) {
          var fiberFlags = Update;
          {
            fiberFlags |= LayoutStatic;
          }
          if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
            fiberFlags |= MountLayoutDev;
          }
          return mountEffectImpl(fiberFlags, Layout, create9, deps);
        }
        function updateLayoutEffect(create9, deps) {
          return updateEffectImpl(Update, Layout, create9, deps);
        }
        function imperativeHandleEffect(create9, ref) {
          if (typeof ref === "function") {
            var refCallback = ref;
            var _inst = create9();
            refCallback(_inst);
            return function() {
              refCallback(null);
            };
          } else if (ref !== null && ref !== void 0) {
            var refObject = ref;
            {
              if (!refObject.hasOwnProperty("current")) {
                error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(refObject).join(", ") + "}");
              }
            }
            var _inst2 = create9();
            refObject.current = _inst2;
            return function() {
              refObject.current = null;
            };
          }
        }
        function mountImperativeHandle(ref, create9, deps) {
          {
            if (typeof create9 !== "function") {
              error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create9 !== null ? typeof create9 : "null");
            }
          }
          var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null;
          var fiberFlags = Update;
          {
            fiberFlags |= LayoutStatic;
          }
          if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
            fiberFlags |= MountLayoutDev;
          }
          return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create9, ref), effectDeps);
        }
        function updateImperativeHandle(ref, create9, deps) {
          {
            if (typeof create9 !== "function") {
              error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create9 !== null ? typeof create9 : "null");
            }
          }
          var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null;
          return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create9, ref), effectDeps);
        }
        function mountDebugValue(value, formatterFn) {
        }
        var updateDebugValue = mountDebugValue;
        function mountCallback(callback, deps) {
          var hook = mountWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          hook.memoizedState = [callback, nextDeps];
          return callback;
        }
        function updateCallback(callback, deps) {
          var hook = updateWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          var prevState = hook.memoizedState;
          if (prevState !== null) {
            if (nextDeps !== null) {
              var prevDeps = prevState[1];
              if (areHookInputsEqual(nextDeps, prevDeps)) {
                return prevState[0];
              }
            }
          }
          hook.memoizedState = [callback, nextDeps];
          return callback;
        }
        function mountMemo(nextCreate, deps) {
          var hook = mountWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          var nextValue = nextCreate();
          hook.memoizedState = [nextValue, nextDeps];
          return nextValue;
        }
        function updateMemo(nextCreate, deps) {
          var hook = updateWorkInProgressHook();
          var nextDeps = deps === void 0 ? null : deps;
          var prevState = hook.memoizedState;
          if (prevState !== null) {
            if (nextDeps !== null) {
              var prevDeps = prevState[1];
              if (areHookInputsEqual(nextDeps, prevDeps)) {
                return prevState[0];
              }
            }
          }
          var nextValue = nextCreate();
          hook.memoizedState = [nextValue, nextDeps];
          return nextValue;
        }
        function mountDeferredValue(value) {
          var hook = mountWorkInProgressHook();
          hook.memoizedState = value;
          return value;
        }
        function updateDeferredValue(value) {
          var hook = updateWorkInProgressHook();
          var resolvedCurrentHook = currentHook;
          var prevValue = resolvedCurrentHook.memoizedState;
          return updateDeferredValueImpl(hook, prevValue, value);
        }
        function rerenderDeferredValue(value) {
          var hook = updateWorkInProgressHook();
          if (currentHook === null) {
            hook.memoizedState = value;
            return value;
          } else {
            var prevValue = currentHook.memoizedState;
            return updateDeferredValueImpl(hook, prevValue, value);
          }
        }
        function updateDeferredValueImpl(hook, prevValue, value) {
          var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);
          if (shouldDeferValue) {
            if (!objectIs(value, prevValue)) {
              var deferredLane = claimNextTransitionLane();
              currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
              markSkippedUpdateLanes(deferredLane);
              hook.baseState = true;
            }
            return prevValue;
          } else {
            if (hook.baseState) {
              hook.baseState = false;
              markWorkInProgressReceivedUpdate();
            }
            hook.memoizedState = value;
            return value;
          }
        }
        function startTransition(setPending, callback, options2) {
          var previousPriority = getCurrentUpdatePriority();
          setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
          setPending(true);
          var prevTransition = ReactCurrentBatchConfig$2.transition;
          ReactCurrentBatchConfig$2.transition = {};
          var currentTransition = ReactCurrentBatchConfig$2.transition;
          {
            ReactCurrentBatchConfig$2.transition._updatedFibers = /* @__PURE__ */ new Set();
          }
          try {
            setPending(false);
            callback();
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig$2.transition = prevTransition;
            {
              if (prevTransition === null && currentTransition._updatedFibers) {
                var updatedFibersCount = currentTransition._updatedFibers.size;
                if (updatedFibersCount > 10) {
                  warn2("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.");
                }
                currentTransition._updatedFibers.clear();
              }
            }
          }
        }
        function mountTransition() {
          var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1];
          var start = startTransition.bind(null, setPending);
          var hook = mountWorkInProgressHook();
          hook.memoizedState = start;
          return [isPending, start];
        }
        function updateTransition() {
          var _updateState = updateState(), isPending = _updateState[0];
          var hook = updateWorkInProgressHook();
          var start = hook.memoizedState;
          return [isPending, start];
        }
        function rerenderTransition() {
          var _rerenderState = rerenderState(), isPending = _rerenderState[0];
          var hook = updateWorkInProgressHook();
          var start = hook.memoizedState;
          return [isPending, start];
        }
        var isUpdatingOpaqueValueInRenderPhase = false;
        function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
          {
            return isUpdatingOpaqueValueInRenderPhase;
          }
        }
        function mountId() {
          var hook = mountWorkInProgressHook();
          var root3 = getWorkInProgressRoot();
          var identifierPrefix = root3.identifierPrefix;
          var id;
          if (getIsHydrating()) {
            var treeId = getTreeId();
            id = ":" + identifierPrefix + "R" + treeId;
            var localId = localIdCounter++;
            if (localId > 0) {
              id += "H" + localId.toString(32);
            }
            id += ":";
          } else {
            var globalClientId = globalClientIdCounter++;
            id = ":" + identifierPrefix + "r" + globalClientId.toString(32) + ":";
          }
          hook.memoizedState = id;
          return id;
        }
        function updateId() {
          var hook = updateWorkInProgressHook();
          var id = hook.memoizedState;
          return id;
        }
        function dispatchReducerAction(fiber, queue2, action) {
          {
            if (typeof arguments[3] === "function") {
              error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
            }
          }
          var lane = requestUpdateLane(fiber);
          var update2 = {
            lane,
            action,
            hasEagerState: false,
            eagerState: null,
            next: null
          };
          if (isRenderPhaseUpdate(fiber)) {
            enqueueRenderPhaseUpdate(queue2, update2);
          } else {
            var root3 = enqueueConcurrentHookUpdate(fiber, queue2, update2, lane);
            if (root3 !== null) {
              var eventTime = requestEventTime();
              scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
              entangleTransitionUpdate(root3, queue2, lane);
            }
          }
          markUpdateInDevTools(fiber, lane);
        }
        function dispatchSetState(fiber, queue2, action) {
          {
            if (typeof arguments[3] === "function") {
              error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
            }
          }
          var lane = requestUpdateLane(fiber);
          var update2 = {
            lane,
            action,
            hasEagerState: false,
            eagerState: null,
            next: null
          };
          if (isRenderPhaseUpdate(fiber)) {
            enqueueRenderPhaseUpdate(queue2, update2);
          } else {
            var alternate = fiber.alternate;
            if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
              var lastRenderedReducer = queue2.lastRenderedReducer;
              if (lastRenderedReducer !== null) {
                var prevDispatcher;
                {
                  prevDispatcher = ReactCurrentDispatcher$1.current;
                  ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
                }
                try {
                  var currentState = queue2.lastRenderedState;
                  var eagerState = lastRenderedReducer(currentState, action);
                  update2.hasEagerState = true;
                  update2.eagerState = eagerState;
                  if (objectIs(eagerState, currentState)) {
                    enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue2, update2, lane);
                    return;
                  }
                } catch (error2) {
                } finally {
                  {
                    ReactCurrentDispatcher$1.current = prevDispatcher;
                  }
                }
              }
            }
            var root3 = enqueueConcurrentHookUpdate(fiber, queue2, update2, lane);
            if (root3 !== null) {
              var eventTime = requestEventTime();
              scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
              entangleTransitionUpdate(root3, queue2, lane);
            }
          }
          markUpdateInDevTools(fiber, lane);
        }
        function isRenderPhaseUpdate(fiber) {
          var alternate = fiber.alternate;
          return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
        }
        function enqueueRenderPhaseUpdate(queue2, update2) {
          didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
          var pending = queue2.pending;
          if (pending === null) {
            update2.next = update2;
          } else {
            update2.next = pending.next;
            pending.next = update2;
          }
          queue2.pending = update2;
        }
        function entangleTransitionUpdate(root3, queue2, lane) {
          if (isTransitionLane(lane)) {
            var queueLanes = queue2.lanes;
            queueLanes = intersectLanes(queueLanes, root3.pendingLanes);
            var newQueueLanes = mergeLanes(queueLanes, lane);
            queue2.lanes = newQueueLanes;
            markRootEntangled(root3, newQueueLanes);
          }
        }
        function markUpdateInDevTools(fiber, lane, action) {
          {
            markStateUpdateScheduled(fiber, lane);
          }
        }
        var ContextOnlyDispatcher = {
          readContext,
          useCallback: throwInvalidHookError,
          useContext: throwInvalidHookError,
          useEffect: throwInvalidHookError,
          useImperativeHandle: throwInvalidHookError,
          useInsertionEffect: throwInvalidHookError,
          useLayoutEffect: throwInvalidHookError,
          useMemo: throwInvalidHookError,
          useReducer: throwInvalidHookError,
          useRef: throwInvalidHookError,
          useState: throwInvalidHookError,
          useDebugValue: throwInvalidHookError,
          useDeferredValue: throwInvalidHookError,
          useTransition: throwInvalidHookError,
          useMutableSource: throwInvalidHookError,
          useSyncExternalStore: throwInvalidHookError,
          useId: throwInvalidHookError,
          unstable_isNewReconciler: enableNewReconciler
        };
        var HooksDispatcherOnMountInDEV = null;
        var HooksDispatcherOnMountWithHookTypesInDEV = null;
        var HooksDispatcherOnUpdateInDEV = null;
        var HooksDispatcherOnRerenderInDEV = null;
        var InvalidNestedHooksDispatcherOnMountInDEV = null;
        var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
        var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
        {
          var warnInvalidContextAccess = function() {
            error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
          };
          var warnInvalidHookAccess = function() {
            error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks");
          };
          HooksDispatcherOnMountInDEV = {
            readContext: function(context) {
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              return mountCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              mountHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              return mountEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              return mountImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              return mountInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              return mountLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              mountHookTypesDev();
              checkDepsAreArrayDev(deps);
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              mountHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              mountHookTypesDev();
              return mountRef(initialValue);
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              mountHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              mountHookTypesDev();
              return mountDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              mountHookTypesDev();
              return mountDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              mountHookTypesDev();
              return mountTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              mountHookTypesDev();
              return mountMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              mountHookTypesDev();
              return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              mountHookTypesDev();
              return mountId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          HooksDispatcherOnMountWithHookTypesInDEV = {
            readContext: function(context) {
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              updateHookTypesDev();
              return mountCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              updateHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              updateHookTypesDev();
              return mountEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              updateHookTypesDev();
              return mountImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              updateHookTypesDev();
              return mountInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              updateHookTypesDev();
              return mountLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              updateHookTypesDev();
              return mountRef(initialValue);
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              updateHookTypesDev();
              return mountDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              updateHookTypesDev();
              return mountDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              updateHookTypesDev();
              return mountTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              updateHookTypesDev();
              return mountMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              updateHookTypesDev();
              return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              updateHookTypesDev();
              return mountId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          HooksDispatcherOnUpdateInDEV = {
            readContext: function(context) {
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              updateHookTypesDev();
              return updateCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              updateHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              updateHookTypesDev();
              return updateEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              updateHookTypesDev();
              return updateImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              updateHookTypesDev();
              return updateInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              updateHookTypesDev();
              return updateLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              updateHookTypesDev();
              return updateRef();
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              updateHookTypesDev();
              return updateDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              updateHookTypesDev();
              return updateDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              updateHookTypesDev();
              return updateTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              updateHookTypesDev();
              return updateMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              updateHookTypesDev();
              return updateSyncExternalStore(subscribe, getSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              updateHookTypesDev();
              return updateId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          HooksDispatcherOnRerenderInDEV = {
            readContext: function(context) {
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              updateHookTypesDev();
              return updateCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              updateHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              updateHookTypesDev();
              return updateEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              updateHookTypesDev();
              return updateImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              updateHookTypesDev();
              return updateInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              updateHookTypesDev();
              return updateLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
              try {
                return updateMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
              try {
                return rerenderReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              updateHookTypesDev();
              return updateRef();
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
              try {
                return rerenderState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              updateHookTypesDev();
              return updateDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              updateHookTypesDev();
              return rerenderDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              updateHookTypesDev();
              return rerenderTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              updateHookTypesDev();
              return updateMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              updateHookTypesDev();
              return updateSyncExternalStore(subscribe, getSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              updateHookTypesDev();
              return updateId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          InvalidNestedHooksDispatcherOnMountInDEV = {
            readContext: function(context) {
              warnInvalidContextAccess();
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              warnInvalidHookAccess();
              mountHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              warnInvalidHookAccess();
              mountHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountRef(initialValue);
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              warnInvalidHookAccess();
              mountHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
              try {
                return mountState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              warnInvalidHookAccess();
              mountHookTypesDev();
              return mountId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          InvalidNestedHooksDispatcherOnUpdateInDEV = {
            readContext: function(context) {
              warnInvalidContextAccess();
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateRef();
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateSyncExternalStore(subscribe, getSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
          InvalidNestedHooksDispatcherOnRerenderInDEV = {
            readContext: function(context) {
              warnInvalidContextAccess();
              return readContext(context);
            },
            useCallback: function(callback, deps) {
              currentHookNameInDev = "useCallback";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateCallback(callback, deps);
            },
            useContext: function(context) {
              currentHookNameInDev = "useContext";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return readContext(context);
            },
            useEffect: function(create9, deps) {
              currentHookNameInDev = "useEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateEffect(create9, deps);
            },
            useImperativeHandle: function(ref, create9, deps) {
              currentHookNameInDev = "useImperativeHandle";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateImperativeHandle(ref, create9, deps);
            },
            useInsertionEffect: function(create9, deps) {
              currentHookNameInDev = "useInsertionEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateInsertionEffect(create9, deps);
            },
            useLayoutEffect: function(create9, deps) {
              currentHookNameInDev = "useLayoutEffect";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateLayoutEffect(create9, deps);
            },
            useMemo: function(create9, deps) {
              currentHookNameInDev = "useMemo";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return updateMemo(create9, deps);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useReducer: function(reducer2, initialArg, init) {
              currentHookNameInDev = "useReducer";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return rerenderReducer(reducer2, initialArg, init);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useRef: function(initialValue) {
              currentHookNameInDev = "useRef";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateRef();
            },
            useState: function(initialState2) {
              currentHookNameInDev = "useState";
              warnInvalidHookAccess();
              updateHookTypesDev();
              var prevDispatcher = ReactCurrentDispatcher$1.current;
              ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              try {
                return rerenderState(initialState2);
              } finally {
                ReactCurrentDispatcher$1.current = prevDispatcher;
              }
            },
            useDebugValue: function(value, formatterFn) {
              currentHookNameInDev = "useDebugValue";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateDebugValue();
            },
            useDeferredValue: function(value) {
              currentHookNameInDev = "useDeferredValue";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return rerenderDeferredValue(value);
            },
            useTransition: function() {
              currentHookNameInDev = "useTransition";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return rerenderTransition();
            },
            useMutableSource: function(source, getSnapshot, subscribe) {
              currentHookNameInDev = "useMutableSource";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateMutableSource();
            },
            useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
              currentHookNameInDev = "useSyncExternalStore";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateSyncExternalStore(subscribe, getSnapshot);
            },
            useId: function() {
              currentHookNameInDev = "useId";
              warnInvalidHookAccess();
              updateHookTypesDev();
              return updateId();
            },
            unstable_isNewReconciler: enableNewReconciler
          };
        }
        var now$1 = Scheduler.unstable_now;
        var commitTime = 0;
        var layoutEffectStartTime = -1;
        var profilerStartTime = -1;
        var passiveEffectStartTime = -1;
        var currentUpdateIsNested = false;
        var nestedUpdateScheduled = false;
        function isCurrentUpdateNested() {
          return currentUpdateIsNested;
        }
        function markNestedUpdateScheduled() {
          {
            nestedUpdateScheduled = true;
          }
        }
        function resetNestedUpdateFlag() {
          {
            currentUpdateIsNested = false;
            nestedUpdateScheduled = false;
          }
        }
        function syncNestedUpdateFlag() {
          {
            currentUpdateIsNested = nestedUpdateScheduled;
            nestedUpdateScheduled = false;
          }
        }
        function getCommitTime() {
          return commitTime;
        }
        function recordCommitTime() {
          commitTime = now$1();
        }
        function startProfilerTimer(fiber) {
          profilerStartTime = now$1();
          if (fiber.actualStartTime < 0) {
            fiber.actualStartTime = now$1();
          }
        }
        function stopProfilerTimerIfRunning(fiber) {
          profilerStartTime = -1;
        }
        function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
          if (profilerStartTime >= 0) {
            var elapsedTime = now$1() - profilerStartTime;
            fiber.actualDuration += elapsedTime;
            if (overrideBaseTime) {
              fiber.selfBaseDuration = elapsedTime;
            }
            profilerStartTime = -1;
          }
        }
        function recordLayoutEffectDuration(fiber) {
          if (layoutEffectStartTime >= 0) {
            var elapsedTime = now$1() - layoutEffectStartTime;
            layoutEffectStartTime = -1;
            var parentFiber = fiber.return;
            while (parentFiber !== null) {
              switch (parentFiber.tag) {
                case HostRoot:
                  var root3 = parentFiber.stateNode;
                  root3.effectDuration += elapsedTime;
                  return;
                case Profiler:
                  var parentStateNode = parentFiber.stateNode;
                  parentStateNode.effectDuration += elapsedTime;
                  return;
              }
              parentFiber = parentFiber.return;
            }
          }
        }
        function recordPassiveEffectDuration(fiber) {
          if (passiveEffectStartTime >= 0) {
            var elapsedTime = now$1() - passiveEffectStartTime;
            passiveEffectStartTime = -1;
            var parentFiber = fiber.return;
            while (parentFiber !== null) {
              switch (parentFiber.tag) {
                case HostRoot:
                  var root3 = parentFiber.stateNode;
                  if (root3 !== null) {
                    root3.passiveEffectDuration += elapsedTime;
                  }
                  return;
                case Profiler:
                  var parentStateNode = parentFiber.stateNode;
                  if (parentStateNode !== null) {
                    parentStateNode.passiveEffectDuration += elapsedTime;
                  }
                  return;
              }
              parentFiber = parentFiber.return;
            }
          }
        }
        function startLayoutEffectTimer() {
          layoutEffectStartTime = now$1();
        }
        function startPassiveEffectTimer() {
          passiveEffectStartTime = now$1();
        }
        function transferActualDuration(fiber) {
          var child = fiber.child;
          while (child) {
            fiber.actualDuration += child.actualDuration;
            child = child.sibling;
          }
        }
        function createCapturedValueAtFiber(value, source) {
          return {
            value,
            source,
            stack: getStackByFiberInDevAndProd(source),
            digest: null
          };
        }
        function createCapturedValue(value, digest, stack) {
          return {
            value,
            source: null,
            stack: stack != null ? stack : null,
            digest: digest != null ? digest : null
          };
        }
        function showErrorDialog(boundary, errorInfo) {
          return true;
        }
        function logCapturedError(boundary, errorInfo) {
          try {
            var logError2 = showErrorDialog(boundary, errorInfo);
            if (logError2 === false) {
              return;
            }
            var error2 = errorInfo.value;
            if (true) {
              var source = errorInfo.source;
              var stack = errorInfo.stack;
              var componentStack = stack !== null ? stack : "";
              if (error2 != null && error2._suppressLogging) {
                if (boundary.tag === ClassComponent) {
                  return;
                }
                console["error"](error2);
              }
              var componentName = source ? getComponentNameFromFiber(source) : null;
              var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:";
              var errorBoundaryMessage;
              if (boundary.tag === HostRoot) {
                errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://reactjs.org/link/error-boundaries to learn more about error boundaries.";
              } else {
                var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous";
                errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
              }
              var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage);
              console["error"](combinedMessage);
            } else {
              console["error"](error2);
            }
          } catch (e3) {
            setTimeout(function() {
              throw e3;
            });
          }
        }
        var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map;
        function createRootErrorUpdate(fiber, errorInfo, lane) {
          var update2 = createUpdate(NoTimestamp, lane);
          update2.tag = CaptureUpdate;
          update2.payload = {
            element: null
          };
          var error2 = errorInfo.value;
          update2.callback = function() {
            onUncaughtError(error2);
            logCapturedError(fiber, errorInfo);
          };
          return update2;
        }
        function createClassErrorUpdate(fiber, errorInfo, lane) {
          var update2 = createUpdate(NoTimestamp, lane);
          update2.tag = CaptureUpdate;
          var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
          if (typeof getDerivedStateFromError === "function") {
            var error$1 = errorInfo.value;
            update2.payload = function() {
              return getDerivedStateFromError(error$1);
            };
            update2.callback = function() {
              {
                markFailedErrorBoundaryForHotReloading(fiber);
              }
              logCapturedError(fiber, errorInfo);
            };
          }
          var inst = fiber.stateNode;
          if (inst !== null && typeof inst.componentDidCatch === "function") {
            update2.callback = function callback() {
              {
                markFailedErrorBoundaryForHotReloading(fiber);
              }
              logCapturedError(fiber, errorInfo);
              if (typeof getDerivedStateFromError !== "function") {
                markLegacyErrorBoundaryAsFailed(this);
              }
              var error$12 = errorInfo.value;
              var stack = errorInfo.stack;
              this.componentDidCatch(error$12, {
                componentStack: stack !== null ? stack : ""
              });
              {
                if (typeof getDerivedStateFromError !== "function") {
                  if (!includesSomeLane(fiber.lanes, SyncLane)) {
                    error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentNameFromFiber(fiber) || "Unknown");
                  }
                }
              }
            };
          }
          return update2;
        }
        function attachPingListener(root3, wakeable, lanes) {
          var pingCache = root3.pingCache;
          var threadIDs;
          if (pingCache === null) {
            pingCache = root3.pingCache = new PossiblyWeakMap$1();
            threadIDs = /* @__PURE__ */ new Set();
            pingCache.set(wakeable, threadIDs);
          } else {
            threadIDs = pingCache.get(wakeable);
            if (threadIDs === void 0) {
              threadIDs = /* @__PURE__ */ new Set();
              pingCache.set(wakeable, threadIDs);
            }
          }
          if (!threadIDs.has(lanes)) {
            threadIDs.add(lanes);
            var ping = pingSuspendedRoot.bind(null, root3, wakeable, lanes);
            {
              if (isDevToolsPresent) {
                restorePendingUpdaters(root3, lanes);
              }
            }
            wakeable.then(ping, ping);
          }
        }
        function attachRetryListener(suspenseBoundary, root3, wakeable, lanes) {
          var wakeables = suspenseBoundary.updateQueue;
          if (wakeables === null) {
            var updateQueue = /* @__PURE__ */ new Set();
            updateQueue.add(wakeable);
            suspenseBoundary.updateQueue = updateQueue;
          } else {
            wakeables.add(wakeable);
          }
        }
        function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
          var tag = sourceFiber.tag;
          if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
            var currentSource = sourceFiber.alternate;
            if (currentSource) {
              sourceFiber.updateQueue = currentSource.updateQueue;
              sourceFiber.memoizedState = currentSource.memoizedState;
              sourceFiber.lanes = currentSource.lanes;
            } else {
              sourceFiber.updateQueue = null;
              sourceFiber.memoizedState = null;
            }
          }
        }
        function getNearestSuspenseBoundaryToCapture(returnFiber) {
          var node = returnFiber;
          do {
            if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) {
              return node;
            }
            node = node.return;
          } while (node !== null);
          return null;
        }
        function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root3, rootRenderLanes) {
          if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
            if (suspenseBoundary === returnFiber) {
              suspenseBoundary.flags |= ShouldCapture;
            } else {
              suspenseBoundary.flags |= DidCapture;
              sourceFiber.flags |= ForceUpdateForLegacySuspense;
              sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
              if (sourceFiber.tag === ClassComponent) {
                var currentSourceFiber = sourceFiber.alternate;
                if (currentSourceFiber === null) {
                  sourceFiber.tag = IncompleteClassComponent;
                } else {
                  var update2 = createUpdate(NoTimestamp, SyncLane);
                  update2.tag = ForceUpdate;
                  enqueueUpdate(sourceFiber, update2, SyncLane);
                }
              }
              sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
            }
            return suspenseBoundary;
          }
          suspenseBoundary.flags |= ShouldCapture;
          suspenseBoundary.lanes = rootRenderLanes;
          return suspenseBoundary;
        }
        function throwException(root3, returnFiber, sourceFiber, value, rootRenderLanes) {
          sourceFiber.flags |= Incomplete;
          {
            if (isDevToolsPresent) {
              restorePendingUpdaters(root3, rootRenderLanes);
            }
          }
          if (value !== null && typeof value === "object" && typeof value.then === "function") {
            var wakeable = value;
            resetSuspendedComponent(sourceFiber);
            {
              if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
                markDidThrowWhileHydratingDEV();
              }
            }
            var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
            if (suspenseBoundary !== null) {
              suspenseBoundary.flags &= ~ForceClientRender;
              markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root3, rootRenderLanes);
              if (suspenseBoundary.mode & ConcurrentMode) {
                attachPingListener(root3, wakeable, rootRenderLanes);
              }
              attachRetryListener(suspenseBoundary, root3, wakeable);
              return;
            } else {
              if (!includesSyncLane(rootRenderLanes)) {
                attachPingListener(root3, wakeable, rootRenderLanes);
                renderDidSuspendDelayIfPossible();
                return;
              }
              var uncaughtSuspenseError = new Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.");
              value = uncaughtSuspenseError;
            }
          } else {
            if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
              markDidThrowWhileHydratingDEV();
              var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
              if (_suspenseBoundary !== null) {
                if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
                  _suspenseBoundary.flags |= ForceClientRender;
                }
                markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root3, rootRenderLanes);
                queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
                return;
              }
            }
          }
          value = createCapturedValueAtFiber(value, sourceFiber);
          renderDidError(value);
          var workInProgress2 = returnFiber;
          do {
            switch (workInProgress2.tag) {
              case HostRoot: {
                var _errorInfo = value;
                workInProgress2.flags |= ShouldCapture;
                var lane = pickArbitraryLane(rootRenderLanes);
                workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane);
                var update2 = createRootErrorUpdate(workInProgress2, _errorInfo, lane);
                enqueueCapturedUpdate(workInProgress2, update2);
                return;
              }
              case ClassComponent:
                var errorInfo = value;
                var ctor = workInProgress2.type;
                var instance = workInProgress2.stateNode;
                if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance))) {
                  workInProgress2.flags |= ShouldCapture;
                  var _lane = pickArbitraryLane(rootRenderLanes);
                  workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane);
                  var _update = createClassErrorUpdate(workInProgress2, errorInfo, _lane);
                  enqueueCapturedUpdate(workInProgress2, _update);
                  return;
                }
                break;
            }
            workInProgress2 = workInProgress2.return;
          } while (workInProgress2 !== null);
        }
        function getSuspendedCache() {
          {
            return null;
          }
        }
        var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
        var didReceiveUpdate = false;
        var didWarnAboutBadClass;
        var didWarnAboutModulePatternComponent;
        var didWarnAboutContextTypeOnFunctionComponent;
        var didWarnAboutGetDerivedStateOnFunctionComponent;
        var didWarnAboutFunctionRefs;
        var didWarnAboutReassigningProps;
        var didWarnAboutRevealOrder;
        var didWarnAboutTailOptions;
        {
          didWarnAboutBadClass = {};
          didWarnAboutModulePatternComponent = {};
          didWarnAboutContextTypeOnFunctionComponent = {};
          didWarnAboutGetDerivedStateOnFunctionComponent = {};
          didWarnAboutFunctionRefs = {};
          didWarnAboutReassigningProps = false;
          didWarnAboutRevealOrder = {};
          didWarnAboutTailOptions = {};
        }
        function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
          if (current2 === null) {
            workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
          } else {
            workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2);
          }
        }
        function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) {
          workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
          workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
        }
        function updateForwardRef(current2, workInProgress2, Component2, nextProps, renderLanes2) {
          {
            if (workInProgress2.type !== workInProgress2.elementType) {
              var innerPropTypes = Component2.propTypes;
              if (innerPropTypes) {
                checkPropTypes(
                  innerPropTypes,
                  nextProps,
                  // Resolved props
                  "prop",
                  getComponentNameFromType(Component2)
                );
              }
            }
          }
          var render4 = Component2.render;
          var ref = workInProgress2.ref;
          var nextChildren;
          var hasId;
          prepareToReadContext(workInProgress2, renderLanes2);
          {
            markComponentRenderStarted(workInProgress2);
          }
          {
            ReactCurrentOwner$1.current = workInProgress2;
            setIsRendering(true);
            nextChildren = renderWithHooks(current2, workInProgress2, render4, nextProps, ref, renderLanes2);
            hasId = checkDidRenderIdHook();
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                nextChildren = renderWithHooks(current2, workInProgress2, render4, nextProps, ref, renderLanes2);
                hasId = checkDidRenderIdHook();
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            setIsRendering(false);
          }
          {
            markComponentRenderStopped();
          }
          if (current2 !== null && !didReceiveUpdate) {
            bailoutHooks(current2, workInProgress2, renderLanes2);
            return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
          }
          if (getIsHydrating() && hasId) {
            pushMaterializedTreeId(workInProgress2);
          }
          workInProgress2.flags |= PerformedWork;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateMemoComponent(current2, workInProgress2, Component2, nextProps, renderLanes2) {
          if (current2 === null) {
            var type = Component2.type;
            if (isSimpleFunctionComponent(type) && Component2.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
            Component2.defaultProps === void 0) {
              var resolvedType = type;
              {
                resolvedType = resolveFunctionForHotReloading(type);
              }
              workInProgress2.tag = SimpleMemoComponent;
              workInProgress2.type = resolvedType;
              {
                validateFunctionComponentInDev(workInProgress2, type);
              }
              return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, renderLanes2);
            }
            {
              var innerPropTypes = type.propTypes;
              if (innerPropTypes) {
                checkPropTypes(
                  innerPropTypes,
                  nextProps,
                  // Resolved props
                  "prop",
                  getComponentNameFromType(type)
                );
              }
            }
            var child = createFiberFromTypeAndProps(Component2.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2);
            child.ref = workInProgress2.ref;
            child.return = workInProgress2;
            workInProgress2.child = child;
            return child;
          }
          {
            var _type = Component2.type;
            var _innerPropTypes = _type.propTypes;
            if (_innerPropTypes) {
              checkPropTypes(
                _innerPropTypes,
                nextProps,
                // Resolved props
                "prop",
                getComponentNameFromType(_type)
              );
            }
          }
          var currentChild = current2.child;
          var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2);
          if (!hasScheduledUpdateOrContext) {
            var prevProps = currentChild.memoizedProps;
            var compare2 = Component2.compare;
            compare2 = compare2 !== null ? compare2 : shallowEqual;
            if (compare2(prevProps, nextProps) && current2.ref === workInProgress2.ref) {
              return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
            }
          }
          workInProgress2.flags |= PerformedWork;
          var newChild = createWorkInProgress(currentChild, nextProps);
          newChild.ref = workInProgress2.ref;
          newChild.return = workInProgress2;
          workInProgress2.child = newChild;
          return newChild;
        }
        function updateSimpleMemoComponent(current2, workInProgress2, Component2, nextProps, renderLanes2) {
          {
            if (workInProgress2.type !== workInProgress2.elementType) {
              var outerMemoType = workInProgress2.elementType;
              if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
                var lazyComponent = outerMemoType;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  outerMemoType = init(payload);
                } catch (x2) {
                  outerMemoType = null;
                }
                var outerPropTypes = outerMemoType && outerMemoType.propTypes;
                if (outerPropTypes) {
                  checkPropTypes(
                    outerPropTypes,
                    nextProps,
                    // Resolved (SimpleMemoComponent has no defaultProps)
                    "prop",
                    getComponentNameFromType(outerMemoType)
                  );
                }
              }
            }
          }
          if (current2 !== null) {
            var prevProps = current2.memoizedProps;
            if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && // Prevent bailout if the implementation changed due to hot reload.
            workInProgress2.type === current2.type) {
              didReceiveUpdate = false;
              workInProgress2.pendingProps = nextProps = prevProps;
              if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
                workInProgress2.lanes = current2.lanes;
                return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
              } else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
                didReceiveUpdate = true;
              }
            }
          }
          return updateFunctionComponent(current2, workInProgress2, Component2, nextProps, renderLanes2);
        }
        function updateOffscreenComponent(current2, workInProgress2, renderLanes2) {
          var nextProps = workInProgress2.pendingProps;
          var nextChildren = nextProps.children;
          var prevState = current2 !== null ? current2.memoizedState : null;
          if (nextProps.mode === "hidden" || enableLegacyHidden) {
            if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
              var nextState = {
                baseLanes: NoLanes,
                cachePool: null,
                transitions: null
              };
              workInProgress2.memoizedState = nextState;
              pushRenderLanes(workInProgress2, renderLanes2);
            } else if (!includesSomeLane(renderLanes2, OffscreenLane)) {
              var spawnedCachePool = null;
              var nextBaseLanes;
              if (prevState !== null) {
                var prevBaseLanes = prevState.baseLanes;
                nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2);
              } else {
                nextBaseLanes = renderLanes2;
              }
              workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane);
              var _nextState = {
                baseLanes: nextBaseLanes,
                cachePool: spawnedCachePool,
                transitions: null
              };
              workInProgress2.memoizedState = _nextState;
              workInProgress2.updateQueue = null;
              pushRenderLanes(workInProgress2, nextBaseLanes);
              return null;
            } else {
              var _nextState2 = {
                baseLanes: NoLanes,
                cachePool: null,
                transitions: null
              };
              workInProgress2.memoizedState = _nextState2;
              var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2;
              pushRenderLanes(workInProgress2, subtreeRenderLanes2);
            }
          } else {
            var _subtreeRenderLanes;
            if (prevState !== null) {
              _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2);
              workInProgress2.memoizedState = null;
            } else {
              _subtreeRenderLanes = renderLanes2;
            }
            pushRenderLanes(workInProgress2, _subtreeRenderLanes);
          }
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateFragment(current2, workInProgress2, renderLanes2) {
          var nextChildren = workInProgress2.pendingProps;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateMode(current2, workInProgress2, renderLanes2) {
          var nextChildren = workInProgress2.pendingProps.children;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateProfiler(current2, workInProgress2, renderLanes2) {
          {
            workInProgress2.flags |= Update;
            {
              var stateNode = workInProgress2.stateNode;
              stateNode.effectDuration = 0;
              stateNode.passiveEffectDuration = 0;
            }
          }
          var nextProps = workInProgress2.pendingProps;
          var nextChildren = nextProps.children;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function markRef(current2, workInProgress2) {
          var ref = workInProgress2.ref;
          if (current2 === null && ref !== null || current2 !== null && current2.ref !== ref) {
            workInProgress2.flags |= Ref;
            {
              workInProgress2.flags |= RefStatic;
            }
          }
        }
        function updateFunctionComponent(current2, workInProgress2, Component2, nextProps, renderLanes2) {
          {
            if (workInProgress2.type !== workInProgress2.elementType) {
              var innerPropTypes = Component2.propTypes;
              if (innerPropTypes) {
                checkPropTypes(
                  innerPropTypes,
                  nextProps,
                  // Resolved props
                  "prop",
                  getComponentNameFromType(Component2)
                );
              }
            }
          }
          var context;
          {
            var unmaskedContext = getUnmaskedContext(workInProgress2, Component2, true);
            context = getMaskedContext(workInProgress2, unmaskedContext);
          }
          var nextChildren;
          var hasId;
          prepareToReadContext(workInProgress2, renderLanes2);
          {
            markComponentRenderStarted(workInProgress2);
          }
          {
            ReactCurrentOwner$1.current = workInProgress2;
            setIsRendering(true);
            nextChildren = renderWithHooks(current2, workInProgress2, Component2, nextProps, context, renderLanes2);
            hasId = checkDidRenderIdHook();
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                nextChildren = renderWithHooks(current2, workInProgress2, Component2, nextProps, context, renderLanes2);
                hasId = checkDidRenderIdHook();
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            setIsRendering(false);
          }
          {
            markComponentRenderStopped();
          }
          if (current2 !== null && !didReceiveUpdate) {
            bailoutHooks(current2, workInProgress2, renderLanes2);
            return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
          }
          if (getIsHydrating() && hasId) {
            pushMaterializedTreeId(workInProgress2);
          }
          workInProgress2.flags |= PerformedWork;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateClassComponent(current2, workInProgress2, Component2, nextProps, renderLanes2) {
          {
            switch (shouldError(workInProgress2)) {
              case false: {
                var _instance = workInProgress2.stateNode;
                var ctor = workInProgress2.type;
                var tempInstance = new ctor(workInProgress2.memoizedProps, _instance.context);
                var state = tempInstance.state;
                _instance.updater.enqueueSetState(_instance, state, null);
                break;
              }
              case true: {
                workInProgress2.flags |= DidCapture;
                workInProgress2.flags |= ShouldCapture;
                var error$1 = new Error("Simulated error coming from DevTools");
                var lane = pickArbitraryLane(renderLanes2);
                workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane);
                var update2 = createClassErrorUpdate(workInProgress2, createCapturedValueAtFiber(error$1, workInProgress2), lane);
                enqueueCapturedUpdate(workInProgress2, update2);
                break;
              }
            }
            if (workInProgress2.type !== workInProgress2.elementType) {
              var innerPropTypes = Component2.propTypes;
              if (innerPropTypes) {
                checkPropTypes(
                  innerPropTypes,
                  nextProps,
                  // Resolved props
                  "prop",
                  getComponentNameFromType(Component2)
                );
              }
            }
          }
          var hasContext;
          if (isContextProvider(Component2)) {
            hasContext = true;
            pushContextProvider(workInProgress2);
          } else {
            hasContext = false;
          }
          prepareToReadContext(workInProgress2, renderLanes2);
          var instance = workInProgress2.stateNode;
          var shouldUpdate;
          if (instance === null) {
            resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2);
            constructClassInstance(workInProgress2, Component2, nextProps);
            mountClassInstance(workInProgress2, Component2, nextProps, renderLanes2);
            shouldUpdate = true;
          } else if (current2 === null) {
            shouldUpdate = resumeMountClassInstance(workInProgress2, Component2, nextProps, renderLanes2);
          } else {
            shouldUpdate = updateClassInstance(current2, workInProgress2, Component2, nextProps, renderLanes2);
          }
          var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component2, shouldUpdate, hasContext, renderLanes2);
          {
            var inst = workInProgress2.stateNode;
            if (shouldUpdate && inst.props !== nextProps) {
              if (!didWarnAboutReassigningProps) {
                error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentNameFromFiber(workInProgress2) || "a component");
              }
              didWarnAboutReassigningProps = true;
            }
          }
          return nextUnitOfWork;
        }
        function finishClassComponent(current2, workInProgress2, Component2, shouldUpdate, hasContext, renderLanes2) {
          markRef(current2, workInProgress2);
          var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags;
          if (!shouldUpdate && !didCaptureError) {
            if (hasContext) {
              invalidateContextProvider(workInProgress2, Component2, false);
            }
            return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
          }
          var instance = workInProgress2.stateNode;
          ReactCurrentOwner$1.current = workInProgress2;
          var nextChildren;
          if (didCaptureError && typeof Component2.getDerivedStateFromError !== "function") {
            nextChildren = null;
            {
              stopProfilerTimerIfRunning();
            }
          } else {
            {
              markComponentRenderStarted(workInProgress2);
            }
            {
              setIsRendering(true);
              nextChildren = instance.render();
              if (workInProgress2.mode & StrictLegacyMode) {
                setIsStrictModeForDevtools(true);
                try {
                  instance.render();
                } finally {
                  setIsStrictModeForDevtools(false);
                }
              }
              setIsRendering(false);
            }
            {
              markComponentRenderStopped();
            }
          }
          workInProgress2.flags |= PerformedWork;
          if (current2 !== null && didCaptureError) {
            forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2);
          } else {
            reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          }
          workInProgress2.memoizedState = instance.state;
          if (hasContext) {
            invalidateContextProvider(workInProgress2, Component2, true);
          }
          return workInProgress2.child;
        }
        function pushHostRootContext(workInProgress2) {
          var root3 = workInProgress2.stateNode;
          if (root3.pendingContext) {
            pushTopLevelContextObject(workInProgress2, root3.pendingContext, root3.pendingContext !== root3.context);
          } else if (root3.context) {
            pushTopLevelContextObject(workInProgress2, root3.context, false);
          }
          pushHostContainer(workInProgress2, root3.containerInfo);
        }
        function updateHostRoot(current2, workInProgress2, renderLanes2) {
          pushHostRootContext(workInProgress2);
          if (current2 === null) {
            throw new Error("Should have a current fiber. This is a bug in React.");
          }
          var nextProps = workInProgress2.pendingProps;
          var prevState = workInProgress2.memoizedState;
          var prevChildren = prevState.element;
          cloneUpdateQueue(current2, workInProgress2);
          processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
          var nextState = workInProgress2.memoizedState;
          var root3 = workInProgress2.stateNode;
          var nextChildren = nextState.element;
          if (prevState.isDehydrated) {
            var overrideState = {
              element: nextChildren,
              isDehydrated: false,
              cache: nextState.cache,
              pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
              transitions: nextState.transitions
            };
            var updateQueue = workInProgress2.updateQueue;
            updateQueue.baseState = overrideState;
            workInProgress2.memoizedState = overrideState;
            if (workInProgress2.flags & ForceClientRender) {
              var recoverableError = createCapturedValueAtFiber(new Error("There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering."), workInProgress2);
              return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError);
            } else if (nextChildren !== prevChildren) {
              var _recoverableError = createCapturedValueAtFiber(new Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2);
              return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, _recoverableError);
            } else {
              enterHydrationState(workInProgress2);
              var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
              workInProgress2.child = child;
              var node = child;
              while (node) {
                node.flags = node.flags & ~Placement | Hydrating;
                node = node.sibling;
              }
            }
          } else {
            resetHydrationState();
            if (nextChildren === prevChildren) {
              return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
            }
            reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          }
          return workInProgress2.child;
        }
        function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError) {
          resetHydrationState();
          queueHydrationError(recoverableError);
          workInProgress2.flags |= ForceClientRender;
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateHostComponent(current2, workInProgress2, renderLanes2) {
          pushHostContext(workInProgress2);
          if (current2 === null) {
            tryToClaimNextHydratableInstance(workInProgress2);
          }
          var type = workInProgress2.type;
          var nextProps = workInProgress2.pendingProps;
          var prevProps = current2 !== null ? current2.memoizedProps : null;
          var nextChildren = nextProps.children;
          var isDirectTextChild = shouldSetTextContent(type, nextProps);
          if (isDirectTextChild) {
            nextChildren = null;
          } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
            workInProgress2.flags |= ContentReset;
          }
          markRef(current2, workInProgress2);
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          return workInProgress2.child;
        }
        function updateHostText(current2, workInProgress2) {
          if (current2 === null) {
            tryToClaimNextHydratableInstance(workInProgress2);
          }
          return null;
        }
        function mountLazyComponent(_current, workInProgress2, elementType, renderLanes2) {
          resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
          var props = workInProgress2.pendingProps;
          var lazyComponent = elementType;
          var payload = lazyComponent._payload;
          var init = lazyComponent._init;
          var Component2 = init(payload);
          workInProgress2.type = Component2;
          var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component2);
          var resolvedProps = resolveDefaultProps(Component2, props);
          var child;
          switch (resolvedTag) {
            case FunctionComponent: {
              {
                validateFunctionComponentInDev(workInProgress2, Component2);
                workInProgress2.type = Component2 = resolveFunctionForHotReloading(Component2);
              }
              child = updateFunctionComponent(null, workInProgress2, Component2, resolvedProps, renderLanes2);
              return child;
            }
            case ClassComponent: {
              {
                workInProgress2.type = Component2 = resolveClassForHotReloading(Component2);
              }
              child = updateClassComponent(null, workInProgress2, Component2, resolvedProps, renderLanes2);
              return child;
            }
            case ForwardRef: {
              {
                workInProgress2.type = Component2 = resolveForwardRefForHotReloading(Component2);
              }
              child = updateForwardRef(null, workInProgress2, Component2, resolvedProps, renderLanes2);
              return child;
            }
            case MemoComponent: {
              {
                if (workInProgress2.type !== workInProgress2.elementType) {
                  var outerPropTypes = Component2.propTypes;
                  if (outerPropTypes) {
                    checkPropTypes(
                      outerPropTypes,
                      resolvedProps,
                      // Resolved for outer only
                      "prop",
                      getComponentNameFromType(Component2)
                    );
                  }
                }
              }
              child = updateMemoComponent(
                null,
                workInProgress2,
                Component2,
                resolveDefaultProps(Component2.type, resolvedProps),
                // The inner type can have defaults too
                renderLanes2
              );
              return child;
            }
          }
          var hint = "";
          {
            if (Component2 !== null && typeof Component2 === "object" && Component2.$$typeof === REACT_LAZY_TYPE) {
              hint = " Did you wrap a component in React.lazy() more than once?";
            }
          }
          throw new Error("Element type is invalid. Received a promise that resolves to: " + Component2 + ". " + ("Lazy element type must resolve to a class or function." + hint));
        }
        function mountIncompleteClassComponent(_current, workInProgress2, Component2, nextProps, renderLanes2) {
          resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
          workInProgress2.tag = ClassComponent;
          var hasContext;
          if (isContextProvider(Component2)) {
            hasContext = true;
            pushContextProvider(workInProgress2);
          } else {
            hasContext = false;
          }
          prepareToReadContext(workInProgress2, renderLanes2);
          constructClassInstance(workInProgress2, Component2, nextProps);
          mountClassInstance(workInProgress2, Component2, nextProps, renderLanes2);
          return finishClassComponent(null, workInProgress2, Component2, true, hasContext, renderLanes2);
        }
        function mountIndeterminateComponent(_current, workInProgress2, Component2, renderLanes2) {
          resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
          var props = workInProgress2.pendingProps;
          var context;
          {
            var unmaskedContext = getUnmaskedContext(workInProgress2, Component2, false);
            context = getMaskedContext(workInProgress2, unmaskedContext);
          }
          prepareToReadContext(workInProgress2, renderLanes2);
          var value;
          var hasId;
          {
            markComponentRenderStarted(workInProgress2);
          }
          {
            if (Component2.prototype && typeof Component2.prototype.render === "function") {
              var componentName = getComponentNameFromType(Component2) || "Unknown";
              if (!didWarnAboutBadClass[componentName]) {
                error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName, componentName);
                didWarnAboutBadClass[componentName] = true;
              }
            }
            if (workInProgress2.mode & StrictLegacyMode) {
              ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null);
            }
            setIsRendering(true);
            ReactCurrentOwner$1.current = workInProgress2;
            value = renderWithHooks(null, workInProgress2, Component2, props, context, renderLanes2);
            hasId = checkDidRenderIdHook();
            setIsRendering(false);
          }
          {
            markComponentRenderStopped();
          }
          workInProgress2.flags |= PerformedWork;
          {
            if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) {
              var _componentName = getComponentNameFromType(Component2) || "Unknown";
              if (!didWarnAboutModulePatternComponent[_componentName]) {
                error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName, _componentName, _componentName);
                didWarnAboutModulePatternComponent[_componentName] = true;
              }
            }
          }
          if (
            // Run these checks in production only if the flag is off.
            // Eventually we'll delete this branch altogether.
            typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0
          ) {
            {
              var _componentName2 = getComponentNameFromType(Component2) || "Unknown";
              if (!didWarnAboutModulePatternComponent[_componentName2]) {
                error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName2, _componentName2, _componentName2);
                didWarnAboutModulePatternComponent[_componentName2] = true;
              }
            }
            workInProgress2.tag = ClassComponent;
            workInProgress2.memoizedState = null;
            workInProgress2.updateQueue = null;
            var hasContext = false;
            if (isContextProvider(Component2)) {
              hasContext = true;
              pushContextProvider(workInProgress2);
            } else {
              hasContext = false;
            }
            workInProgress2.memoizedState = value.state !== null && value.state !== void 0 ? value.state : null;
            initializeUpdateQueue(workInProgress2);
            adoptClassInstance(workInProgress2, value);
            mountClassInstance(workInProgress2, Component2, props, renderLanes2);
            return finishClassComponent(null, workInProgress2, Component2, true, hasContext, renderLanes2);
          } else {
            workInProgress2.tag = FunctionComponent;
            {
              if (workInProgress2.mode & StrictLegacyMode) {
                setIsStrictModeForDevtools(true);
                try {
                  value = renderWithHooks(null, workInProgress2, Component2, props, context, renderLanes2);
                  hasId = checkDidRenderIdHook();
                } finally {
                  setIsStrictModeForDevtools(false);
                }
              }
            }
            if (getIsHydrating() && hasId) {
              pushMaterializedTreeId(workInProgress2);
            }
            reconcileChildren(null, workInProgress2, value, renderLanes2);
            {
              validateFunctionComponentInDev(workInProgress2, Component2);
            }
            return workInProgress2.child;
          }
        }
        function validateFunctionComponentInDev(workInProgress2, Component2) {
          {
            if (Component2) {
              if (Component2.childContextTypes) {
                error("%s(...): childContextTypes cannot be defined on a function component.", Component2.displayName || Component2.name || "Component");
              }
            }
            if (workInProgress2.ref !== null) {
              var info = "";
              var ownerName = getCurrentFiberOwnerNameInDevOrNull();
              if (ownerName) {
                info += "\n\nCheck the render method of `" + ownerName + "`.";
              }
              var warningKey = ownerName || "";
              var debugSource = workInProgress2._debugSource;
              if (debugSource) {
                warningKey = debugSource.fileName + ":" + debugSource.lineNumber;
              }
              if (!didWarnAboutFunctionRefs[warningKey]) {
                didWarnAboutFunctionRefs[warningKey] = true;
                error("Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s", info);
              }
            }
            if (typeof Component2.getDerivedStateFromProps === "function") {
              var _componentName3 = getComponentNameFromType(Component2) || "Unknown";
              if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
                error("%s: Function components do not support getDerivedStateFromProps.", _componentName3);
                didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
              }
            }
            if (typeof Component2.contextType === "object" && Component2.contextType !== null) {
              var _componentName4 = getComponentNameFromType(Component2) || "Unknown";
              if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
                error("%s: Function components do not support contextType.", _componentName4);
                didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
              }
            }
          }
        }
        var SUSPENDED_MARKER = {
          dehydrated: null,
          treeContext: null,
          retryLane: NoLane
        };
        function mountSuspenseOffscreenState(renderLanes2) {
          return {
            baseLanes: renderLanes2,
            cachePool: getSuspendedCache(),
            transitions: null
          };
        }
        function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) {
          var cachePool = null;
          return {
            baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2),
            cachePool,
            transitions: prevOffscreenState.transitions
          };
        }
        function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) {
          if (current2 !== null) {
            var suspenseState = current2.memoizedState;
            if (suspenseState === null) {
              return false;
            }
          }
          return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
        }
        function getRemainingWorkInPrimaryTree(current2, renderLanes2) {
          return removeLanes(current2.childLanes, renderLanes2);
        }
        function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
          var nextProps = workInProgress2.pendingProps;
          {
            if (shouldSuspend(workInProgress2)) {
              workInProgress2.flags |= DidCapture;
            }
          }
          var suspenseContext = suspenseStackCursor.current;
          var showFallback = false;
          var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags;
          if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) {
            showFallback = true;
            workInProgress2.flags &= ~DidCapture;
          } else {
            if (current2 === null || current2.memoizedState !== null) {
              {
                suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
              }
            }
          }
          suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
          pushSuspenseContext(workInProgress2, suspenseContext);
          if (current2 === null) {
            tryToClaimNextHydratableInstance(workInProgress2);
            var suspenseState = workInProgress2.memoizedState;
            if (suspenseState !== null) {
              var dehydrated = suspenseState.dehydrated;
              if (dehydrated !== null) {
                return mountDehydratedSuspenseComponent(workInProgress2, dehydrated);
              }
            }
            var nextPrimaryChildren = nextProps.children;
            var nextFallbackChildren = nextProps.fallback;
            if (showFallback) {
              var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
              var primaryChildFragment = workInProgress2.child;
              primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2);
              workInProgress2.memoizedState = SUSPENDED_MARKER;
              return fallbackFragment;
            } else {
              return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren);
            }
          } else {
            var prevState = current2.memoizedState;
            if (prevState !== null) {
              var _dehydrated = prevState.dehydrated;
              if (_dehydrated !== null) {
                return updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, _dehydrated, prevState, renderLanes2);
              }
            }
            if (showFallback) {
              var _nextFallbackChildren = nextProps.fallback;
              var _nextPrimaryChildren = nextProps.children;
              var fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren, _nextFallbackChildren, renderLanes2);
              var _primaryChildFragment2 = workInProgress2.child;
              var prevOffscreenState = current2.child.memoizedState;
              _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2);
              _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2);
              workInProgress2.memoizedState = SUSPENDED_MARKER;
              return fallbackChildFragment;
            } else {
              var _nextPrimaryChildren2 = nextProps.children;
              var _primaryChildFragment3 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren2, renderLanes2);
              workInProgress2.memoizedState = null;
              return _primaryChildFragment3;
            }
          }
        }
        function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) {
          var mode = workInProgress2.mode;
          var primaryChildProps = {
            mode: "visible",
            children: primaryChildren
          };
          var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
          primaryChildFragment.return = workInProgress2;
          workInProgress2.child = primaryChildFragment;
          return primaryChildFragment;
        }
        function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
          var mode = workInProgress2.mode;
          var progressedPrimaryFragment = workInProgress2.child;
          var primaryChildProps = {
            mode: "hidden",
            children: primaryChildren
          };
          var primaryChildFragment;
          var fallbackChildFragment;
          if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
            primaryChildFragment = progressedPrimaryFragment;
            primaryChildFragment.childLanes = NoLanes;
            primaryChildFragment.pendingProps = primaryChildProps;
            if (workInProgress2.mode & ProfileMode) {
              primaryChildFragment.actualDuration = 0;
              primaryChildFragment.actualStartTime = -1;
              primaryChildFragment.selfBaseDuration = 0;
              primaryChildFragment.treeBaseDuration = 0;
            }
            fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
          } else {
            primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
            fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
          }
          primaryChildFragment.return = workInProgress2;
          fallbackChildFragment.return = workInProgress2;
          primaryChildFragment.sibling = fallbackChildFragment;
          workInProgress2.child = primaryChildFragment;
          return fallbackChildFragment;
        }
        function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes2) {
          return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
        }
        function updateWorkInProgressOffscreenFiber(current2, offscreenProps) {
          return createWorkInProgress(current2, offscreenProps);
        }
        function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) {
          var currentPrimaryChildFragment = current2.child;
          var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
          var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
            mode: "visible",
            children: primaryChildren
          });
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            primaryChildFragment.lanes = renderLanes2;
          }
          primaryChildFragment.return = workInProgress2;
          primaryChildFragment.sibling = null;
          if (currentFallbackChildFragment !== null) {
            var deletions = workInProgress2.deletions;
            if (deletions === null) {
              workInProgress2.deletions = [currentFallbackChildFragment];
              workInProgress2.flags |= ChildDeletion;
            } else {
              deletions.push(currentFallbackChildFragment);
            }
          }
          workInProgress2.child = primaryChildFragment;
          return primaryChildFragment;
        }
        function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
          var mode = workInProgress2.mode;
          var currentPrimaryChildFragment = current2.child;
          var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
          var primaryChildProps = {
            mode: "hidden",
            children: primaryChildren
          };
          var primaryChildFragment;
          if (
            // In legacy mode, we commit the primary tree as if it successfully
            // completed, even though it's in an inconsistent state.
            (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
            // already cloned. In legacy mode, the only case where this isn't true is
            // when DevTools forces us to display a fallback; we skip the first render
            // pass entirely and go straight to rendering the fallback. (In Concurrent
            // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
            // only codepath.)
            workInProgress2.child !== currentPrimaryChildFragment
          ) {
            var progressedPrimaryFragment = workInProgress2.child;
            primaryChildFragment = progressedPrimaryFragment;
            primaryChildFragment.childLanes = NoLanes;
            primaryChildFragment.pendingProps = primaryChildProps;
            if (workInProgress2.mode & ProfileMode) {
              primaryChildFragment.actualDuration = 0;
              primaryChildFragment.actualStartTime = -1;
              primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
              primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
            }
            workInProgress2.deletions = null;
          } else {
            primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps);
            primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
          }
          var fallbackChildFragment;
          if (currentFallbackChildFragment !== null) {
            fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
          } else {
            fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
            fallbackChildFragment.flags |= Placement;
          }
          fallbackChildFragment.return = workInProgress2;
          primaryChildFragment.return = workInProgress2;
          primaryChildFragment.sibling = fallbackChildFragment;
          workInProgress2.child = primaryChildFragment;
          return fallbackChildFragment;
        }
        function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, recoverableError) {
          if (recoverableError !== null) {
            queueHydrationError(recoverableError);
          }
          reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
          var nextProps = workInProgress2.pendingProps;
          var primaryChildren = nextProps.children;
          var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren);
          primaryChildFragment.flags |= Placement;
          workInProgress2.memoizedState = null;
          return primaryChildFragment;
        }
        function mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
          var fiberMode = workInProgress2.mode;
          var primaryChildProps = {
            mode: "visible",
            children: primaryChildren
          };
          var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
          var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes2, null);
          fallbackChildFragment.flags |= Placement;
          primaryChildFragment.return = workInProgress2;
          fallbackChildFragment.return = workInProgress2;
          primaryChildFragment.sibling = fallbackChildFragment;
          workInProgress2.child = primaryChildFragment;
          if ((workInProgress2.mode & ConcurrentMode) !== NoMode) {
            reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
          }
          return fallbackChildFragment;
        }
        function mountDehydratedSuspenseComponent(workInProgress2, suspenseInstance, renderLanes2) {
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            {
              error("Cannot hydrate Suspense in legacy mode. Switch from ReactDOM.hydrate(element, container) to ReactDOMClient.hydrateRoot(container, <App />).render(element) or remove the Suspense components from the server rendered components.");
            }
            workInProgress2.lanes = laneToLanes(SyncLane);
          } else if (isSuspenseInstanceFallback(suspenseInstance)) {
            workInProgress2.lanes = laneToLanes(DefaultHydrationLane);
          } else {
            workInProgress2.lanes = laneToLanes(OffscreenLane);
          }
          return null;
        }
        function updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes2) {
          if (!didSuspend) {
            warnIfHydrating();
            if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
              return retrySuspenseComponentWithoutHydrating(
                current2,
                workInProgress2,
                renderLanes2,
                // TODO: When we delete legacy mode, we should make this error argument
                // required — every concurrent mode path that causes hydration to
                // de-opt to client rendering should have an error message.
                null
              );
            }
            if (isSuspenseInstanceFallback(suspenseInstance)) {
              var digest, message, stack;
              {
                var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);
                digest = _getSuspenseInstanceF.digest;
                message = _getSuspenseInstanceF.message;
                stack = _getSuspenseInstanceF.stack;
              }
              var error2;
              if (message) {
                error2 = new Error(message);
              } else {
                error2 = new Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.");
              }
              var capturedValue = createCapturedValue(error2, digest, stack);
              return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, capturedValue);
            }
            var hasContextChanged2 = includesSomeLane(renderLanes2, current2.childLanes);
            if (didReceiveUpdate || hasContextChanged2) {
              var root3 = getWorkInProgressRoot();
              if (root3 !== null) {
                var attemptHydrationAtLane = getBumpedLaneForHydration(root3, renderLanes2);
                if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
                  suspenseState.retryLane = attemptHydrationAtLane;
                  var eventTime = NoTimestamp;
                  enqueueConcurrentRenderForLane(current2, attemptHydrationAtLane);
                  scheduleUpdateOnFiber(root3, current2, attemptHydrationAtLane, eventTime);
                }
              }
              renderDidSuspendDelayIfPossible();
              var _capturedValue = createCapturedValue(new Error("This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch to client rendering. The usual way to fix this is to wrap the original update in startTransition."));
              return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue);
            } else if (isSuspenseInstancePending(suspenseInstance)) {
              workInProgress2.flags |= DidCapture;
              workInProgress2.child = current2.child;
              var retry = retryDehydratedSuspenseBoundary.bind(null, current2);
              registerSuspenseInstanceRetry(suspenseInstance, retry);
              return null;
            } else {
              reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress2, suspenseInstance, suspenseState.treeContext);
              var primaryChildren = nextProps.children;
              var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren);
              primaryChildFragment.flags |= Hydrating;
              return primaryChildFragment;
            }
          } else {
            if (workInProgress2.flags & ForceClientRender) {
              workInProgress2.flags &= ~ForceClientRender;
              var _capturedValue2 = createCapturedValue(new Error("There was an error while hydrating this Suspense boundary. Switched to client rendering."));
              return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue2);
            } else if (workInProgress2.memoizedState !== null) {
              workInProgress2.child = current2.child;
              workInProgress2.flags |= DidCapture;
              return null;
            } else {
              var nextPrimaryChildren = nextProps.children;
              var nextFallbackChildren = nextProps.fallback;
              var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
              var _primaryChildFragment4 = workInProgress2.child;
              _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes2);
              workInProgress2.memoizedState = SUSPENDED_MARKER;
              return fallbackChildFragment;
            }
          }
        }
        function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
          fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
          var alternate = fiber.alternate;
          if (alternate !== null) {
            alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
          }
          scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
        }
        function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) {
          var node = firstChild;
          while (node !== null) {
            if (node.tag === SuspenseComponent) {
              var state = node.memoizedState;
              if (state !== null) {
                scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2);
              }
            } else if (node.tag === SuspenseListComponent) {
              scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2);
            } else if (node.child !== null) {
              node.child.return = node;
              node = node.child;
              continue;
            }
            if (node === workInProgress2) {
              return;
            }
            while (node.sibling === null) {
              if (node.return === null || node.return === workInProgress2) {
                return;
              }
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        }
        function findLastContentRow(firstChild) {
          var row = firstChild;
          var lastContentRow = null;
          while (row !== null) {
            var currentRow = row.alternate;
            if (currentRow !== null && findFirstSuspended(currentRow) === null) {
              lastContentRow = row;
            }
            row = row.sibling;
          }
          return lastContentRow;
        }
        function validateRevealOrder(revealOrder) {
          {
            if (revealOrder !== void 0 && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder]) {
              didWarnAboutRevealOrder[revealOrder] = true;
              if (typeof revealOrder === "string") {
                switch (revealOrder.toLowerCase()) {
                  case "together":
                  case "forwards":
                  case "backwards": {
                    error('"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
                    break;
                  }
                  case "forward":
                  case "backward": {
                    error('"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
                    break;
                  }
                  default:
                    error('"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
                    break;
                }
              } else {
                error('%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
              }
            }
          }
        }
        function validateTailOptions(tailMode, revealOrder) {
          {
            if (tailMode !== void 0 && !didWarnAboutTailOptions[tailMode]) {
              if (tailMode !== "collapsed" && tailMode !== "hidden") {
                didWarnAboutTailOptions[tailMode] = true;
                error('"%s" is not a supported value for tail on <SuspenseList />. Did you mean "collapsed" or "hidden"?', tailMode);
              } else if (revealOrder !== "forwards" && revealOrder !== "backwards") {
                didWarnAboutTailOptions[tailMode] = true;
                error('<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode);
              }
            }
          }
        }
        function validateSuspenseListNestedChild(childSlot, index3) {
          {
            var isAnArray = isArray2(childSlot);
            var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === "function";
            if (isAnArray || isIterable) {
              var type = isAnArray ? "array" : "iterable";
              error("A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>", type, index3, type);
              return false;
            }
          }
          return true;
        }
        function validateSuspenseListChildren(children, revealOrder) {
          {
            if ((revealOrder === "forwards" || revealOrder === "backwards") && children !== void 0 && children !== null && children !== false) {
              if (isArray2(children)) {
                for (var i3 = 0; i3 < children.length; i3++) {
                  if (!validateSuspenseListNestedChild(children[i3], i3)) {
                    return;
                  }
                }
              } else {
                var iteratorFn = getIteratorFn(children);
                if (typeof iteratorFn === "function") {
                  var childrenIterator = iteratorFn.call(children);
                  if (childrenIterator) {
                    var step = childrenIterator.next();
                    var _i = 0;
                    for (; !step.done; step = childrenIterator.next()) {
                      if (!validateSuspenseListNestedChild(step.value, _i)) {
                        return;
                      }
                      _i++;
                    }
                  }
                } else {
                  error('A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder);
                }
              }
            }
          }
        }
        function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
          var renderState = workInProgress2.memoizedState;
          if (renderState === null) {
            workInProgress2.memoizedState = {
              isBackwards,
              rendering: null,
              renderingStartTime: 0,
              last: lastContentRow,
              tail,
              tailMode
            };
          } else {
            renderState.isBackwards = isBackwards;
            renderState.rendering = null;
            renderState.renderingStartTime = 0;
            renderState.last = lastContentRow;
            renderState.tail = tail;
            renderState.tailMode = tailMode;
          }
        }
        function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
          var nextProps = workInProgress2.pendingProps;
          var revealOrder = nextProps.revealOrder;
          var tailMode = nextProps.tail;
          var newChildren = nextProps.children;
          validateRevealOrder(revealOrder);
          validateTailOptions(tailMode, revealOrder);
          validateSuspenseListChildren(newChildren, revealOrder);
          reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
          var suspenseContext = suspenseStackCursor.current;
          var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
          if (shouldForceFallback) {
            suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
            workInProgress2.flags |= DidCapture;
          } else {
            var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags;
            if (didSuspendBefore) {
              propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2);
            }
            suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
          }
          pushSuspenseContext(workInProgress2, suspenseContext);
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            workInProgress2.memoizedState = null;
          } else {
            switch (revealOrder) {
              case "forwards": {
                var lastContentRow = findLastContentRow(workInProgress2.child);
                var tail;
                if (lastContentRow === null) {
                  tail = workInProgress2.child;
                  workInProgress2.child = null;
                } else {
                  tail = lastContentRow.sibling;
                  lastContentRow.sibling = null;
                }
                initSuspenseListRenderState(
                  workInProgress2,
                  false,
                  // isBackwards
                  tail,
                  lastContentRow,
                  tailMode
                );
                break;
              }
              case "backwards": {
                var _tail = null;
                var row = workInProgress2.child;
                workInProgress2.child = null;
                while (row !== null) {
                  var currentRow = row.alternate;
                  if (currentRow !== null && findFirstSuspended(currentRow) === null) {
                    workInProgress2.child = row;
                    break;
                  }
                  var nextRow = row.sibling;
                  row.sibling = _tail;
                  _tail = row;
                  row = nextRow;
                }
                initSuspenseListRenderState(
                  workInProgress2,
                  true,
                  // isBackwards
                  _tail,
                  null,
                  // last
                  tailMode
                );
                break;
              }
              case "together": {
                initSuspenseListRenderState(
                  workInProgress2,
                  false,
                  // isBackwards
                  null,
                  // tail
                  null,
                  // last
                  void 0
                );
                break;
              }
              default: {
                workInProgress2.memoizedState = null;
              }
            }
          }
          return workInProgress2.child;
        }
        function updatePortalComponent(current2, workInProgress2, renderLanes2) {
          pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
          var nextChildren = workInProgress2.pendingProps;
          if (current2 === null) {
            workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
          } else {
            reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
          }
          return workInProgress2.child;
        }
        var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
        function updateContextProvider(current2, workInProgress2, renderLanes2) {
          var providerType = workInProgress2.type;
          var context = providerType._context;
          var newProps = workInProgress2.pendingProps;
          var oldProps = workInProgress2.memoizedProps;
          var newValue = newProps.value;
          {
            if (!("value" in newProps)) {
              if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
                hasWarnedAboutUsingNoValuePropOnContextProvider = true;
                error("The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?");
              }
            }
            var providerPropTypes = workInProgress2.type.propTypes;
            if (providerPropTypes) {
              checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider");
            }
          }
          pushProvider(workInProgress2, context, newValue);
          {
            if (oldProps !== null) {
              var oldValue = oldProps.value;
              if (objectIs(oldValue, newValue)) {
                if (oldProps.children === newProps.children && !hasContextChanged()) {
                  return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
                }
              } else {
                propagateContextChange(workInProgress2, context, renderLanes2);
              }
            }
          }
          var newChildren = newProps.children;
          reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
          return workInProgress2.child;
        }
        var hasWarnedAboutUsingContextAsConsumer = false;
        function updateContextConsumer(current2, workInProgress2, renderLanes2) {
          var context = workInProgress2.type;
          {
            if (context._context === void 0) {
              if (context !== context.Consumer) {
                if (!hasWarnedAboutUsingContextAsConsumer) {
                  hasWarnedAboutUsingContextAsConsumer = true;
                  error("Rendering <Context> directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
                }
              }
            } else {
              context = context._context;
            }
          }
          var newProps = workInProgress2.pendingProps;
          var render4 = newProps.children;
          {
            if (typeof render4 !== "function") {
              error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.");
            }
          }
          prepareToReadContext(workInProgress2, renderLanes2);
          var newValue = readContext(context);
          {
            markComponentRenderStarted(workInProgress2);
          }
          var newChildren;
          {
            ReactCurrentOwner$1.current = workInProgress2;
            setIsRendering(true);
            newChildren = render4(newValue);
            setIsRendering(false);
          }
          {
            markComponentRenderStopped();
          }
          workInProgress2.flags |= PerformedWork;
          reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
          return workInProgress2.child;
        }
        function markWorkInProgressReceivedUpdate() {
          didReceiveUpdate = true;
        }
        function resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2) {
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            if (current2 !== null) {
              current2.alternate = null;
              workInProgress2.alternate = null;
              workInProgress2.flags |= Placement;
            }
          }
        }
        function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
          if (current2 !== null) {
            workInProgress2.dependencies = current2.dependencies;
          }
          {
            stopProfilerTimerIfRunning();
          }
          markSkippedUpdateLanes(workInProgress2.lanes);
          if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) {
            {
              return null;
            }
          }
          cloneChildFibers(current2, workInProgress2);
          return workInProgress2.child;
        }
        function remountFiber(current2, oldWorkInProgress, newWorkInProgress) {
          {
            var returnFiber = oldWorkInProgress.return;
            if (returnFiber === null) {
              throw new Error("Cannot swap the root fiber.");
            }
            current2.alternate = null;
            oldWorkInProgress.alternate = null;
            newWorkInProgress.index = oldWorkInProgress.index;
            newWorkInProgress.sibling = oldWorkInProgress.sibling;
            newWorkInProgress.return = oldWorkInProgress.return;
            newWorkInProgress.ref = oldWorkInProgress.ref;
            if (oldWorkInProgress === returnFiber.child) {
              returnFiber.child = newWorkInProgress;
            } else {
              var prevSibling = returnFiber.child;
              if (prevSibling === null) {
                throw new Error("Expected parent to have a child.");
              }
              while (prevSibling.sibling !== oldWorkInProgress) {
                prevSibling = prevSibling.sibling;
                if (prevSibling === null) {
                  throw new Error("Expected to find the previous sibling.");
                }
              }
              prevSibling.sibling = newWorkInProgress;
            }
            var deletions = returnFiber.deletions;
            if (deletions === null) {
              returnFiber.deletions = [current2];
              returnFiber.flags |= ChildDeletion;
            } else {
              deletions.push(current2);
            }
            newWorkInProgress.flags |= Placement;
            return newWorkInProgress;
          }
        }
        function checkScheduledUpdateOrContext(current2, renderLanes2) {
          var updateLanes = current2.lanes;
          if (includesSomeLane(updateLanes, renderLanes2)) {
            return true;
          }
          return false;
        }
        function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
          switch (workInProgress2.tag) {
            case HostRoot:
              pushHostRootContext(workInProgress2);
              var root3 = workInProgress2.stateNode;
              resetHydrationState();
              break;
            case HostComponent:
              pushHostContext(workInProgress2);
              break;
            case ClassComponent: {
              var Component2 = workInProgress2.type;
              if (isContextProvider(Component2)) {
                pushContextProvider(workInProgress2);
              }
              break;
            }
            case HostPortal:
              pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
              break;
            case ContextProvider: {
              var newValue = workInProgress2.memoizedProps.value;
              var context = workInProgress2.type._context;
              pushProvider(workInProgress2, context, newValue);
              break;
            }
            case Profiler:
              {
                var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
                if (hasChildWork) {
                  workInProgress2.flags |= Update;
                }
                {
                  var stateNode = workInProgress2.stateNode;
                  stateNode.effectDuration = 0;
                  stateNode.passiveEffectDuration = 0;
                }
              }
              break;
            case SuspenseComponent: {
              var state = workInProgress2.memoizedState;
              if (state !== null) {
                if (state.dehydrated !== null) {
                  pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
                  workInProgress2.flags |= DidCapture;
                  return null;
                }
                var primaryChildFragment = workInProgress2.child;
                var primaryChildLanes = primaryChildFragment.childLanes;
                if (includesSomeLane(renderLanes2, primaryChildLanes)) {
                  return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
                } else {
                  pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
                  var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
                  if (child !== null) {
                    return child.sibling;
                  } else {
                    return null;
                  }
                }
              } else {
                pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
              }
              break;
            }
            case SuspenseListComponent: {
              var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags;
              var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
              if (didSuspendBefore) {
                if (_hasChildWork) {
                  return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
                }
                workInProgress2.flags |= DidCapture;
              }
              var renderState = workInProgress2.memoizedState;
              if (renderState !== null) {
                renderState.rendering = null;
                renderState.tail = null;
                renderState.lastEffect = null;
              }
              pushSuspenseContext(workInProgress2, suspenseStackCursor.current);
              if (_hasChildWork) {
                break;
              } else {
                return null;
              }
            }
            case OffscreenComponent:
            case LegacyHiddenComponent: {
              workInProgress2.lanes = NoLanes;
              return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
            }
          }
          return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        function beginWork(current2, workInProgress2, renderLanes2) {
          {
            if (workInProgress2._debugNeedsRemount && current2 !== null) {
              return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes));
            }
          }
          if (current2 !== null) {
            var oldProps = current2.memoizedProps;
            var newProps = workInProgress2.pendingProps;
            if (oldProps !== newProps || hasContextChanged() || // Force a re-render if the implementation changed due to hot reload:
            workInProgress2.type !== current2.type) {
              didReceiveUpdate = true;
            } else {
              var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2);
              if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
              // may not be work scheduled on `current`, so we check for this flag.
              (workInProgress2.flags & DidCapture) === NoFlags) {
                didReceiveUpdate = false;
                return attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2);
              }
              if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
                didReceiveUpdate = true;
              } else {
                didReceiveUpdate = false;
              }
            }
          } else {
            didReceiveUpdate = false;
            if (getIsHydrating() && isForkedChild(workInProgress2)) {
              var slotIndex = workInProgress2.index;
              var numberOfForks = getForksAtLevel();
              pushTreeId(workInProgress2, numberOfForks, slotIndex);
            }
          }
          workInProgress2.lanes = NoLanes;
          switch (workInProgress2.tag) {
            case IndeterminateComponent: {
              return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2);
            }
            case LazyComponent: {
              var elementType = workInProgress2.elementType;
              return mountLazyComponent(current2, workInProgress2, elementType, renderLanes2);
            }
            case FunctionComponent: {
              var Component2 = workInProgress2.type;
              var unresolvedProps = workInProgress2.pendingProps;
              var resolvedProps = workInProgress2.elementType === Component2 ? unresolvedProps : resolveDefaultProps(Component2, unresolvedProps);
              return updateFunctionComponent(current2, workInProgress2, Component2, resolvedProps, renderLanes2);
            }
            case ClassComponent: {
              var _Component = workInProgress2.type;
              var _unresolvedProps = workInProgress2.pendingProps;
              var _resolvedProps = workInProgress2.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);
              return updateClassComponent(current2, workInProgress2, _Component, _resolvedProps, renderLanes2);
            }
            case HostRoot:
              return updateHostRoot(current2, workInProgress2, renderLanes2);
            case HostComponent:
              return updateHostComponent(current2, workInProgress2, renderLanes2);
            case HostText:
              return updateHostText(current2, workInProgress2);
            case SuspenseComponent:
              return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
            case HostPortal:
              return updatePortalComponent(current2, workInProgress2, renderLanes2);
            case ForwardRef: {
              var type = workInProgress2.type;
              var _unresolvedProps2 = workInProgress2.pendingProps;
              var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
              return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2);
            }
            case Fragment21:
              return updateFragment(current2, workInProgress2, renderLanes2);
            case Mode:
              return updateMode(current2, workInProgress2, renderLanes2);
            case Profiler:
              return updateProfiler(current2, workInProgress2, renderLanes2);
            case ContextProvider:
              return updateContextProvider(current2, workInProgress2, renderLanes2);
            case ContextConsumer:
              return updateContextConsumer(current2, workInProgress2, renderLanes2);
            case MemoComponent: {
              var _type2 = workInProgress2.type;
              var _unresolvedProps3 = workInProgress2.pendingProps;
              var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
              {
                if (workInProgress2.type !== workInProgress2.elementType) {
                  var outerPropTypes = _type2.propTypes;
                  if (outerPropTypes) {
                    checkPropTypes(
                      outerPropTypes,
                      _resolvedProps3,
                      // Resolved for outer only
                      "prop",
                      getComponentNameFromType(_type2)
                    );
                  }
                }
              }
              _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
              return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, renderLanes2);
            }
            case SimpleMemoComponent: {
              return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
            }
            case IncompleteClassComponent: {
              var _Component2 = workInProgress2.type;
              var _unresolvedProps4 = workInProgress2.pendingProps;
              var _resolvedProps4 = workInProgress2.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);
              return mountIncompleteClassComponent(current2, workInProgress2, _Component2, _resolvedProps4, renderLanes2);
            }
            case SuspenseListComponent: {
              return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
            }
            case ScopeComponent: {
              break;
            }
            case OffscreenComponent: {
              return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
            }
          }
          throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
        }
        function markUpdate(workInProgress2) {
          workInProgress2.flags |= Update;
        }
        function markRef$1(workInProgress2) {
          workInProgress2.flags |= Ref;
          {
            workInProgress2.flags |= RefStatic;
          }
        }
        var appendAllChildren;
        var updateHostContainer;
        var updateHostComponent$1;
        var updateHostText$1;
        {
          appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden5) {
            var node = workInProgress2.child;
            while (node !== null) {
              if (node.tag === HostComponent || node.tag === HostText) {
                appendInitialChild(parent, node.stateNode);
              } else if (node.tag === HostPortal)
                ;
              else if (node.child !== null) {
                node.child.return = node;
                node = node.child;
                continue;
              }
              if (node === workInProgress2) {
                return;
              }
              while (node.sibling === null) {
                if (node.return === null || node.return === workInProgress2) {
                  return;
                }
                node = node.return;
              }
              node.sibling.return = node.return;
              node = node.sibling;
            }
          };
          updateHostContainer = function(current2, workInProgress2) {
          };
          updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) {
            var oldProps = current2.memoizedProps;
            if (oldProps === newProps) {
              return;
            }
            var instance = workInProgress2.stateNode;
            var currentHostContext = getHostContext();
            var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
            workInProgress2.updateQueue = updatePayload;
            if (updatePayload) {
              markUpdate(workInProgress2);
            }
          };
          updateHostText$1 = function(current2, workInProgress2, oldText, newText) {
            if (oldText !== newText) {
              markUpdate(workInProgress2);
            }
          };
        }
        function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
          if (getIsHydrating()) {
            return;
          }
          switch (renderState.tailMode) {
            case "hidden": {
              var tailNode = renderState.tail;
              var lastTailNode = null;
              while (tailNode !== null) {
                if (tailNode.alternate !== null) {
                  lastTailNode = tailNode;
                }
                tailNode = tailNode.sibling;
              }
              if (lastTailNode === null) {
                renderState.tail = null;
              } else {
                lastTailNode.sibling = null;
              }
              break;
            }
            case "collapsed": {
              var _tailNode = renderState.tail;
              var _lastTailNode = null;
              while (_tailNode !== null) {
                if (_tailNode.alternate !== null) {
                  _lastTailNode = _tailNode;
                }
                _tailNode = _tailNode.sibling;
              }
              if (_lastTailNode === null) {
                if (!hasRenderedATailFallback && renderState.tail !== null) {
                  renderState.tail.sibling = null;
                } else {
                  renderState.tail = null;
                }
              } else {
                _lastTailNode.sibling = null;
              }
              break;
            }
          }
        }
        function bubbleProperties(completedWork) {
          var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
          var newChildLanes = NoLanes;
          var subtreeFlags = NoFlags;
          if (!didBailout) {
            if ((completedWork.mode & ProfileMode) !== NoMode) {
              var actualDuration = completedWork.actualDuration;
              var treeBaseDuration = completedWork.selfBaseDuration;
              var child = completedWork.child;
              while (child !== null) {
                newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
                subtreeFlags |= child.subtreeFlags;
                subtreeFlags |= child.flags;
                actualDuration += child.actualDuration;
                treeBaseDuration += child.treeBaseDuration;
                child = child.sibling;
              }
              completedWork.actualDuration = actualDuration;
              completedWork.treeBaseDuration = treeBaseDuration;
            } else {
              var _child = completedWork.child;
              while (_child !== null) {
                newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
                subtreeFlags |= _child.subtreeFlags;
                subtreeFlags |= _child.flags;
                _child.return = completedWork;
                _child = _child.sibling;
              }
            }
            completedWork.subtreeFlags |= subtreeFlags;
          } else {
            if ((completedWork.mode & ProfileMode) !== NoMode) {
              var _treeBaseDuration = completedWork.selfBaseDuration;
              var _child2 = completedWork.child;
              while (_child2 !== null) {
                newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes));
                subtreeFlags |= _child2.subtreeFlags & StaticMask;
                subtreeFlags |= _child2.flags & StaticMask;
                _treeBaseDuration += _child2.treeBaseDuration;
                _child2 = _child2.sibling;
              }
              completedWork.treeBaseDuration = _treeBaseDuration;
            } else {
              var _child3 = completedWork.child;
              while (_child3 !== null) {
                newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes));
                subtreeFlags |= _child3.subtreeFlags & StaticMask;
                subtreeFlags |= _child3.flags & StaticMask;
                _child3.return = completedWork;
                _child3 = _child3.sibling;
              }
            }
            completedWork.subtreeFlags |= subtreeFlags;
          }
          completedWork.childLanes = newChildLanes;
          return didBailout;
        }
        function completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState) {
          if (hasUnhydratedTailNodes() && (workInProgress2.mode & ConcurrentMode) !== NoMode && (workInProgress2.flags & DidCapture) === NoFlags) {
            warnIfUnhydratedTailNodes(workInProgress2);
            resetHydrationState();
            workInProgress2.flags |= ForceClientRender | Incomplete | ShouldCapture;
            return false;
          }
          var wasHydrated = popHydrationState(workInProgress2);
          if (nextState !== null && nextState.dehydrated !== null) {
            if (current2 === null) {
              if (!wasHydrated) {
                throw new Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.");
              }
              prepareToHydrateHostSuspenseInstance(workInProgress2);
              bubbleProperties(workInProgress2);
              {
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  var isTimedOutSuspense = nextState !== null;
                  if (isTimedOutSuspense) {
                    var primaryChildFragment = workInProgress2.child;
                    if (primaryChildFragment !== null) {
                      workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
                    }
                  }
                }
              }
              return false;
            } else {
              resetHydrationState();
              if ((workInProgress2.flags & DidCapture) === NoFlags) {
                workInProgress2.memoizedState = null;
              }
              workInProgress2.flags |= Update;
              bubbleProperties(workInProgress2);
              {
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  var _isTimedOutSuspense = nextState !== null;
                  if (_isTimedOutSuspense) {
                    var _primaryChildFragment = workInProgress2.child;
                    if (_primaryChildFragment !== null) {
                      workInProgress2.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
                    }
                  }
                }
              }
              return false;
            }
          } else {
            upgradeHydrationErrorsToRecoverable();
            return true;
          }
        }
        function completeWork(current2, workInProgress2, renderLanes2) {
          var newProps = workInProgress2.pendingProps;
          popTreeContext(workInProgress2);
          switch (workInProgress2.tag) {
            case IndeterminateComponent:
            case LazyComponent:
            case SimpleMemoComponent:
            case FunctionComponent:
            case ForwardRef:
            case Fragment21:
            case Mode:
            case Profiler:
            case ContextConsumer:
            case MemoComponent:
              bubbleProperties(workInProgress2);
              return null;
            case ClassComponent: {
              var Component2 = workInProgress2.type;
              if (isContextProvider(Component2)) {
                popContext(workInProgress2);
              }
              bubbleProperties(workInProgress2);
              return null;
            }
            case HostRoot: {
              var fiberRoot = workInProgress2.stateNode;
              popHostContainer(workInProgress2);
              popTopLevelContextObject(workInProgress2);
              resetWorkInProgressVersions();
              if (fiberRoot.pendingContext) {
                fiberRoot.context = fiberRoot.pendingContext;
                fiberRoot.pendingContext = null;
              }
              if (current2 === null || current2.child === null) {
                var wasHydrated = popHydrationState(workInProgress2);
                if (wasHydrated) {
                  markUpdate(workInProgress2);
                } else {
                  if (current2 !== null) {
                    var prevState = current2.memoizedState;
                    if (
                      // Check if this is a client root
                      !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
                      (workInProgress2.flags & ForceClientRender) !== NoFlags
                    ) {
                      workInProgress2.flags |= Snapshot;
                      upgradeHydrationErrorsToRecoverable();
                    }
                  }
                }
              }
              updateHostContainer(current2, workInProgress2);
              bubbleProperties(workInProgress2);
              return null;
            }
            case HostComponent: {
              popHostContext(workInProgress2);
              var rootContainerInstance = getRootHostContainer();
              var type = workInProgress2.type;
              if (current2 !== null && workInProgress2.stateNode != null) {
                updateHostComponent$1(current2, workInProgress2, type, newProps, rootContainerInstance);
                if (current2.ref !== workInProgress2.ref) {
                  markRef$1(workInProgress2);
                }
              } else {
                if (!newProps) {
                  if (workInProgress2.stateNode === null) {
                    throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                  }
                  bubbleProperties(workInProgress2);
                  return null;
                }
                var currentHostContext = getHostContext();
                var _wasHydrated = popHydrationState(workInProgress2);
                if (_wasHydrated) {
                  if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) {
                    markUpdate(workInProgress2);
                  }
                } else {
                  var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress2);
                  appendAllChildren(instance, workInProgress2, false, false);
                  workInProgress2.stateNode = instance;
                  if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
                    markUpdate(workInProgress2);
                  }
                }
                if (workInProgress2.ref !== null) {
                  markRef$1(workInProgress2);
                }
              }
              bubbleProperties(workInProgress2);
              return null;
            }
            case HostText: {
              var newText = newProps;
              if (current2 && workInProgress2.stateNode != null) {
                var oldText = current2.memoizedProps;
                updateHostText$1(current2, workInProgress2, oldText, newText);
              } else {
                if (typeof newText !== "string") {
                  if (workInProgress2.stateNode === null) {
                    throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                  }
                }
                var _rootContainerInstance = getRootHostContainer();
                var _currentHostContext = getHostContext();
                var _wasHydrated2 = popHydrationState(workInProgress2);
                if (_wasHydrated2) {
                  if (prepareToHydrateHostTextInstance(workInProgress2)) {
                    markUpdate(workInProgress2);
                  }
                } else {
                  workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2);
                }
              }
              bubbleProperties(workInProgress2);
              return null;
            }
            case SuspenseComponent: {
              popSuspenseContext(workInProgress2);
              var nextState = workInProgress2.memoizedState;
              if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) {
                var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState);
                if (!fallthroughToNormalSuspensePath) {
                  if (workInProgress2.flags & ShouldCapture) {
                    return workInProgress2;
                  } else {
                    return null;
                  }
                }
              }
              if ((workInProgress2.flags & DidCapture) !== NoFlags) {
                workInProgress2.lanes = renderLanes2;
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  transferActualDuration(workInProgress2);
                }
                return workInProgress2;
              }
              var nextDidTimeout = nextState !== null;
              var prevDidTimeout = current2 !== null && current2.memoizedState !== null;
              if (nextDidTimeout !== prevDidTimeout) {
                if (nextDidTimeout) {
                  var _offscreenFiber2 = workInProgress2.child;
                  _offscreenFiber2.flags |= Visibility;
                  if ((workInProgress2.mode & ConcurrentMode) !== NoMode) {
                    var hasInvisibleChildContext = current2 === null && (workInProgress2.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback);
                    if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
                      renderDidSuspend();
                    } else {
                      renderDidSuspendDelayIfPossible();
                    }
                  }
                }
              }
              var wakeables = workInProgress2.updateQueue;
              if (wakeables !== null) {
                workInProgress2.flags |= Update;
              }
              bubbleProperties(workInProgress2);
              {
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  if (nextDidTimeout) {
                    var primaryChildFragment = workInProgress2.child;
                    if (primaryChildFragment !== null) {
                      workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
                    }
                  }
                }
              }
              return null;
            }
            case HostPortal:
              popHostContainer(workInProgress2);
              updateHostContainer(current2, workInProgress2);
              if (current2 === null) {
                preparePortalMount(workInProgress2.stateNode.containerInfo);
              }
              bubbleProperties(workInProgress2);
              return null;
            case ContextProvider:
              var context = workInProgress2.type._context;
              popProvider(context, workInProgress2);
              bubbleProperties(workInProgress2);
              return null;
            case IncompleteClassComponent: {
              var _Component = workInProgress2.type;
              if (isContextProvider(_Component)) {
                popContext(workInProgress2);
              }
              bubbleProperties(workInProgress2);
              return null;
            }
            case SuspenseListComponent: {
              popSuspenseContext(workInProgress2);
              var renderState = workInProgress2.memoizedState;
              if (renderState === null) {
                bubbleProperties(workInProgress2);
                return null;
              }
              var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags;
              var renderedTail = renderState.rendering;
              if (renderedTail === null) {
                if (!didSuspendAlready) {
                  var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags);
                  if (!cannotBeSuspended) {
                    var row = workInProgress2.child;
                    while (row !== null) {
                      var suspended = findFirstSuspended(row);
                      if (suspended !== null) {
                        didSuspendAlready = true;
                        workInProgress2.flags |= DidCapture;
                        cutOffTailIfNeeded(renderState, false);
                        var newThenables = suspended.updateQueue;
                        if (newThenables !== null) {
                          workInProgress2.updateQueue = newThenables;
                          workInProgress2.flags |= Update;
                        }
                        workInProgress2.subtreeFlags = NoFlags;
                        resetChildFibers(workInProgress2, renderLanes2);
                        pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
                        return workInProgress2.child;
                      }
                      row = row.sibling;
                    }
                  }
                  if (renderState.tail !== null && now3() > getRenderTargetTime()) {
                    workInProgress2.flags |= DidCapture;
                    didSuspendAlready = true;
                    cutOffTailIfNeeded(renderState, false);
                    workInProgress2.lanes = SomeRetryLane;
                  }
                } else {
                  cutOffTailIfNeeded(renderState, false);
                }
              } else {
                if (!didSuspendAlready) {
                  var _suspended = findFirstSuspended(renderedTail);
                  if (_suspended !== null) {
                    workInProgress2.flags |= DidCapture;
                    didSuspendAlready = true;
                    var _newThenables = _suspended.updateQueue;
                    if (_newThenables !== null) {
                      workInProgress2.updateQueue = _newThenables;
                      workInProgress2.flags |= Update;
                    }
                    cutOffTailIfNeeded(renderState, true);
                    if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) {
                      bubbleProperties(workInProgress2);
                      return null;
                    }
                  } else if (
                    // The time it took to render last row is greater than the remaining
                    // time we have to render. So rendering one more row would likely
                    // exceed it.
                    now3() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane
                  ) {
                    workInProgress2.flags |= DidCapture;
                    didSuspendAlready = true;
                    cutOffTailIfNeeded(renderState, false);
                    workInProgress2.lanes = SomeRetryLane;
                  }
                }
                if (renderState.isBackwards) {
                  renderedTail.sibling = workInProgress2.child;
                  workInProgress2.child = renderedTail;
                } else {
                  var previousSibling = renderState.last;
                  if (previousSibling !== null) {
                    previousSibling.sibling = renderedTail;
                  } else {
                    workInProgress2.child = renderedTail;
                  }
                  renderState.last = renderedTail;
                }
              }
              if (renderState.tail !== null) {
                var next = renderState.tail;
                renderState.rendering = next;
                renderState.tail = next.sibling;
                renderState.renderingStartTime = now3();
                next.sibling = null;
                var suspenseContext = suspenseStackCursor.current;
                if (didSuspendAlready) {
                  suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
                } else {
                  suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
                }
                pushSuspenseContext(workInProgress2, suspenseContext);
                return next;
              }
              bubbleProperties(workInProgress2);
              return null;
            }
            case ScopeComponent: {
              break;
            }
            case OffscreenComponent:
            case LegacyHiddenComponent: {
              popRenderLanes(workInProgress2);
              var _nextState = workInProgress2.memoizedState;
              var nextIsHidden = _nextState !== null;
              if (current2 !== null) {
                var _prevState = current2.memoizedState;
                var prevIsHidden = _prevState !== null;
                if (prevIsHidden !== nextIsHidden && // LegacyHidden doesn't do any hiding — it only pre-renders.
                !enableLegacyHidden) {
                  workInProgress2.flags |= Visibility;
                }
              }
              if (!nextIsHidden || (workInProgress2.mode & ConcurrentMode) === NoMode) {
                bubbleProperties(workInProgress2);
              } else {
                if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
                  bubbleProperties(workInProgress2);
                  {
                    if (workInProgress2.subtreeFlags & (Placement | Update)) {
                      workInProgress2.flags |= Visibility;
                    }
                  }
                }
              }
              return null;
            }
            case CacheComponent: {
              return null;
            }
            case TracingMarkerComponent: {
              return null;
            }
          }
          throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
        }
        function unwindWork(current2, workInProgress2, renderLanes2) {
          popTreeContext(workInProgress2);
          switch (workInProgress2.tag) {
            case ClassComponent: {
              var Component2 = workInProgress2.type;
              if (isContextProvider(Component2)) {
                popContext(workInProgress2);
              }
              var flags = workInProgress2.flags;
              if (flags & ShouldCapture) {
                workInProgress2.flags = flags & ~ShouldCapture | DidCapture;
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  transferActualDuration(workInProgress2);
                }
                return workInProgress2;
              }
              return null;
            }
            case HostRoot: {
              var root3 = workInProgress2.stateNode;
              popHostContainer(workInProgress2);
              popTopLevelContextObject(workInProgress2);
              resetWorkInProgressVersions();
              var _flags = workInProgress2.flags;
              if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
                workInProgress2.flags = _flags & ~ShouldCapture | DidCapture;
                return workInProgress2;
              }
              return null;
            }
            case HostComponent: {
              popHostContext(workInProgress2);
              return null;
            }
            case SuspenseComponent: {
              popSuspenseContext(workInProgress2);
              var suspenseState = workInProgress2.memoizedState;
              if (suspenseState !== null && suspenseState.dehydrated !== null) {
                if (workInProgress2.alternate === null) {
                  throw new Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue.");
                }
                resetHydrationState();
              }
              var _flags2 = workInProgress2.flags;
              if (_flags2 & ShouldCapture) {
                workInProgress2.flags = _flags2 & ~ShouldCapture | DidCapture;
                if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                  transferActualDuration(workInProgress2);
                }
                return workInProgress2;
              }
              return null;
            }
            case SuspenseListComponent: {
              popSuspenseContext(workInProgress2);
              return null;
            }
            case HostPortal:
              popHostContainer(workInProgress2);
              return null;
            case ContextProvider:
              var context = workInProgress2.type._context;
              popProvider(context, workInProgress2);
              return null;
            case OffscreenComponent:
            case LegacyHiddenComponent:
              popRenderLanes(workInProgress2);
              return null;
            case CacheComponent:
              return null;
            default:
              return null;
          }
        }
        function unwindInterruptedWork(current2, interruptedWork, renderLanes2) {
          popTreeContext(interruptedWork);
          switch (interruptedWork.tag) {
            case ClassComponent: {
              var childContextTypes = interruptedWork.type.childContextTypes;
              if (childContextTypes !== null && childContextTypes !== void 0) {
                popContext(interruptedWork);
              }
              break;
            }
            case HostRoot: {
              var root3 = interruptedWork.stateNode;
              popHostContainer(interruptedWork);
              popTopLevelContextObject(interruptedWork);
              resetWorkInProgressVersions();
              break;
            }
            case HostComponent: {
              popHostContext(interruptedWork);
              break;
            }
            case HostPortal:
              popHostContainer(interruptedWork);
              break;
            case SuspenseComponent:
              popSuspenseContext(interruptedWork);
              break;
            case SuspenseListComponent:
              popSuspenseContext(interruptedWork);
              break;
            case ContextProvider:
              var context = interruptedWork.type._context;
              popProvider(context, interruptedWork);
              break;
            case OffscreenComponent:
            case LegacyHiddenComponent:
              popRenderLanes(interruptedWork);
              break;
          }
        }
        var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
        {
          didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
        }
        var offscreenSubtreeIsHidden = false;
        var offscreenSubtreeWasHidden = false;
        var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set;
        var nextEffect = null;
        var inProgressLanes = null;
        var inProgressRoot = null;
        function reportUncaughtErrorInDEV(error2) {
          {
            invokeGuardedCallback(null, function() {
              throw error2;
            });
            clearCaughtError();
          }
        }
        var callComponentWillUnmountWithTimer = function(current2, instance) {
          instance.props = current2.memoizedProps;
          instance.state = current2.memoizedState;
          if (current2.mode & ProfileMode) {
            try {
              startLayoutEffectTimer();
              instance.componentWillUnmount();
            } finally {
              recordLayoutEffectDuration(current2);
            }
          } else {
            instance.componentWillUnmount();
          }
        };
        function safelyCallCommitHookLayoutEffectListMount(current2, nearestMountedAncestor) {
          try {
            commitHookEffectListMount(Layout, current2);
          } catch (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }
        function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) {
          try {
            callComponentWillUnmountWithTimer(current2, instance);
          } catch (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }
        function safelyCallComponentDidMount(current2, nearestMountedAncestor, instance) {
          try {
            instance.componentDidMount();
          } catch (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }
        function safelyAttachRef(current2, nearestMountedAncestor) {
          try {
            commitAttachRef(current2);
          } catch (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }
        function safelyDetachRef(current2, nearestMountedAncestor) {
          var ref = current2.ref;
          if (ref !== null) {
            if (typeof ref === "function") {
              var retVal;
              try {
                if (enableProfilerTimer && enableProfilerCommitHooks && current2.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    retVal = ref(null);
                  } finally {
                    recordLayoutEffectDuration(current2);
                  }
                } else {
                  retVal = ref(null);
                }
              } catch (error2) {
                captureCommitPhaseError(current2, nearestMountedAncestor, error2);
              }
              {
                if (typeof retVal === "function") {
                  error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(current2));
                }
              }
            } else {
              ref.current = null;
            }
          }
        }
        function safelyCallDestroy(current2, nearestMountedAncestor, destroy) {
          try {
            destroy();
          } catch (error2) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error2);
          }
        }
        var focusedInstanceHandle = null;
        var shouldFireAfterActiveInstanceBlur = false;
        function commitBeforeMutationEffects(root3, firstChild) {
          focusedInstanceHandle = prepareForCommit(root3.containerInfo);
          nextEffect = firstChild;
          commitBeforeMutationEffects_begin();
          var shouldFire = shouldFireAfterActiveInstanceBlur;
          shouldFireAfterActiveInstanceBlur = false;
          focusedInstanceHandle = null;
          return shouldFire;
        }
        function commitBeforeMutationEffects_begin() {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var child = fiber.child;
            if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
              child.return = fiber;
              nextEffect = child;
            } else {
              commitBeforeMutationEffects_complete();
            }
          }
        }
        function commitBeforeMutationEffects_complete() {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            setCurrentFiber(fiber);
            try {
              commitBeforeMutationEffectsOnFiber(fiber);
            } catch (error2) {
              captureCommitPhaseError(fiber, fiber.return, error2);
            }
            resetCurrentFiber();
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function commitBeforeMutationEffectsOnFiber(finishedWork) {
          var current2 = finishedWork.alternate;
          var flags = finishedWork.flags;
          if ((flags & Snapshot) !== NoFlags) {
            setCurrentFiber(finishedWork);
            switch (finishedWork.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                break;
              }
              case ClassComponent: {
                if (current2 !== null) {
                  var prevProps = current2.memoizedProps;
                  var prevState = current2.memoizedState;
                  var instance = finishedWork.stateNode;
                  {
                    if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                      if (instance.props !== finishedWork.memoizedProps) {
                        error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                      }
                      if (instance.state !== finishedWork.memoizedState) {
                        error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                      }
                    }
                  }
                  var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
                  {
                    var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
                    if (snapshot === void 0 && !didWarnSet.has(finishedWork.type)) {
                      didWarnSet.add(finishedWork.type);
                      error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentNameFromFiber(finishedWork));
                    }
                  }
                  instance.__reactInternalSnapshotBeforeUpdate = snapshot;
                }
                break;
              }
              case HostRoot: {
                {
                  var root3 = finishedWork.stateNode;
                  clearContainer(root3.containerInfo);
                }
                break;
              }
              case HostComponent:
              case HostText:
              case HostPortal:
              case IncompleteClassComponent:
                break;
              default: {
                throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
              }
            }
            resetCurrentFiber();
          }
        }
        function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
          var updateQueue = finishedWork.updateQueue;
          var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
          if (lastEffect !== null) {
            var firstEffect = lastEffect.next;
            var effect = firstEffect;
            do {
              if ((effect.tag & flags) === flags) {
                var destroy = effect.destroy;
                effect.destroy = void 0;
                if (destroy !== void 0) {
                  {
                    if ((flags & Passive$1) !== NoFlags$1) {
                      markComponentPassiveEffectUnmountStarted(finishedWork);
                    } else if ((flags & Layout) !== NoFlags$1) {
                      markComponentLayoutEffectUnmountStarted(finishedWork);
                    }
                  }
                  {
                    if ((flags & Insertion) !== NoFlags$1) {
                      setIsRunningInsertionEffect(true);
                    }
                  }
                  safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
                  {
                    if ((flags & Insertion) !== NoFlags$1) {
                      setIsRunningInsertionEffect(false);
                    }
                  }
                  {
                    if ((flags & Passive$1) !== NoFlags$1) {
                      markComponentPassiveEffectUnmountStopped();
                    } else if ((flags & Layout) !== NoFlags$1) {
                      markComponentLayoutEffectUnmountStopped();
                    }
                  }
                }
              }
              effect = effect.next;
            } while (effect !== firstEffect);
          }
        }
        function commitHookEffectListMount(flags, finishedWork) {
          var updateQueue = finishedWork.updateQueue;
          var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
          if (lastEffect !== null) {
            var firstEffect = lastEffect.next;
            var effect = firstEffect;
            do {
              if ((effect.tag & flags) === flags) {
                {
                  if ((flags & Passive$1) !== NoFlags$1) {
                    markComponentPassiveEffectMountStarted(finishedWork);
                  } else if ((flags & Layout) !== NoFlags$1) {
                    markComponentLayoutEffectMountStarted(finishedWork);
                  }
                }
                var create9 = effect.create;
                {
                  if ((flags & Insertion) !== NoFlags$1) {
                    setIsRunningInsertionEffect(true);
                  }
                }
                effect.destroy = create9();
                {
                  if ((flags & Insertion) !== NoFlags$1) {
                    setIsRunningInsertionEffect(false);
                  }
                }
                {
                  if ((flags & Passive$1) !== NoFlags$1) {
                    markComponentPassiveEffectMountStopped();
                  } else if ((flags & Layout) !== NoFlags$1) {
                    markComponentLayoutEffectMountStopped();
                  }
                }
                {
                  var destroy = effect.destroy;
                  if (destroy !== void 0 && typeof destroy !== "function") {
                    var hookName = void 0;
                    if ((effect.tag & Layout) !== NoFlags) {
                      hookName = "useLayoutEffect";
                    } else if ((effect.tag & Insertion) !== NoFlags) {
                      hookName = "useInsertionEffect";
                    } else {
                      hookName = "useEffect";
                    }
                    var addendum = void 0;
                    if (destroy === null) {
                      addendum = " You returned null. If your effect does not require clean up, return undefined (or nothing).";
                    } else if (typeof destroy.then === "function") {
                      addendum = "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching";
                    } else {
                      addendum = " You returned: " + destroy;
                    }
                    error("%s must not return anything besides a function, which is used for clean-up.%s", hookName, addendum);
                  }
                }
              }
              effect = effect.next;
            } while (effect !== firstEffect);
          }
        }
        function commitPassiveEffectDurations(finishedRoot, finishedWork) {
          {
            if ((finishedWork.flags & Update) !== NoFlags) {
              switch (finishedWork.tag) {
                case Profiler: {
                  var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
                  var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit;
                  var commitTime2 = getCommitTime();
                  var phase = finishedWork.alternate === null ? "mount" : "update";
                  {
                    if (isCurrentUpdateNested()) {
                      phase = "nested-update";
                    }
                  }
                  if (typeof onPostCommit === "function") {
                    onPostCommit(id, phase, passiveEffectDuration, commitTime2);
                  }
                  var parentFiber = finishedWork.return;
                  outer:
                    while (parentFiber !== null) {
                      switch (parentFiber.tag) {
                        case HostRoot:
                          var root3 = parentFiber.stateNode;
                          root3.passiveEffectDuration += passiveEffectDuration;
                          break outer;
                        case Profiler:
                          var parentStateNode = parentFiber.stateNode;
                          parentStateNode.passiveEffectDuration += passiveEffectDuration;
                          break outer;
                      }
                      parentFiber = parentFiber.return;
                    }
                  break;
                }
              }
            }
          }
        }
        function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork, committedLanes) {
          if ((finishedWork.flags & LayoutMask) !== NoFlags) {
            switch (finishedWork.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                if (!offscreenSubtreeWasHidden) {
                  if (finishedWork.mode & ProfileMode) {
                    try {
                      startLayoutEffectTimer();
                      commitHookEffectListMount(Layout | HasEffect, finishedWork);
                    } finally {
                      recordLayoutEffectDuration(finishedWork);
                    }
                  } else {
                    commitHookEffectListMount(Layout | HasEffect, finishedWork);
                  }
                }
                break;
              }
              case ClassComponent: {
                var instance = finishedWork.stateNode;
                if (finishedWork.flags & Update) {
                  if (!offscreenSubtreeWasHidden) {
                    if (current2 === null) {
                      {
                        if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                          if (instance.props !== finishedWork.memoizedProps) {
                            error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                          }
                          if (instance.state !== finishedWork.memoizedState) {
                            error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                          }
                        }
                      }
                      if (finishedWork.mode & ProfileMode) {
                        try {
                          startLayoutEffectTimer();
                          instance.componentDidMount();
                        } finally {
                          recordLayoutEffectDuration(finishedWork);
                        }
                      } else {
                        instance.componentDidMount();
                      }
                    } else {
                      var prevProps = finishedWork.elementType === finishedWork.type ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps);
                      var prevState = current2.memoizedState;
                      {
                        if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                          if (instance.props !== finishedWork.memoizedProps) {
                            error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                          }
                          if (instance.state !== finishedWork.memoizedState) {
                            error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                          }
                        }
                      }
                      if (finishedWork.mode & ProfileMode) {
                        try {
                          startLayoutEffectTimer();
                          instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                        } finally {
                          recordLayoutEffectDuration(finishedWork);
                        }
                      } else {
                        instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
                      }
                    }
                  }
                }
                var updateQueue = finishedWork.updateQueue;
                if (updateQueue !== null) {
                  {
                    if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                      if (instance.props !== finishedWork.memoizedProps) {
                        error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                      }
                      if (instance.state !== finishedWork.memoizedState) {
                        error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                      }
                    }
                  }
                  commitUpdateQueue(finishedWork, updateQueue, instance);
                }
                break;
              }
              case HostRoot: {
                var _updateQueue = finishedWork.updateQueue;
                if (_updateQueue !== null) {
                  var _instance = null;
                  if (finishedWork.child !== null) {
                    switch (finishedWork.child.tag) {
                      case HostComponent:
                        _instance = getPublicInstance(finishedWork.child.stateNode);
                        break;
                      case ClassComponent:
                        _instance = finishedWork.child.stateNode;
                        break;
                    }
                  }
                  commitUpdateQueue(finishedWork, _updateQueue, _instance);
                }
                break;
              }
              case HostComponent: {
                var _instance2 = finishedWork.stateNode;
                if (current2 === null && finishedWork.flags & Update) {
                  var type = finishedWork.type;
                  var props = finishedWork.memoizedProps;
                  commitMount(_instance2, type, props);
                }
                break;
              }
              case HostText: {
                break;
              }
              case HostPortal: {
                break;
              }
              case Profiler: {
                {
                  var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender;
                  var effectDuration = finishedWork.stateNode.effectDuration;
                  var commitTime2 = getCommitTime();
                  var phase = current2 === null ? "mount" : "update";
                  {
                    if (isCurrentUpdateNested()) {
                      phase = "nested-update";
                    }
                  }
                  if (typeof onRender === "function") {
                    onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2);
                  }
                  {
                    if (typeof onCommit === "function") {
                      onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime2);
                    }
                    enqueuePendingPassiveProfilerEffect(finishedWork);
                    var parentFiber = finishedWork.return;
                    outer:
                      while (parentFiber !== null) {
                        switch (parentFiber.tag) {
                          case HostRoot:
                            var root3 = parentFiber.stateNode;
                            root3.effectDuration += effectDuration;
                            break outer;
                          case Profiler:
                            var parentStateNode = parentFiber.stateNode;
                            parentStateNode.effectDuration += effectDuration;
                            break outer;
                        }
                        parentFiber = parentFiber.return;
                      }
                  }
                }
                break;
              }
              case SuspenseComponent: {
                commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
                break;
              }
              case SuspenseListComponent:
              case IncompleteClassComponent:
              case ScopeComponent:
              case OffscreenComponent:
              case LegacyHiddenComponent:
              case TracingMarkerComponent: {
                break;
              }
              default:
                throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          if (!offscreenSubtreeWasHidden) {
            {
              if (finishedWork.flags & Ref) {
                commitAttachRef(finishedWork);
              }
            }
          }
        }
        function reappearLayoutEffectsOnFiber(node) {
          switch (node.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              if (node.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  safelyCallCommitHookLayoutEffectListMount(node, node.return);
                } finally {
                  recordLayoutEffectDuration(node);
                }
              } else {
                safelyCallCommitHookLayoutEffectListMount(node, node.return);
              }
              break;
            }
            case ClassComponent: {
              var instance = node.stateNode;
              if (typeof instance.componentDidMount === "function") {
                safelyCallComponentDidMount(node, node.return, instance);
              }
              safelyAttachRef(node, node.return);
              break;
            }
            case HostComponent: {
              safelyAttachRef(node, node.return);
              break;
            }
          }
        }
        function hideOrUnhideAllChildren(finishedWork, isHidden5) {
          var hostSubtreeRoot = null;
          {
            var node = finishedWork;
            while (true) {
              if (node.tag === HostComponent) {
                if (hostSubtreeRoot === null) {
                  hostSubtreeRoot = node;
                  try {
                    var instance = node.stateNode;
                    if (isHidden5) {
                      hideInstance(instance);
                    } else {
                      unhideInstance(node.stateNode, node.memoizedProps);
                    }
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                }
              } else if (node.tag === HostText) {
                if (hostSubtreeRoot === null) {
                  try {
                    var _instance3 = node.stateNode;
                    if (isHidden5) {
                      hideTextInstance(_instance3);
                    } else {
                      unhideTextInstance(_instance3, node.memoizedProps);
                    }
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                }
              } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork)
                ;
              else if (node.child !== null) {
                node.child.return = node;
                node = node.child;
                continue;
              }
              if (node === finishedWork) {
                return;
              }
              while (node.sibling === null) {
                if (node.return === null || node.return === finishedWork) {
                  return;
                }
                if (hostSubtreeRoot === node) {
                  hostSubtreeRoot = null;
                }
                node = node.return;
              }
              if (hostSubtreeRoot === node) {
                hostSubtreeRoot = null;
              }
              node.sibling.return = node.return;
              node = node.sibling;
            }
          }
        }
        function commitAttachRef(finishedWork) {
          var ref = finishedWork.ref;
          if (ref !== null) {
            var instance = finishedWork.stateNode;
            var instanceToUse;
            switch (finishedWork.tag) {
              case HostComponent:
                instanceToUse = getPublicInstance(instance);
                break;
              default:
                instanceToUse = instance;
            }
            if (typeof ref === "function") {
              var retVal;
              if (finishedWork.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  retVal = ref(instanceToUse);
                } finally {
                  recordLayoutEffectDuration(finishedWork);
                }
              } else {
                retVal = ref(instanceToUse);
              }
              {
                if (typeof retVal === "function") {
                  error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(finishedWork));
                }
              }
            } else {
              {
                if (!ref.hasOwnProperty("current")) {
                  error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentNameFromFiber(finishedWork));
                }
              }
              ref.current = instanceToUse;
            }
          }
        }
        function detachFiberMutation(fiber) {
          var alternate = fiber.alternate;
          if (alternate !== null) {
            alternate.return = null;
          }
          fiber.return = null;
        }
        function detachFiberAfterEffects(fiber) {
          var alternate = fiber.alternate;
          if (alternate !== null) {
            fiber.alternate = null;
            detachFiberAfterEffects(alternate);
          }
          {
            fiber.child = null;
            fiber.deletions = null;
            fiber.sibling = null;
            if (fiber.tag === HostComponent) {
              var hostInstance = fiber.stateNode;
              if (hostInstance !== null) {
                detachDeletedInstance(hostInstance);
              }
            }
            fiber.stateNode = null;
            {
              fiber._debugOwner = null;
            }
            {
              fiber.return = null;
              fiber.dependencies = null;
              fiber.memoizedProps = null;
              fiber.memoizedState = null;
              fiber.pendingProps = null;
              fiber.stateNode = null;
              fiber.updateQueue = null;
            }
          }
        }
        function getHostParentFiber(fiber) {
          var parent = fiber.return;
          while (parent !== null) {
            if (isHostParent(parent)) {
              return parent;
            }
            parent = parent.return;
          }
          throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
        }
        function isHostParent(fiber) {
          return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
        }
        function getHostSibling(fiber) {
          var node = fiber;
          siblings:
            while (true) {
              while (node.sibling === null) {
                if (node.return === null || isHostParent(node.return)) {
                  return null;
                }
                node = node.return;
              }
              node.sibling.return = node.return;
              node = node.sibling;
              while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
                if (node.flags & Placement) {
                  continue siblings;
                }
                if (node.child === null || node.tag === HostPortal) {
                  continue siblings;
                } else {
                  node.child.return = node;
                  node = node.child;
                }
              }
              if (!(node.flags & Placement)) {
                return node.stateNode;
              }
            }
        }
        function commitPlacement(finishedWork) {
          var parentFiber = getHostParentFiber(finishedWork);
          switch (parentFiber.tag) {
            case HostComponent: {
              var parent = parentFiber.stateNode;
              if (parentFiber.flags & ContentReset) {
                resetTextContent(parent);
                parentFiber.flags &= ~ContentReset;
              }
              var before = getHostSibling(finishedWork);
              insertOrAppendPlacementNode(finishedWork, before, parent);
              break;
            }
            case HostRoot:
            case HostPortal: {
              var _parent = parentFiber.stateNode.containerInfo;
              var _before = getHostSibling(finishedWork);
              insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
              break;
            }
            default:
              throw new Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
          var tag = node.tag;
          var isHost = tag === HostComponent || tag === HostText;
          if (isHost) {
            var stateNode = node.stateNode;
            if (before) {
              insertInContainerBefore(parent, stateNode, before);
            } else {
              appendChildToContainer(parent, stateNode);
            }
          } else if (tag === HostPortal)
            ;
          else {
            var child = node.child;
            if (child !== null) {
              insertOrAppendPlacementNodeIntoContainer(child, before, parent);
              var sibling = child.sibling;
              while (sibling !== null) {
                insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
                sibling = sibling.sibling;
              }
            }
          }
        }
        function insertOrAppendPlacementNode(node, before, parent) {
          var tag = node.tag;
          var isHost = tag === HostComponent || tag === HostText;
          if (isHost) {
            var stateNode = node.stateNode;
            if (before) {
              insertBefore(parent, stateNode, before);
            } else {
              appendChild(parent, stateNode);
            }
          } else if (tag === HostPortal)
            ;
          else {
            var child = node.child;
            if (child !== null) {
              insertOrAppendPlacementNode(child, before, parent);
              var sibling = child.sibling;
              while (sibling !== null) {
                insertOrAppendPlacementNode(sibling, before, parent);
                sibling = sibling.sibling;
              }
            }
          }
        }
        var hostParent = null;
        var hostParentIsContainer = false;
        function commitDeletionEffects(root3, returnFiber, deletedFiber) {
          {
            var parent = returnFiber;
            findParent:
              while (parent !== null) {
                switch (parent.tag) {
                  case HostComponent: {
                    hostParent = parent.stateNode;
                    hostParentIsContainer = false;
                    break findParent;
                  }
                  case HostRoot: {
                    hostParent = parent.stateNode.containerInfo;
                    hostParentIsContainer = true;
                    break findParent;
                  }
                  case HostPortal: {
                    hostParent = parent.stateNode.containerInfo;
                    hostParentIsContainer = true;
                    break findParent;
                  }
                }
                parent = parent.return;
              }
            if (hostParent === null) {
              throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
            }
            commitDeletionEffectsOnFiber(root3, returnFiber, deletedFiber);
            hostParent = null;
            hostParentIsContainer = false;
          }
          detachFiberMutation(deletedFiber);
        }
        function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
          var child = parent.child;
          while (child !== null) {
            commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
            child = child.sibling;
          }
        }
        function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
          onCommitUnmount(deletedFiber);
          switch (deletedFiber.tag) {
            case HostComponent: {
              if (!offscreenSubtreeWasHidden) {
                safelyDetachRef(deletedFiber, nearestMountedAncestor);
              }
            }
            case HostText: {
              {
                var prevHostParent = hostParent;
                var prevHostParentIsContainer = hostParentIsContainer;
                hostParent = null;
                recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
                hostParent = prevHostParent;
                hostParentIsContainer = prevHostParentIsContainer;
                if (hostParent !== null) {
                  if (hostParentIsContainer) {
                    removeChildFromContainer(hostParent, deletedFiber.stateNode);
                  } else {
                    removeChild(hostParent, deletedFiber.stateNode);
                  }
                }
              }
              return;
            }
            case DehydratedFragment: {
              {
                if (hostParent !== null) {
                  if (hostParentIsContainer) {
                    clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
                  } else {
                    clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
                  }
                }
              }
              return;
            }
            case HostPortal: {
              {
                var _prevHostParent = hostParent;
                var _prevHostParentIsContainer = hostParentIsContainer;
                hostParent = deletedFiber.stateNode.containerInfo;
                hostParentIsContainer = true;
                recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
                hostParent = _prevHostParent;
                hostParentIsContainer = _prevHostParentIsContainer;
              }
              return;
            }
            case FunctionComponent:
            case ForwardRef:
            case MemoComponent:
            case SimpleMemoComponent: {
              if (!offscreenSubtreeWasHidden) {
                var updateQueue = deletedFiber.updateQueue;
                if (updateQueue !== null) {
                  var lastEffect = updateQueue.lastEffect;
                  if (lastEffect !== null) {
                    var firstEffect = lastEffect.next;
                    var effect = firstEffect;
                    do {
                      var _effect = effect, destroy = _effect.destroy, tag = _effect.tag;
                      if (destroy !== void 0) {
                        if ((tag & Insertion) !== NoFlags$1) {
                          safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                        } else if ((tag & Layout) !== NoFlags$1) {
                          {
                            markComponentLayoutEffectUnmountStarted(deletedFiber);
                          }
                          if (deletedFiber.mode & ProfileMode) {
                            startLayoutEffectTimer();
                            safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                            recordLayoutEffectDuration(deletedFiber);
                          } else {
                            safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                          }
                          {
                            markComponentLayoutEffectUnmountStopped();
                          }
                        }
                      }
                      effect = effect.next;
                    } while (effect !== firstEffect);
                  }
                }
              }
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              return;
            }
            case ClassComponent: {
              if (!offscreenSubtreeWasHidden) {
                safelyDetachRef(deletedFiber, nearestMountedAncestor);
                var instance = deletedFiber.stateNode;
                if (typeof instance.componentWillUnmount === "function") {
                  safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance);
                }
              }
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              return;
            }
            case ScopeComponent: {
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              return;
            }
            case OffscreenComponent: {
              if (
                // TODO: Remove this dead flag
                deletedFiber.mode & ConcurrentMode
              ) {
                var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
                offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
                recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
                offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
              } else {
                recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              }
              break;
            }
            default: {
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              return;
            }
          }
        }
        function commitSuspenseCallback(finishedWork) {
          var newState = finishedWork.memoizedState;
        }
        function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
          var newState = finishedWork.memoizedState;
          if (newState === null) {
            var current2 = finishedWork.alternate;
            if (current2 !== null) {
              var prevState = current2.memoizedState;
              if (prevState !== null) {
                var suspenseInstance = prevState.dehydrated;
                if (suspenseInstance !== null) {
                  commitHydratedSuspenseInstance(suspenseInstance);
                }
              }
            }
          }
        }
        function attachSuspenseRetryListeners(finishedWork) {
          var wakeables = finishedWork.updateQueue;
          if (wakeables !== null) {
            finishedWork.updateQueue = null;
            var retryCache = finishedWork.stateNode;
            if (retryCache === null) {
              retryCache = finishedWork.stateNode = new PossiblyWeakSet();
            }
            wakeables.forEach(function(wakeable) {
              var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
              if (!retryCache.has(wakeable)) {
                retryCache.add(wakeable);
                {
                  if (isDevToolsPresent) {
                    if (inProgressLanes !== null && inProgressRoot !== null) {
                      restorePendingUpdaters(inProgressRoot, inProgressLanes);
                    } else {
                      throw Error("Expected finished root and lanes to be set. This is a bug in React.");
                    }
                  }
                }
                wakeable.then(retry, retry);
              }
            });
          }
        }
        function commitMutationEffects(root3, finishedWork, committedLanes) {
          inProgressLanes = committedLanes;
          inProgressRoot = root3;
          setCurrentFiber(finishedWork);
          commitMutationEffectsOnFiber(finishedWork, root3);
          setCurrentFiber(finishedWork);
          inProgressLanes = null;
          inProgressRoot = null;
        }
        function recursivelyTraverseMutationEffects(root3, parentFiber, lanes) {
          var deletions = parentFiber.deletions;
          if (deletions !== null) {
            for (var i3 = 0; i3 < deletions.length; i3++) {
              var childToDelete = deletions[i3];
              try {
                commitDeletionEffects(root3, parentFiber, childToDelete);
              } catch (error2) {
                captureCommitPhaseError(childToDelete, parentFiber, error2);
              }
            }
          }
          var prevDebugFiber = getCurrentFiber();
          if (parentFiber.subtreeFlags & MutationMask) {
            var child = parentFiber.child;
            while (child !== null) {
              setCurrentFiber(child);
              commitMutationEffectsOnFiber(child, root3);
              child = child.sibling;
            }
          }
          setCurrentFiber(prevDebugFiber);
        }
        function commitMutationEffectsOnFiber(finishedWork, root3, lanes) {
          var current2 = finishedWork.alternate;
          var flags = finishedWork.flags;
          switch (finishedWork.tag) {
            case FunctionComponent:
            case ForwardRef:
            case MemoComponent:
            case SimpleMemoComponent: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Update) {
                try {
                  commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
                  commitHookEffectListMount(Insertion | HasEffect, finishedWork);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
                if (finishedWork.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                  recordLayoutEffectDuration(finishedWork);
                } else {
                  try {
                    commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                }
              }
              return;
            }
            case ClassComponent: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Ref) {
                if (current2 !== null) {
                  safelyDetachRef(current2, current2.return);
                }
              }
              return;
            }
            case HostComponent: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Ref) {
                if (current2 !== null) {
                  safelyDetachRef(current2, current2.return);
                }
              }
              {
                if (finishedWork.flags & ContentReset) {
                  var instance = finishedWork.stateNode;
                  try {
                    resetTextContent(instance);
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                }
                if (flags & Update) {
                  var _instance4 = finishedWork.stateNode;
                  if (_instance4 != null) {
                    var newProps = finishedWork.memoizedProps;
                    var oldProps = current2 !== null ? current2.memoizedProps : newProps;
                    var type = finishedWork.type;
                    var updatePayload = finishedWork.updateQueue;
                    finishedWork.updateQueue = null;
                    if (updatePayload !== null) {
                      try {
                        commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork);
                      } catch (error2) {
                        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                      }
                    }
                  }
                }
              }
              return;
            }
            case HostText: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Update) {
                {
                  if (finishedWork.stateNode === null) {
                    throw new Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
                  }
                  var textInstance = finishedWork.stateNode;
                  var newText = finishedWork.memoizedProps;
                  var oldText = current2 !== null ? current2.memoizedProps : newText;
                  try {
                    commitTextUpdate(textInstance, oldText, newText);
                  } catch (error2) {
                    captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                  }
                }
              }
              return;
            }
            case HostRoot: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Update) {
                {
                  if (current2 !== null) {
                    var prevRootState = current2.memoizedState;
                    if (prevRootState.isDehydrated) {
                      try {
                        commitHydratedContainer(root3.containerInfo);
                      } catch (error2) {
                        captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                      }
                    }
                  }
                }
              }
              return;
            }
            case HostPortal: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              return;
            }
            case SuspenseComponent: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              var offscreenFiber = finishedWork.child;
              if (offscreenFiber.flags & Visibility) {
                var offscreenInstance = offscreenFiber.stateNode;
                var newState = offscreenFiber.memoizedState;
                var isHidden5 = newState !== null;
                offscreenInstance.isHidden = isHidden5;
                if (isHidden5) {
                  var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;
                  if (!wasHidden) {
                    markCommitTimeOfFallback();
                  }
                }
              }
              if (flags & Update) {
                try {
                  commitSuspenseCallback(finishedWork);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
                attachSuspenseRetryListeners(finishedWork);
              }
              return;
            }
            case OffscreenComponent: {
              var _wasHidden = current2 !== null && current2.memoizedState !== null;
              if (
                // TODO: Remove this dead flag
                finishedWork.mode & ConcurrentMode
              ) {
                var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
                offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
                recursivelyTraverseMutationEffects(root3, finishedWork);
                offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
              } else {
                recursivelyTraverseMutationEffects(root3, finishedWork);
              }
              commitReconciliationEffects(finishedWork);
              if (flags & Visibility) {
                var _offscreenInstance = finishedWork.stateNode;
                var _newState = finishedWork.memoizedState;
                var _isHidden = _newState !== null;
                var offscreenBoundary = finishedWork;
                _offscreenInstance.isHidden = _isHidden;
                {
                  if (_isHidden) {
                    if (!_wasHidden) {
                      if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
                        nextEffect = offscreenBoundary;
                        var offscreenChild = offscreenBoundary.child;
                        while (offscreenChild !== null) {
                          nextEffect = offscreenChild;
                          disappearLayoutEffects_begin(offscreenChild);
                          offscreenChild = offscreenChild.sibling;
                        }
                      }
                    }
                  }
                }
                {
                  hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
                }
              }
              return;
            }
            case SuspenseListComponent: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              if (flags & Update) {
                attachSuspenseRetryListeners(finishedWork);
              }
              return;
            }
            case ScopeComponent: {
              return;
            }
            default: {
              recursivelyTraverseMutationEffects(root3, finishedWork);
              commitReconciliationEffects(finishedWork);
              return;
            }
          }
        }
        function commitReconciliationEffects(finishedWork) {
          var flags = finishedWork.flags;
          if (flags & Placement) {
            try {
              commitPlacement(finishedWork);
            } catch (error2) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error2);
            }
            finishedWork.flags &= ~Placement;
          }
          if (flags & Hydrating) {
            finishedWork.flags &= ~Hydrating;
          }
        }
        function commitLayoutEffects(finishedWork, root3, committedLanes) {
          inProgressLanes = committedLanes;
          inProgressRoot = root3;
          nextEffect = finishedWork;
          commitLayoutEffects_begin(finishedWork, root3, committedLanes);
          inProgressLanes = null;
          inProgressRoot = null;
        }
        function commitLayoutEffects_begin(subtreeRoot, root3, committedLanes) {
          var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var firstChild = fiber.child;
            if (fiber.tag === OffscreenComponent && isModernRoot) {
              var isHidden5 = fiber.memoizedState !== null;
              var newOffscreenSubtreeIsHidden = isHidden5 || offscreenSubtreeIsHidden;
              if (newOffscreenSubtreeIsHidden) {
                commitLayoutMountEffects_complete(subtreeRoot, root3, committedLanes);
                continue;
              } else {
                var current2 = fiber.alternate;
                var wasHidden = current2 !== null && current2.memoizedState !== null;
                var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
                var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
                var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
                offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
                offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;
                if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
                  nextEffect = fiber;
                  reappearLayoutEffects_begin(fiber);
                }
                var child = firstChild;
                while (child !== null) {
                  nextEffect = child;
                  commitLayoutEffects_begin(
                    child,
                    // New root; bubble back up to here and stop.
                    root3,
                    committedLanes
                  );
                  child = child.sibling;
                }
                nextEffect = fiber;
                offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
                offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
                commitLayoutMountEffects_complete(subtreeRoot, root3, committedLanes);
                continue;
              }
            }
            if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
              firstChild.return = fiber;
              nextEffect = firstChild;
            } else {
              commitLayoutMountEffects_complete(subtreeRoot, root3, committedLanes);
            }
          }
        }
        function commitLayoutMountEffects_complete(subtreeRoot, root3, committedLanes) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            if ((fiber.flags & LayoutMask) !== NoFlags) {
              var current2 = fiber.alternate;
              setCurrentFiber(fiber);
              try {
                commitLayoutEffectOnFiber(root3, current2, fiber, committedLanes);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              resetCurrentFiber();
            }
            if (fiber === subtreeRoot) {
              nextEffect = null;
              return;
            }
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function disappearLayoutEffects_begin(subtreeRoot) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var firstChild = fiber.child;
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case MemoComponent:
              case SimpleMemoComponent: {
                if (fiber.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    commitHookEffectListUnmount(Layout, fiber, fiber.return);
                  } finally {
                    recordLayoutEffectDuration(fiber);
                  }
                } else {
                  commitHookEffectListUnmount(Layout, fiber, fiber.return);
                }
                break;
              }
              case ClassComponent: {
                safelyDetachRef(fiber, fiber.return);
                var instance = fiber.stateNode;
                if (typeof instance.componentWillUnmount === "function") {
                  safelyCallComponentWillUnmount(fiber, fiber.return, instance);
                }
                break;
              }
              case HostComponent: {
                safelyDetachRef(fiber, fiber.return);
                break;
              }
              case OffscreenComponent: {
                var isHidden5 = fiber.memoizedState !== null;
                if (isHidden5) {
                  disappearLayoutEffects_complete(subtreeRoot);
                  continue;
                }
                break;
              }
            }
            if (firstChild !== null) {
              firstChild.return = fiber;
              nextEffect = firstChild;
            } else {
              disappearLayoutEffects_complete(subtreeRoot);
            }
          }
        }
        function disappearLayoutEffects_complete(subtreeRoot) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            if (fiber === subtreeRoot) {
              nextEffect = null;
              return;
            }
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function reappearLayoutEffects_begin(subtreeRoot) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var firstChild = fiber.child;
            if (fiber.tag === OffscreenComponent) {
              var isHidden5 = fiber.memoizedState !== null;
              if (isHidden5) {
                reappearLayoutEffects_complete(subtreeRoot);
                continue;
              }
            }
            if (firstChild !== null) {
              firstChild.return = fiber;
              nextEffect = firstChild;
            } else {
              reappearLayoutEffects_complete(subtreeRoot);
            }
          }
        }
        function reappearLayoutEffects_complete(subtreeRoot) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            setCurrentFiber(fiber);
            try {
              reappearLayoutEffectsOnFiber(fiber);
            } catch (error2) {
              captureCommitPhaseError(fiber, fiber.return, error2);
            }
            resetCurrentFiber();
            if (fiber === subtreeRoot) {
              nextEffect = null;
              return;
            }
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function commitPassiveMountEffects(root3, finishedWork, committedLanes, committedTransitions) {
          nextEffect = finishedWork;
          commitPassiveMountEffects_begin(finishedWork, root3, committedLanes, committedTransitions);
        }
        function commitPassiveMountEffects_begin(subtreeRoot, root3, committedLanes, committedTransitions) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var firstChild = fiber.child;
            if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
              firstChild.return = fiber;
              nextEffect = firstChild;
            } else {
              commitPassiveMountEffects_complete(subtreeRoot, root3, committedLanes, committedTransitions);
            }
          }
        }
        function commitPassiveMountEffects_complete(subtreeRoot, root3, committedLanes, committedTransitions) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            if ((fiber.flags & Passive) !== NoFlags) {
              setCurrentFiber(fiber);
              try {
                commitPassiveMountOnFiber(root3, fiber, committedLanes, committedTransitions);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              resetCurrentFiber();
            }
            if (fiber === subtreeRoot) {
              nextEffect = null;
              return;
            }
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
          switch (finishedWork.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              if (finishedWork.mode & ProfileMode) {
                startPassiveEffectTimer();
                try {
                  commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
                } finally {
                  recordPassiveEffectDuration(finishedWork);
                }
              } else {
                commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
              }
              break;
            }
          }
        }
        function commitPassiveUnmountEffects(firstChild) {
          nextEffect = firstChild;
          commitPassiveUnmountEffects_begin();
        }
        function commitPassiveUnmountEffects_begin() {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var child = fiber.child;
            if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
              var deletions = fiber.deletions;
              if (deletions !== null) {
                for (var i3 = 0; i3 < deletions.length; i3++) {
                  var fiberToDelete = deletions[i3];
                  nextEffect = fiberToDelete;
                  commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
                }
                {
                  var previousFiber = fiber.alternate;
                  if (previousFiber !== null) {
                    var detachedChild = previousFiber.child;
                    if (detachedChild !== null) {
                      previousFiber.child = null;
                      do {
                        var detachedSibling = detachedChild.sibling;
                        detachedChild.sibling = null;
                        detachedChild = detachedSibling;
                      } while (detachedChild !== null);
                    }
                  }
                }
                nextEffect = fiber;
              }
            }
            if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
              child.return = fiber;
              nextEffect = child;
            } else {
              commitPassiveUnmountEffects_complete();
            }
          }
        }
        function commitPassiveUnmountEffects_complete() {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            if ((fiber.flags & Passive) !== NoFlags) {
              setCurrentFiber(fiber);
              commitPassiveUnmountOnFiber(fiber);
              resetCurrentFiber();
            }
            var sibling = fiber.sibling;
            if (sibling !== null) {
              sibling.return = fiber.return;
              nextEffect = sibling;
              return;
            }
            nextEffect = fiber.return;
          }
        }
        function commitPassiveUnmountOnFiber(finishedWork) {
          switch (finishedWork.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              if (finishedWork.mode & ProfileMode) {
                startPassiveEffectTimer();
                commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
                recordPassiveEffectDuration(finishedWork);
              } else {
                commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
              }
              break;
            }
          }
        }
        function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            setCurrentFiber(fiber);
            commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
            resetCurrentFiber();
            var child = fiber.child;
            if (child !== null) {
              child.return = fiber;
              nextEffect = child;
            } else {
              commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
            }
          }
        }
        function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
          while (nextEffect !== null) {
            var fiber = nextEffect;
            var sibling = fiber.sibling;
            var returnFiber = fiber.return;
            {
              detachFiberAfterEffects(fiber);
              if (fiber === deletedSubtreeRoot) {
                nextEffect = null;
                return;
              }
            }
            if (sibling !== null) {
              sibling.return = returnFiber;
              nextEffect = sibling;
              return;
            }
            nextEffect = returnFiber;
          }
        }
        function commitPassiveUnmountInsideDeletedTreeOnFiber(current2, nearestMountedAncestor) {
          switch (current2.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              if (current2.mode & ProfileMode) {
                startPassiveEffectTimer();
                commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor);
                recordPassiveEffectDuration(current2);
              } else {
                commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor);
              }
              break;
            }
          }
        }
        function invokeLayoutEffectMountInDEV(fiber) {
          {
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                try {
                  commitHookEffectListMount(Layout | HasEffect, fiber);
                } catch (error2) {
                  captureCommitPhaseError(fiber, fiber.return, error2);
                }
                break;
              }
              case ClassComponent: {
                var instance = fiber.stateNode;
                try {
                  instance.componentDidMount();
                } catch (error2) {
                  captureCommitPhaseError(fiber, fiber.return, error2);
                }
                break;
              }
            }
          }
        }
        function invokePassiveEffectMountInDEV(fiber) {
          {
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                try {
                  commitHookEffectListMount(Passive$1 | HasEffect, fiber);
                } catch (error2) {
                  captureCommitPhaseError(fiber, fiber.return, error2);
                }
                break;
              }
            }
          }
        }
        function invokeLayoutEffectUnmountInDEV(fiber) {
          {
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                try {
                  commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
                } catch (error2) {
                  captureCommitPhaseError(fiber, fiber.return, error2);
                }
                break;
              }
              case ClassComponent: {
                var instance = fiber.stateNode;
                if (typeof instance.componentWillUnmount === "function") {
                  safelyCallComponentWillUnmount(fiber, fiber.return, instance);
                }
                break;
              }
            }
          }
        }
        function invokePassiveEffectUnmountInDEV(fiber) {
          {
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                try {
                  commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
                } catch (error2) {
                  captureCommitPhaseError(fiber, fiber.return, error2);
                }
              }
            }
          }
        }
        var COMPONENT_TYPE = 0;
        var HAS_PSEUDO_CLASS_TYPE = 1;
        var ROLE_TYPE = 2;
        var TEST_NAME_TYPE = 3;
        var TEXT_TYPE = 4;
        if (typeof Symbol === "function" && Symbol.for) {
          var symbolFor = Symbol.for;
          COMPONENT_TYPE = symbolFor("selector.component");
          HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class");
          ROLE_TYPE = symbolFor("selector.role");
          TEST_NAME_TYPE = symbolFor("selector.test_id");
          TEXT_TYPE = symbolFor("selector.text");
        }
        var commitHooks = [];
        function onCommitRoot$1() {
          {
            commitHooks.forEach(function(commitHook) {
              return commitHook();
            });
          }
        }
        var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
        function isLegacyActEnvironment(fiber) {
          {
            var isReactActEnvironmentGlobal = (
              // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
              typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0
            );
            var jestIsDefined = typeof jest !== "undefined";
            return jestIsDefined && isReactActEnvironmentGlobal !== false;
          }
        }
        function isConcurrentActEnvironment() {
          {
            var isReactActEnvironmentGlobal = (
              // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
              typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0
            );
            if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
              error("The current testing environment is not configured to support act(...)");
            }
            return isReactActEnvironmentGlobal;
          }
        }
        var ceil = Math.ceil;
        var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
        var NoContext = (
          /*             */
          0
        );
        var BatchedContext = (
          /*               */
          1
        );
        var RenderContext = (
          /*                */
          2
        );
        var CommitContext = (
          /*                */
          4
        );
        var RootInProgress = 0;
        var RootFatalErrored = 1;
        var RootErrored = 2;
        var RootSuspended = 3;
        var RootSuspendedWithDelay = 4;
        var RootCompleted = 5;
        var RootDidNotComplete = 6;
        var executionContext = NoContext;
        var workInProgressRoot = null;
        var workInProgress = null;
        var workInProgressRootRenderLanes = NoLanes;
        var subtreeRenderLanes = NoLanes;
        var subtreeRenderLanesCursor = createCursor(NoLanes);
        var workInProgressRootExitStatus = RootInProgress;
        var workInProgressRootFatalError = null;
        var workInProgressRootIncludedLanes = NoLanes;
        var workInProgressRootSkippedLanes = NoLanes;
        var workInProgressRootInterleavedUpdatedLanes = NoLanes;
        var workInProgressRootPingedLanes = NoLanes;
        var workInProgressRootConcurrentErrors = null;
        var workInProgressRootRecoverableErrors = null;
        var globalMostRecentFallbackTime = 0;
        var FALLBACK_THROTTLE_MS = 500;
        var workInProgressRootRenderTargetTime = Infinity;
        var RENDER_TIMEOUT_MS = 500;
        var workInProgressTransitions = null;
        function resetRenderTimer() {
          workInProgressRootRenderTargetTime = now3() + RENDER_TIMEOUT_MS;
        }
        function getRenderTargetTime() {
          return workInProgressRootRenderTargetTime;
        }
        var hasUncaughtError = false;
        var firstUncaughtError = null;
        var legacyErrorBoundariesThatAlreadyFailed = null;
        var rootDoesHavePassiveEffects = false;
        var rootWithPendingPassiveEffects = null;
        var pendingPassiveEffectsLanes = NoLanes;
        var pendingPassiveProfilerEffects = [];
        var pendingPassiveTransitions = null;
        var NESTED_UPDATE_LIMIT = 50;
        var nestedUpdateCount = 0;
        var rootWithNestedUpdates = null;
        var isFlushingPassiveEffects = false;
        var didScheduleUpdateDuringPassiveEffects = false;
        var NESTED_PASSIVE_UPDATE_LIMIT = 50;
        var nestedPassiveUpdateCount = 0;
        var rootWithPassiveNestedUpdates = null;
        var currentEventTime = NoTimestamp;
        var currentEventTransitionLane = NoLanes;
        var isRunningInsertionEffect = false;
        function getWorkInProgressRoot() {
          return workInProgressRoot;
        }
        function requestEventTime() {
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
            return now3();
          }
          if (currentEventTime !== NoTimestamp) {
            return currentEventTime;
          }
          currentEventTime = now3();
          return currentEventTime;
        }
        function requestUpdateLane(fiber) {
          var mode = fiber.mode;
          if ((mode & ConcurrentMode) === NoMode) {
            return SyncLane;
          } else if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
            return pickArbitraryLane(workInProgressRootRenderLanes);
          }
          var isTransition = requestCurrentTransition() !== NoTransition;
          if (isTransition) {
            if (ReactCurrentBatchConfig$3.transition !== null) {
              var transition = ReactCurrentBatchConfig$3.transition;
              if (!transition._updatedFibers) {
                transition._updatedFibers = /* @__PURE__ */ new Set();
              }
              transition._updatedFibers.add(fiber);
            }
            if (currentEventTransitionLane === NoLane) {
              currentEventTransitionLane = claimNextTransitionLane();
            }
            return currentEventTransitionLane;
          }
          var updateLane = getCurrentUpdatePriority();
          if (updateLane !== NoLane) {
            return updateLane;
          }
          var eventLane = getCurrentEventPriority();
          return eventLane;
        }
        function requestRetryLane(fiber) {
          var mode = fiber.mode;
          if ((mode & ConcurrentMode) === NoMode) {
            return SyncLane;
          }
          return claimNextRetryLane();
        }
        function scheduleUpdateOnFiber(root3, fiber, lane, eventTime) {
          checkForNestedUpdates();
          {
            if (isRunningInsertionEffect) {
              error("useInsertionEffect must not schedule updates.");
            }
          }
          {
            if (isFlushingPassiveEffects) {
              didScheduleUpdateDuringPassiveEffects = true;
            }
          }
          markRootUpdated(root3, lane, eventTime);
          if ((executionContext & RenderContext) !== NoLanes && root3 === workInProgressRoot) {
            warnAboutRenderPhaseUpdatesInDEV(fiber);
          } else {
            {
              if (isDevToolsPresent) {
                addFiberToLanesMap(root3, fiber, lane);
              }
            }
            warnIfUpdatesNotWrappedWithActDEV(fiber);
            if (root3 === workInProgressRoot) {
              if ((executionContext & RenderContext) === NoContext) {
                workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
              }
              if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
                markRootSuspended$1(root3, workInProgressRootRenderLanes);
              }
            }
            ensureRootIsScheduled(root3, eventTime);
            if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
            !ReactCurrentActQueue$1.isBatchingLegacy) {
              resetRenderTimer();
              flushSyncCallbacksOnlyInLegacyMode();
            }
          }
        }
        function scheduleInitialHydrationOnRoot(root3, lane, eventTime) {
          var current2 = root3.current;
          current2.lanes = lane;
          markRootUpdated(root3, lane, eventTime);
          ensureRootIsScheduled(root3, eventTime);
        }
        function isUnsafeClassRenderPhaseUpdate(fiber) {
          return (
            // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
            // decided not to enable it.
            (executionContext & RenderContext) !== NoContext
          );
        }
        function ensureRootIsScheduled(root3, currentTime) {
          var existingCallbackNode = root3.callbackNode;
          markStarvedLanesAsExpired(root3, currentTime);
          var nextLanes = getNextLanes(root3, root3 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
          if (nextLanes === NoLanes) {
            if (existingCallbackNode !== null) {
              cancelCallback$1(existingCallbackNode);
            }
            root3.callbackNode = null;
            root3.callbackPriority = NoLane;
            return;
          }
          var newCallbackPriority = getHighestPriorityLane(nextLanes);
          var existingCallbackPriority = root3.callbackPriority;
          if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
          // Scheduler task, rather than an `act` task, cancel it and re-scheduled
          // on the `act` queue.
          !(ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
            {
              if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
                error("Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.");
              }
            }
            return;
          }
          if (existingCallbackNode != null) {
            cancelCallback$1(existingCallbackNode);
          }
          var newCallbackNode;
          if (newCallbackPriority === SyncLane) {
            if (root3.tag === LegacyRoot) {
              if (ReactCurrentActQueue$1.isBatchingLegacy !== null) {
                ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
              }
              scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root3));
            } else {
              scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root3));
            }
            {
              if (ReactCurrentActQueue$1.current !== null) {
                ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
              } else {
                scheduleMicrotask(function() {
                  if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
                    flushSyncCallbacks();
                  }
                });
              }
            }
            newCallbackNode = null;
          } else {
            var schedulerPriorityLevel;
            switch (lanesToEventPriority(nextLanes)) {
              case DiscreteEventPriority:
                schedulerPriorityLevel = ImmediatePriority;
                break;
              case ContinuousEventPriority:
                schedulerPriorityLevel = UserBlockingPriority;
                break;
              case DefaultEventPriority:
                schedulerPriorityLevel = NormalPriority;
                break;
              case IdleEventPriority:
                schedulerPriorityLevel = IdlePriority;
                break;
              default:
                schedulerPriorityLevel = NormalPriority;
                break;
            }
            newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root3));
          }
          root3.callbackPriority = newCallbackPriority;
          root3.callbackNode = newCallbackNode;
        }
        function performConcurrentWorkOnRoot(root3, didTimeout) {
          {
            resetNestedUpdateFlag();
          }
          currentEventTime = NoTimestamp;
          currentEventTransitionLane = NoLanes;
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
            throw new Error("Should not already be working.");
          }
          var originalCallbackNode = root3.callbackNode;
          var didFlushPassiveEffects = flushPassiveEffects();
          if (didFlushPassiveEffects) {
            if (root3.callbackNode !== originalCallbackNode) {
              return null;
            }
          }
          var lanes = getNextLanes(root3, root3 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
          if (lanes === NoLanes) {
            return null;
          }
          var shouldTimeSlice = !includesBlockingLane(root3, lanes) && !includesExpiredLane(root3, lanes) && !didTimeout;
          var exitStatus = shouldTimeSlice ? renderRootConcurrent(root3, lanes) : renderRootSync(root3, lanes);
          if (exitStatus !== RootInProgress) {
            if (exitStatus === RootErrored) {
              var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root3);
              if (errorRetryLanes !== NoLanes) {
                lanes = errorRetryLanes;
                exitStatus = recoverFromConcurrentError(root3, errorRetryLanes);
              }
            }
            if (exitStatus === RootFatalErrored) {
              var fatalError = workInProgressRootFatalError;
              prepareFreshStack(root3, NoLanes);
              markRootSuspended$1(root3, lanes);
              ensureRootIsScheduled(root3, now3());
              throw fatalError;
            }
            if (exitStatus === RootDidNotComplete) {
              markRootSuspended$1(root3, lanes);
            } else {
              var renderWasConcurrent = !includesBlockingLane(root3, lanes);
              var finishedWork = root3.current.alternate;
              if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
                exitStatus = renderRootSync(root3, lanes);
                if (exitStatus === RootErrored) {
                  var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root3);
                  if (_errorRetryLanes !== NoLanes) {
                    lanes = _errorRetryLanes;
                    exitStatus = recoverFromConcurrentError(root3, _errorRetryLanes);
                  }
                }
                if (exitStatus === RootFatalErrored) {
                  var _fatalError = workInProgressRootFatalError;
                  prepareFreshStack(root3, NoLanes);
                  markRootSuspended$1(root3, lanes);
                  ensureRootIsScheduled(root3, now3());
                  throw _fatalError;
                }
              }
              root3.finishedWork = finishedWork;
              root3.finishedLanes = lanes;
              finishConcurrentRender(root3, exitStatus, lanes);
            }
          }
          ensureRootIsScheduled(root3, now3());
          if (root3.callbackNode === originalCallbackNode) {
            return performConcurrentWorkOnRoot.bind(null, root3);
          }
          return null;
        }
        function recoverFromConcurrentError(root3, errorRetryLanes) {
          var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
          if (isRootDehydrated(root3)) {
            var rootWorkInProgress = prepareFreshStack(root3, errorRetryLanes);
            rootWorkInProgress.flags |= ForceClientRender;
            {
              errorHydratingContainer(root3.containerInfo);
            }
          }
          var exitStatus = renderRootSync(root3, errorRetryLanes);
          if (exitStatus !== RootErrored) {
            var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
            workInProgressRootRecoverableErrors = errorsFromFirstAttempt;
            if (errorsFromSecondAttempt !== null) {
              queueRecoverableErrors(errorsFromSecondAttempt);
            }
          }
          return exitStatus;
        }
        function queueRecoverableErrors(errors2) {
          if (workInProgressRootRecoverableErrors === null) {
            workInProgressRootRecoverableErrors = errors2;
          } else {
            workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors2);
          }
        }
        function finishConcurrentRender(root3, exitStatus, lanes) {
          switch (exitStatus) {
            case RootInProgress:
            case RootFatalErrored: {
              throw new Error("Root did not complete. This is a bug in React.");
            }
            case RootErrored: {
              commitRoot(root3, workInProgressRootRecoverableErrors, workInProgressTransitions);
              break;
            }
            case RootSuspended: {
              markRootSuspended$1(root3, lanes);
              if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
              !shouldForceFlushFallbacksInDEV()) {
                var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now3();
                if (msUntilTimeout > 10) {
                  var nextLanes = getNextLanes(root3, NoLanes);
                  if (nextLanes !== NoLanes) {
                    break;
                  }
                  var suspendedLanes = root3.suspendedLanes;
                  if (!isSubsetOfLanes(suspendedLanes, lanes)) {
                    var eventTime = requestEventTime();
                    markRootPinged(root3, suspendedLanes);
                    break;
                  }
                  root3.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root3, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
                  break;
                }
              }
              commitRoot(root3, workInProgressRootRecoverableErrors, workInProgressTransitions);
              break;
            }
            case RootSuspendedWithDelay: {
              markRootSuspended$1(root3, lanes);
              if (includesOnlyTransitions(lanes)) {
                break;
              }
              if (!shouldForceFlushFallbacksInDEV()) {
                var mostRecentEventTime = getMostRecentEventTime(root3, lanes);
                var eventTimeMs = mostRecentEventTime;
                var timeElapsedMs = now3() - eventTimeMs;
                var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs;
                if (_msUntilTimeout > 10) {
                  root3.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root3, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
                  break;
                }
              }
              commitRoot(root3, workInProgressRootRecoverableErrors, workInProgressTransitions);
              break;
            }
            case RootCompleted: {
              commitRoot(root3, workInProgressRootRecoverableErrors, workInProgressTransitions);
              break;
            }
            default: {
              throw new Error("Unknown root exit status.");
            }
          }
        }
        function isRenderConsistentWithExternalStores(finishedWork) {
          var node = finishedWork;
          while (true) {
            if (node.flags & StoreConsistency) {
              var updateQueue = node.updateQueue;
              if (updateQueue !== null) {
                var checks = updateQueue.stores;
                if (checks !== null) {
                  for (var i3 = 0; i3 < checks.length; i3++) {
                    var check = checks[i3];
                    var getSnapshot = check.getSnapshot;
                    var renderedValue = check.value;
                    try {
                      if (!objectIs(getSnapshot(), renderedValue)) {
                        return false;
                      }
                    } catch (error2) {
                      return false;
                    }
                  }
                }
              }
            }
            var child = node.child;
            if (node.subtreeFlags & StoreConsistency && child !== null) {
              child.return = node;
              node = child;
              continue;
            }
            if (node === finishedWork) {
              return true;
            }
            while (node.sibling === null) {
              if (node.return === null || node.return === finishedWork) {
                return true;
              }
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
          return true;
        }
        function markRootSuspended$1(root3, suspendedLanes) {
          suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
          suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
          markRootSuspended(root3, suspendedLanes);
        }
        function performSyncWorkOnRoot(root3) {
          {
            syncNestedUpdateFlag();
          }
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
            throw new Error("Should not already be working.");
          }
          flushPassiveEffects();
          var lanes = getNextLanes(root3, NoLanes);
          if (!includesSomeLane(lanes, SyncLane)) {
            ensureRootIsScheduled(root3, now3());
            return null;
          }
          var exitStatus = renderRootSync(root3, lanes);
          if (root3.tag !== LegacyRoot && exitStatus === RootErrored) {
            var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root3);
            if (errorRetryLanes !== NoLanes) {
              lanes = errorRetryLanes;
              exitStatus = recoverFromConcurrentError(root3, errorRetryLanes);
            }
          }
          if (exitStatus === RootFatalErrored) {
            var fatalError = workInProgressRootFatalError;
            prepareFreshStack(root3, NoLanes);
            markRootSuspended$1(root3, lanes);
            ensureRootIsScheduled(root3, now3());
            throw fatalError;
          }
          if (exitStatus === RootDidNotComplete) {
            throw new Error("Root did not complete. This is a bug in React.");
          }
          var finishedWork = root3.current.alternate;
          root3.finishedWork = finishedWork;
          root3.finishedLanes = lanes;
          commitRoot(root3, workInProgressRootRecoverableErrors, workInProgressTransitions);
          ensureRootIsScheduled(root3, now3());
          return null;
        }
        function flushRoot(root3, lanes) {
          if (lanes !== NoLanes) {
            markRootEntangled(root3, mergeLanes(lanes, SyncLane));
            ensureRootIsScheduled(root3, now3());
            if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
              resetRenderTimer();
              flushSyncCallbacks();
            }
          }
        }
        function batchedUpdates$1(fn, a3) {
          var prevExecutionContext = executionContext;
          executionContext |= BatchedContext;
          try {
            return fn(a3);
          } finally {
            executionContext = prevExecutionContext;
            if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
            !ReactCurrentActQueue$1.isBatchingLegacy) {
              resetRenderTimer();
              flushSyncCallbacksOnlyInLegacyMode();
            }
          }
        }
        function discreteUpdates(fn, a3, b3, c4, d3) {
          var previousPriority = getCurrentUpdatePriority();
          var prevTransition = ReactCurrentBatchConfig$3.transition;
          try {
            ReactCurrentBatchConfig$3.transition = null;
            setCurrentUpdatePriority(DiscreteEventPriority);
            return fn(a3, b3, c4, d3);
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig$3.transition = prevTransition;
            if (executionContext === NoContext) {
              resetRenderTimer();
            }
          }
        }
        function flushSync12(fn) {
          if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
            flushPassiveEffects();
          }
          var prevExecutionContext = executionContext;
          executionContext |= BatchedContext;
          var prevTransition = ReactCurrentBatchConfig$3.transition;
          var previousPriority = getCurrentUpdatePriority();
          try {
            ReactCurrentBatchConfig$3.transition = null;
            setCurrentUpdatePriority(DiscreteEventPriority);
            if (fn) {
              return fn();
            } else {
              return void 0;
            }
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig$3.transition = prevTransition;
            executionContext = prevExecutionContext;
            if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
              flushSyncCallbacks();
            }
          }
        }
        function isAlreadyRendering() {
          return (executionContext & (RenderContext | CommitContext)) !== NoContext;
        }
        function pushRenderLanes(fiber, lanes) {
          push3(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
          subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
          workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
        }
        function popRenderLanes(fiber) {
          subtreeRenderLanes = subtreeRenderLanesCursor.current;
          pop(subtreeRenderLanesCursor, fiber);
        }
        function prepareFreshStack(root3, lanes) {
          root3.finishedWork = null;
          root3.finishedLanes = NoLanes;
          var timeoutHandle = root3.timeoutHandle;
          if (timeoutHandle !== noTimeout) {
            root3.timeoutHandle = noTimeout;
            cancelTimeout(timeoutHandle);
          }
          if (workInProgress !== null) {
            var interruptedWork = workInProgress.return;
            while (interruptedWork !== null) {
              var current2 = interruptedWork.alternate;
              unwindInterruptedWork(current2, interruptedWork);
              interruptedWork = interruptedWork.return;
            }
          }
          workInProgressRoot = root3;
          var rootWorkInProgress = createWorkInProgress(root3.current, null);
          workInProgress = rootWorkInProgress;
          workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
          workInProgressRootExitStatus = RootInProgress;
          workInProgressRootFatalError = null;
          workInProgressRootSkippedLanes = NoLanes;
          workInProgressRootInterleavedUpdatedLanes = NoLanes;
          workInProgressRootPingedLanes = NoLanes;
          workInProgressRootConcurrentErrors = null;
          workInProgressRootRecoverableErrors = null;
          finishQueueingConcurrentUpdates();
          {
            ReactStrictModeWarnings.discardPendingWarnings();
          }
          return rootWorkInProgress;
        }
        function handleError(root3, thrownValue) {
          do {
            var erroredWork = workInProgress;
            try {
              resetContextDependencies();
              resetHooksAfterThrow();
              resetCurrentFiber();
              ReactCurrentOwner$2.current = null;
              if (erroredWork === null || erroredWork.return === null) {
                workInProgressRootExitStatus = RootFatalErrored;
                workInProgressRootFatalError = thrownValue;
                workInProgress = null;
                return;
              }
              if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
                stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
              }
              if (enableSchedulingProfiler) {
                markComponentRenderStopped();
                if (thrownValue !== null && typeof thrownValue === "object" && typeof thrownValue.then === "function") {
                  var wakeable = thrownValue;
                  markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
                } else {
                  markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
                }
              }
              throwException(root3, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
              completeUnitOfWork(erroredWork);
            } catch (yetAnotherThrownValue) {
              thrownValue = yetAnotherThrownValue;
              if (workInProgress === erroredWork && erroredWork !== null) {
                erroredWork = erroredWork.return;
                workInProgress = erroredWork;
              } else {
                erroredWork = workInProgress;
              }
              continue;
            }
            return;
          } while (true);
        }
        function pushDispatcher() {
          var prevDispatcher = ReactCurrentDispatcher$2.current;
          ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
          if (prevDispatcher === null) {
            return ContextOnlyDispatcher;
          } else {
            return prevDispatcher;
          }
        }
        function popDispatcher(prevDispatcher) {
          ReactCurrentDispatcher$2.current = prevDispatcher;
        }
        function markCommitTimeOfFallback() {
          globalMostRecentFallbackTime = now3();
        }
        function markSkippedUpdateLanes(lane) {
          workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
        }
        function renderDidSuspend() {
          if (workInProgressRootExitStatus === RootInProgress) {
            workInProgressRootExitStatus = RootSuspended;
          }
        }
        function renderDidSuspendDelayIfPossible() {
          if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
            workInProgressRootExitStatus = RootSuspendedWithDelay;
          }
          if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
            markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
          }
        }
        function renderDidError(error2) {
          if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
            workInProgressRootExitStatus = RootErrored;
          }
          if (workInProgressRootConcurrentErrors === null) {
            workInProgressRootConcurrentErrors = [error2];
          } else {
            workInProgressRootConcurrentErrors.push(error2);
          }
        }
        function renderHasNotSuspendedYet() {
          return workInProgressRootExitStatus === RootInProgress;
        }
        function renderRootSync(root3, lanes) {
          var prevExecutionContext = executionContext;
          executionContext |= RenderContext;
          var prevDispatcher = pushDispatcher();
          if (workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes) {
            {
              if (isDevToolsPresent) {
                var memoizedUpdaters = root3.memoizedUpdaters;
                if (memoizedUpdaters.size > 0) {
                  restorePendingUpdaters(root3, workInProgressRootRenderLanes);
                  memoizedUpdaters.clear();
                }
                movePendingFibersToMemoized(root3, lanes);
              }
            }
            workInProgressTransitions = getTransitionsForLanes();
            prepareFreshStack(root3, lanes);
          }
          {
            markRenderStarted(lanes);
          }
          do {
            try {
              workLoopSync();
              break;
            } catch (thrownValue) {
              handleError(root3, thrownValue);
            }
          } while (true);
          resetContextDependencies();
          executionContext = prevExecutionContext;
          popDispatcher(prevDispatcher);
          if (workInProgress !== null) {
            throw new Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
          }
          {
            markRenderStopped();
          }
          workInProgressRoot = null;
          workInProgressRootRenderLanes = NoLanes;
          return workInProgressRootExitStatus;
        }
        function workLoopSync() {
          while (workInProgress !== null) {
            performUnitOfWork(workInProgress);
          }
        }
        function renderRootConcurrent(root3, lanes) {
          var prevExecutionContext = executionContext;
          executionContext |= RenderContext;
          var prevDispatcher = pushDispatcher();
          if (workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes) {
            {
              if (isDevToolsPresent) {
                var memoizedUpdaters = root3.memoizedUpdaters;
                if (memoizedUpdaters.size > 0) {
                  restorePendingUpdaters(root3, workInProgressRootRenderLanes);
                  memoizedUpdaters.clear();
                }
                movePendingFibersToMemoized(root3, lanes);
              }
            }
            workInProgressTransitions = getTransitionsForLanes();
            resetRenderTimer();
            prepareFreshStack(root3, lanes);
          }
          {
            markRenderStarted(lanes);
          }
          do {
            try {
              workLoopConcurrent();
              break;
            } catch (thrownValue) {
              handleError(root3, thrownValue);
            }
          } while (true);
          resetContextDependencies();
          popDispatcher(prevDispatcher);
          executionContext = prevExecutionContext;
          if (workInProgress !== null) {
            {
              markRenderYielded();
            }
            return RootInProgress;
          } else {
            {
              markRenderStopped();
            }
            workInProgressRoot = null;
            workInProgressRootRenderLanes = NoLanes;
            return workInProgressRootExitStatus;
          }
        }
        function workLoopConcurrent() {
          while (workInProgress !== null && !shouldYield()) {
            performUnitOfWork(workInProgress);
          }
        }
        function performUnitOfWork(unitOfWork) {
          var current2 = unitOfWork.alternate;
          setCurrentFiber(unitOfWork);
          var next;
          if ((unitOfWork.mode & ProfileMode) !== NoMode) {
            startProfilerTimer(unitOfWork);
            next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
            stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
          } else {
            next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
          }
          resetCurrentFiber();
          unitOfWork.memoizedProps = unitOfWork.pendingProps;
          if (next === null) {
            completeUnitOfWork(unitOfWork);
          } else {
            workInProgress = next;
          }
          ReactCurrentOwner$2.current = null;
        }
        function completeUnitOfWork(unitOfWork) {
          var completedWork = unitOfWork;
          do {
            var current2 = completedWork.alternate;
            var returnFiber = completedWork.return;
            if ((completedWork.flags & Incomplete) === NoFlags) {
              setCurrentFiber(completedWork);
              var next = void 0;
              if ((completedWork.mode & ProfileMode) === NoMode) {
                next = completeWork(current2, completedWork, subtreeRenderLanes);
              } else {
                startProfilerTimer(completedWork);
                next = completeWork(current2, completedWork, subtreeRenderLanes);
                stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
              }
              resetCurrentFiber();
              if (next !== null) {
                workInProgress = next;
                return;
              }
            } else {
              var _next = unwindWork(current2, completedWork);
              if (_next !== null) {
                _next.flags &= HostEffectMask;
                workInProgress = _next;
                return;
              }
              if ((completedWork.mode & ProfileMode) !== NoMode) {
                stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
                var actualDuration = completedWork.actualDuration;
                var child = completedWork.child;
                while (child !== null) {
                  actualDuration += child.actualDuration;
                  child = child.sibling;
                }
                completedWork.actualDuration = actualDuration;
              }
              if (returnFiber !== null) {
                returnFiber.flags |= Incomplete;
                returnFiber.subtreeFlags = NoFlags;
                returnFiber.deletions = null;
              } else {
                workInProgressRootExitStatus = RootDidNotComplete;
                workInProgress = null;
                return;
              }
            }
            var siblingFiber = completedWork.sibling;
            if (siblingFiber !== null) {
              workInProgress = siblingFiber;
              return;
            }
            completedWork = returnFiber;
            workInProgress = completedWork;
          } while (completedWork !== null);
          if (workInProgressRootExitStatus === RootInProgress) {
            workInProgressRootExitStatus = RootCompleted;
          }
        }
        function commitRoot(root3, recoverableErrors, transitions) {
          var previousUpdateLanePriority = getCurrentUpdatePriority();
          var prevTransition = ReactCurrentBatchConfig$3.transition;
          try {
            ReactCurrentBatchConfig$3.transition = null;
            setCurrentUpdatePriority(DiscreteEventPriority);
            commitRootImpl(root3, recoverableErrors, transitions, previousUpdateLanePriority);
          } finally {
            ReactCurrentBatchConfig$3.transition = prevTransition;
            setCurrentUpdatePriority(previousUpdateLanePriority);
          }
          return null;
        }
        function commitRootImpl(root3, recoverableErrors, transitions, renderPriorityLevel) {
          do {
            flushPassiveEffects();
          } while (rootWithPendingPassiveEffects !== null);
          flushRenderPhaseStrictModeWarningsInDEV();
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
            throw new Error("Should not already be working.");
          }
          var finishedWork = root3.finishedWork;
          var lanes = root3.finishedLanes;
          {
            markCommitStarted(lanes);
          }
          if (finishedWork === null) {
            {
              markCommitStopped();
            }
            return null;
          } else {
            {
              if (lanes === NoLanes) {
                error("root.finishedLanes should not be empty during a commit. This is a bug in React.");
              }
            }
          }
          root3.finishedWork = null;
          root3.finishedLanes = NoLanes;
          if (finishedWork === root3.current) {
            throw new Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
          }
          root3.callbackNode = null;
          root3.callbackPriority = NoLane;
          var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
          markRootFinished(root3, remainingLanes);
          if (root3 === workInProgressRoot) {
            workInProgressRoot = null;
            workInProgress = null;
            workInProgressRootRenderLanes = NoLanes;
          }
          if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
            if (!rootDoesHavePassiveEffects) {
              rootDoesHavePassiveEffects = true;
              pendingPassiveTransitions = transitions;
              scheduleCallback$1(NormalPriority, function() {
                flushPassiveEffects();
                return null;
              });
            }
          }
          var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
          var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
          if (subtreeHasEffects || rootHasEffect) {
            var prevTransition = ReactCurrentBatchConfig$3.transition;
            ReactCurrentBatchConfig$3.transition = null;
            var previousPriority = getCurrentUpdatePriority();
            setCurrentUpdatePriority(DiscreteEventPriority);
            var prevExecutionContext = executionContext;
            executionContext |= CommitContext;
            ReactCurrentOwner$2.current = null;
            var shouldFireAfterActiveInstanceBlur2 = commitBeforeMutationEffects(root3, finishedWork);
            {
              recordCommitTime();
            }
            commitMutationEffects(root3, finishedWork, lanes);
            resetAfterCommit(root3.containerInfo);
            root3.current = finishedWork;
            {
              markLayoutEffectsStarted(lanes);
            }
            commitLayoutEffects(finishedWork, root3, lanes);
            {
              markLayoutEffectsStopped();
            }
            requestPaint();
            executionContext = prevExecutionContext;
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig$3.transition = prevTransition;
          } else {
            root3.current = finishedWork;
            {
              recordCommitTime();
            }
          }
          var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
          if (rootDoesHavePassiveEffects) {
            rootDoesHavePassiveEffects = false;
            rootWithPendingPassiveEffects = root3;
            pendingPassiveEffectsLanes = lanes;
          } else {
            {
              nestedPassiveUpdateCount = 0;
              rootWithPassiveNestedUpdates = null;
            }
          }
          remainingLanes = root3.pendingLanes;
          if (remainingLanes === NoLanes) {
            legacyErrorBoundariesThatAlreadyFailed = null;
          }
          {
            if (!rootDidHavePassiveEffects) {
              commitDoubleInvokeEffectsInDEV(root3.current, false);
            }
          }
          onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
          {
            if (isDevToolsPresent) {
              root3.memoizedUpdaters.clear();
            }
          }
          {
            onCommitRoot$1();
          }
          ensureRootIsScheduled(root3, now3());
          if (recoverableErrors !== null) {
            var onRecoverableError = root3.onRecoverableError;
            for (var i3 = 0; i3 < recoverableErrors.length; i3++) {
              var recoverableError = recoverableErrors[i3];
              var componentStack = recoverableError.stack;
              var digest = recoverableError.digest;
              onRecoverableError(recoverableError.value, {
                componentStack,
                digest
              });
            }
          }
          if (hasUncaughtError) {
            hasUncaughtError = false;
            var error$1 = firstUncaughtError;
            firstUncaughtError = null;
            throw error$1;
          }
          if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root3.tag !== LegacyRoot) {
            flushPassiveEffects();
          }
          remainingLanes = root3.pendingLanes;
          if (includesSomeLane(remainingLanes, SyncLane)) {
            {
              markNestedUpdateScheduled();
            }
            if (root3 === rootWithNestedUpdates) {
              nestedUpdateCount++;
            } else {
              nestedUpdateCount = 0;
              rootWithNestedUpdates = root3;
            }
          } else {
            nestedUpdateCount = 0;
          }
          flushSyncCallbacks();
          {
            markCommitStopped();
          }
          return null;
        }
        function flushPassiveEffects() {
          if (rootWithPendingPassiveEffects !== null) {
            var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
            var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
            var prevTransition = ReactCurrentBatchConfig$3.transition;
            var previousPriority = getCurrentUpdatePriority();
            try {
              ReactCurrentBatchConfig$3.transition = null;
              setCurrentUpdatePriority(priority);
              return flushPassiveEffectsImpl();
            } finally {
              setCurrentUpdatePriority(previousPriority);
              ReactCurrentBatchConfig$3.transition = prevTransition;
            }
          }
          return false;
        }
        function enqueuePendingPassiveProfilerEffect(fiber) {
          {
            pendingPassiveProfilerEffects.push(fiber);
            if (!rootDoesHavePassiveEffects) {
              rootDoesHavePassiveEffects = true;
              scheduleCallback$1(NormalPriority, function() {
                flushPassiveEffects();
                return null;
              });
            }
          }
        }
        function flushPassiveEffectsImpl() {
          if (rootWithPendingPassiveEffects === null) {
            return false;
          }
          var transitions = pendingPassiveTransitions;
          pendingPassiveTransitions = null;
          var root3 = rootWithPendingPassiveEffects;
          var lanes = pendingPassiveEffectsLanes;
          rootWithPendingPassiveEffects = null;
          pendingPassiveEffectsLanes = NoLanes;
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
            throw new Error("Cannot flush passive effects while already rendering.");
          }
          {
            isFlushingPassiveEffects = true;
            didScheduleUpdateDuringPassiveEffects = false;
          }
          {
            markPassiveEffectsStarted(lanes);
          }
          var prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          commitPassiveUnmountEffects(root3.current);
          commitPassiveMountEffects(root3, root3.current, lanes, transitions);
          {
            var profilerEffects = pendingPassiveProfilerEffects;
            pendingPassiveProfilerEffects = [];
            for (var i3 = 0; i3 < profilerEffects.length; i3++) {
              var _fiber = profilerEffects[i3];
              commitPassiveEffectDurations(root3, _fiber);
            }
          }
          {
            markPassiveEffectsStopped();
          }
          {
            commitDoubleInvokeEffectsInDEV(root3.current, true);
          }
          executionContext = prevExecutionContext;
          flushSyncCallbacks();
          {
            if (didScheduleUpdateDuringPassiveEffects) {
              if (root3 === rootWithPassiveNestedUpdates) {
                nestedPassiveUpdateCount++;
              } else {
                nestedPassiveUpdateCount = 0;
                rootWithPassiveNestedUpdates = root3;
              }
            } else {
              nestedPassiveUpdateCount = 0;
            }
            isFlushingPassiveEffects = false;
            didScheduleUpdateDuringPassiveEffects = false;
          }
          onPostCommitRoot(root3);
          {
            var stateNode = root3.current.stateNode;
            stateNode.effectDuration = 0;
            stateNode.passiveEffectDuration = 0;
          }
          return true;
        }
        function isAlreadyFailedLegacyErrorBoundary(instance) {
          return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
        }
        function markLegacyErrorBoundaryAsFailed(instance) {
          if (legacyErrorBoundariesThatAlreadyFailed === null) {
            legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([instance]);
          } else {
            legacyErrorBoundariesThatAlreadyFailed.add(instance);
          }
        }
        function prepareToThrowUncaughtError(error2) {
          if (!hasUncaughtError) {
            hasUncaughtError = true;
            firstUncaughtError = error2;
          }
        }
        var onUncaughtError = prepareToThrowUncaughtError;
        function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) {
          var errorInfo = createCapturedValueAtFiber(error2, sourceFiber);
          var update2 = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
          var root3 = enqueueUpdate(rootFiber, update2, SyncLane);
          var eventTime = requestEventTime();
          if (root3 !== null) {
            markRootUpdated(root3, SyncLane, eventTime);
            ensureRootIsScheduled(root3, eventTime);
          }
        }
        function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
          {
            reportUncaughtErrorInDEV(error$1);
            setIsRunningInsertionEffect(false);
          }
          if (sourceFiber.tag === HostRoot) {
            captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
            return;
          }
          var fiber = null;
          {
            fiber = nearestMountedAncestor;
          }
          while (fiber !== null) {
            if (fiber.tag === HostRoot) {
              captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
              return;
            } else if (fiber.tag === ClassComponent) {
              var ctor = fiber.type;
              var instance = fiber.stateNode;
              if (typeof ctor.getDerivedStateFromError === "function" || typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance)) {
                var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
                var update2 = createClassErrorUpdate(fiber, errorInfo, SyncLane);
                var root3 = enqueueUpdate(fiber, update2, SyncLane);
                var eventTime = requestEventTime();
                if (root3 !== null) {
                  markRootUpdated(root3, SyncLane, eventTime);
                  ensureRootIsScheduled(root3, eventTime);
                }
                return;
              }
            }
            fiber = fiber.return;
          }
          {
            error("Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Likely causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s", error$1);
          }
        }
        function pingSuspendedRoot(root3, wakeable, pingedLanes) {
          var pingCache = root3.pingCache;
          if (pingCache !== null) {
            pingCache.delete(wakeable);
          }
          var eventTime = requestEventTime();
          markRootPinged(root3, pingedLanes);
          warnIfSuspenseResolutionNotWrappedWithActDEV(root3);
          if (workInProgressRoot === root3 && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
            if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now3() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
              prepareFreshStack(root3, NoLanes);
            } else {
              workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
            }
          }
          ensureRootIsScheduled(root3, eventTime);
        }
        function retryTimedOutBoundary(boundaryFiber, retryLane) {
          if (retryLane === NoLane) {
            retryLane = requestRetryLane(boundaryFiber);
          }
          var eventTime = requestEventTime();
          var root3 = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
          if (root3 !== null) {
            markRootUpdated(root3, retryLane, eventTime);
            ensureRootIsScheduled(root3, eventTime);
          }
        }
        function retryDehydratedSuspenseBoundary(boundaryFiber) {
          var suspenseState = boundaryFiber.memoizedState;
          var retryLane = NoLane;
          if (suspenseState !== null) {
            retryLane = suspenseState.retryLane;
          }
          retryTimedOutBoundary(boundaryFiber, retryLane);
        }
        function resolveRetryWakeable(boundaryFiber, wakeable) {
          var retryLane = NoLane;
          var retryCache;
          switch (boundaryFiber.tag) {
            case SuspenseComponent:
              retryCache = boundaryFiber.stateNode;
              var suspenseState = boundaryFiber.memoizedState;
              if (suspenseState !== null) {
                retryLane = suspenseState.retryLane;
              }
              break;
            case SuspenseListComponent:
              retryCache = boundaryFiber.stateNode;
              break;
            default:
              throw new Error("Pinged unknown suspense boundary type. This is probably a bug in React.");
          }
          if (retryCache !== null) {
            retryCache.delete(wakeable);
          }
          retryTimedOutBoundary(boundaryFiber, retryLane);
        }
        function jnd(timeElapsed) {
          return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3e3 ? 3e3 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
        }
        function checkForNestedUpdates() {
          if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
            nestedUpdateCount = 0;
            rootWithNestedUpdates = null;
            throw new Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");
          }
          {
            if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
              nestedPassiveUpdateCount = 0;
              rootWithPassiveNestedUpdates = null;
              error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.");
            }
          }
        }
        function flushRenderPhaseStrictModeWarningsInDEV() {
          {
            ReactStrictModeWarnings.flushLegacyContextWarning();
            {
              ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
            }
          }
        }
        function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
          {
            setCurrentFiber(fiber);
            invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
            if (hasPassiveEffects) {
              invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
            }
            invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
            if (hasPassiveEffects) {
              invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
            }
            resetCurrentFiber();
          }
        }
        function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
          {
            var current2 = firstChild;
            var subtreeRoot = null;
            while (current2 !== null) {
              var primarySubtreeFlag = current2.subtreeFlags & fiberFlags;
              if (current2 !== subtreeRoot && current2.child !== null && primarySubtreeFlag !== NoFlags) {
                current2 = current2.child;
              } else {
                if ((current2.flags & fiberFlags) !== NoFlags) {
                  invokeEffectFn(current2);
                }
                if (current2.sibling !== null) {
                  current2 = current2.sibling;
                } else {
                  current2 = subtreeRoot = current2.return;
                }
              }
            }
          }
        }
        var didWarnStateUpdateForNotYetMountedComponent = null;
        function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
          {
            if ((executionContext & RenderContext) !== NoContext) {
              return;
            }
            if (!(fiber.mode & ConcurrentMode)) {
              return;
            }
            var tag = fiber.tag;
            if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
              return;
            }
            var componentName = getComponentNameFromFiber(fiber) || "ReactComponent";
            if (didWarnStateUpdateForNotYetMountedComponent !== null) {
              if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
                return;
              }
              didWarnStateUpdateForNotYetMountedComponent.add(componentName);
            } else {
              didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([componentName]);
            }
            var previousFiber = current;
            try {
              setCurrentFiber(fiber);
              error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.");
            } finally {
              if (previousFiber) {
                setCurrentFiber(fiber);
              } else {
                resetCurrentFiber();
              }
            }
          }
        }
        var beginWork$1;
        {
          var dummyFiber = null;
          beginWork$1 = function(current2, unitOfWork, lanes) {
            var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
            try {
              return beginWork(current2, unitOfWork, lanes);
            } catch (originalError) {
              if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") {
                throw originalError;
              }
              resetContextDependencies();
              resetHooksAfterThrow();
              unwindInterruptedWork(current2, unitOfWork);
              assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
              if (unitOfWork.mode & ProfileMode) {
                startProfilerTimer(unitOfWork);
              }
              invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes);
              if (hasCaughtError()) {
                var replayError = clearCaughtError();
                if (typeof replayError === "object" && replayError !== null && replayError._suppressLogging && typeof originalError === "object" && originalError !== null && !originalError._suppressLogging) {
                  originalError._suppressLogging = true;
                }
              }
              throw originalError;
            }
          };
        }
        var didWarnAboutUpdateInRender = false;
        var didWarnAboutUpdateInRenderForAnotherComponent;
        {
          didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
        }
        function warnAboutRenderPhaseUpdatesInDEV(fiber) {
          {
            if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
              switch (fiber.tag) {
                case FunctionComponent:
                case ForwardRef:
                case SimpleMemoComponent: {
                  var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
                  var dedupeKey = renderingComponentName;
                  if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
                    didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
                    var setStateComponentName = getComponentNameFromFiber(fiber) || "Unknown";
                    error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName);
                  }
                  break;
                }
                case ClassComponent: {
                  if (!didWarnAboutUpdateInRender) {
                    error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.");
                    didWarnAboutUpdateInRender = true;
                  }
                  break;
                }
              }
            }
          }
        }
        function restorePendingUpdaters(root3, lanes) {
          {
            if (isDevToolsPresent) {
              var memoizedUpdaters = root3.memoizedUpdaters;
              memoizedUpdaters.forEach(function(schedulingFiber) {
                addFiberToLanesMap(root3, schedulingFiber, lanes);
              });
            }
          }
        }
        var fakeActCallbackNode = {};
        function scheduleCallback$1(priorityLevel, callback) {
          {
            var actQueue = ReactCurrentActQueue$1.current;
            if (actQueue !== null) {
              actQueue.push(callback);
              return fakeActCallbackNode;
            } else {
              return scheduleCallback(priorityLevel, callback);
            }
          }
        }
        function cancelCallback$1(callbackNode) {
          if (callbackNode === fakeActCallbackNode) {
            return;
          }
          return cancelCallback(callbackNode);
        }
        function shouldForceFlushFallbacksInDEV() {
          return ReactCurrentActQueue$1.current !== null;
        }
        function warnIfUpdatesNotWrappedWithActDEV(fiber) {
          {
            if (fiber.mode & ConcurrentMode) {
              if (!isConcurrentActEnvironment()) {
                return;
              }
            } else {
              if (!isLegacyActEnvironment()) {
                return;
              }
              if (executionContext !== NoContext) {
                return;
              }
              if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
                return;
              }
            }
            if (ReactCurrentActQueue$1.current === null) {
              var previousFiber = current;
              try {
                setCurrentFiber(fiber);
                error("An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentNameFromFiber(fiber));
              } finally {
                if (previousFiber) {
                  setCurrentFiber(fiber);
                } else {
                  resetCurrentFiber();
                }
              }
            }
          }
        }
        function warnIfSuspenseResolutionNotWrappedWithActDEV(root3) {
          {
            if (root3.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
              error("A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act");
            }
          }
        }
        function setIsRunningInsertionEffect(isRunning) {
          {
            isRunningInsertionEffect = isRunning;
          }
        }
        var resolveFamily = null;
        var failedBoundaries = null;
        var setRefreshHandler = function(handler) {
          {
            resolveFamily = handler;
          }
        };
        function resolveFunctionForHotReloading(type) {
          {
            if (resolveFamily === null) {
              return type;
            }
            var family = resolveFamily(type);
            if (family === void 0) {
              return type;
            }
            return family.current;
          }
        }
        function resolveClassForHotReloading(type) {
          return resolveFunctionForHotReloading(type);
        }
        function resolveForwardRefForHotReloading(type) {
          {
            if (resolveFamily === null) {
              return type;
            }
            var family = resolveFamily(type);
            if (family === void 0) {
              if (type !== null && type !== void 0 && typeof type.render === "function") {
                var currentRender = resolveFunctionForHotReloading(type.render);
                if (type.render !== currentRender) {
                  var syntheticType = {
                    $$typeof: REACT_FORWARD_REF_TYPE,
                    render: currentRender
                  };
                  if (type.displayName !== void 0) {
                    syntheticType.displayName = type.displayName;
                  }
                  return syntheticType;
                }
              }
              return type;
            }
            return family.current;
          }
        }
        function isCompatibleFamilyForHotReloading(fiber, element) {
          {
            if (resolveFamily === null) {
              return false;
            }
            var prevType = fiber.elementType;
            var nextType = element.type;
            var needsCompareFamilies = false;
            var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof : null;
            switch (fiber.tag) {
              case ClassComponent: {
                if (typeof nextType === "function") {
                  needsCompareFamilies = true;
                }
                break;
              }
              case FunctionComponent: {
                if (typeof nextType === "function") {
                  needsCompareFamilies = true;
                } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                  needsCompareFamilies = true;
                }
                break;
              }
              case ForwardRef: {
                if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
                  needsCompareFamilies = true;
                } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                  needsCompareFamilies = true;
                }
                break;
              }
              case MemoComponent:
              case SimpleMemoComponent: {
                if ($$typeofNextType === REACT_MEMO_TYPE) {
                  needsCompareFamilies = true;
                } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                  needsCompareFamilies = true;
                }
                break;
              }
              default:
                return false;
            }
            if (needsCompareFamilies) {
              var prevFamily = resolveFamily(prevType);
              if (prevFamily !== void 0 && prevFamily === resolveFamily(nextType)) {
                return true;
              }
            }
            return false;
          }
        }
        function markFailedErrorBoundaryForHotReloading(fiber) {
          {
            if (resolveFamily === null) {
              return;
            }
            if (typeof WeakSet !== "function") {
              return;
            }
            if (failedBoundaries === null) {
              failedBoundaries = /* @__PURE__ */ new WeakSet();
            }
            failedBoundaries.add(fiber);
          }
        }
        var scheduleRefresh = function(root3, update2) {
          {
            if (resolveFamily === null) {
              return;
            }
            var staleFamilies = update2.staleFamilies, updatedFamilies = update2.updatedFamilies;
            flushPassiveEffects();
            flushSync12(function() {
              scheduleFibersWithFamiliesRecursively(root3.current, updatedFamilies, staleFamilies);
            });
          }
        };
        var scheduleRoot = function(root3, element) {
          {
            if (root3.context !== emptyContextObject) {
              return;
            }
            flushPassiveEffects();
            flushSync12(function() {
              updateContainer(element, root3, null, null);
            });
          }
        };
        function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
          {
            var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type;
            var candidateType = null;
            switch (tag) {
              case FunctionComponent:
              case SimpleMemoComponent:
              case ClassComponent:
                candidateType = type;
                break;
              case ForwardRef:
                candidateType = type.render;
                break;
            }
            if (resolveFamily === null) {
              throw new Error("Expected resolveFamily to be set during hot reload.");
            }
            var needsRender = false;
            var needsRemount = false;
            if (candidateType !== null) {
              var family = resolveFamily(candidateType);
              if (family !== void 0) {
                if (staleFamilies.has(family)) {
                  needsRemount = true;
                } else if (updatedFamilies.has(family)) {
                  if (tag === ClassComponent) {
                    needsRemount = true;
                  } else {
                    needsRender = true;
                  }
                }
              }
            }
            if (failedBoundaries !== null) {
              if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
                needsRemount = true;
              }
            }
            if (needsRemount) {
              fiber._debugNeedsRemount = true;
            }
            if (needsRemount || needsRender) {
              var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);
              if (_root !== null) {
                scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
              }
            }
            if (child !== null && !needsRemount) {
              scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
            }
            if (sibling !== null) {
              scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
            }
          }
        }
        var findHostInstancesForRefresh = function(root3, families) {
          {
            var hostInstances = /* @__PURE__ */ new Set();
            var types = new Set(families.map(function(family) {
              return family.current;
            }));
            findHostInstancesForMatchingFibersRecursively(root3.current, types, hostInstances);
            return hostInstances;
          }
        };
        function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
          {
            var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type;
            var candidateType = null;
            switch (tag) {
              case FunctionComponent:
              case SimpleMemoComponent:
              case ClassComponent:
                candidateType = type;
                break;
              case ForwardRef:
                candidateType = type.render;
                break;
            }
            var didMatch = false;
            if (candidateType !== null) {
              if (types.has(candidateType)) {
                didMatch = true;
              }
            }
            if (didMatch) {
              findHostInstancesForFiberShallowly(fiber, hostInstances);
            } else {
              if (child !== null) {
                findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
              }
            }
            if (sibling !== null) {
              findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
            }
          }
        }
        function findHostInstancesForFiberShallowly(fiber, hostInstances) {
          {
            var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
            if (foundHostInstances) {
              return;
            }
            var node = fiber;
            while (true) {
              switch (node.tag) {
                case HostComponent:
                  hostInstances.add(node.stateNode);
                  return;
                case HostPortal:
                  hostInstances.add(node.stateNode.containerInfo);
                  return;
                case HostRoot:
                  hostInstances.add(node.stateNode.containerInfo);
                  return;
              }
              if (node.return === null) {
                throw new Error("Expected to reach root first.");
              }
              node = node.return;
            }
          }
        }
        function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
          {
            var node = fiber;
            var foundHostInstances = false;
            while (true) {
              if (node.tag === HostComponent) {
                foundHostInstances = true;
                hostInstances.add(node.stateNode);
              } else if (node.child !== null) {
                node.child.return = node;
                node = node.child;
                continue;
              }
              if (node === fiber) {
                return foundHostInstances;
              }
              while (node.sibling === null) {
                if (node.return === null || node.return === fiber) {
                  return foundHostInstances;
                }
                node = node.return;
              }
              node.sibling.return = node.return;
              node = node.sibling;
            }
          }
          return false;
        }
        var hasBadMapPolyfill;
        {
          hasBadMapPolyfill = false;
          try {
            var nonExtensibleObject = Object.preventExtensions({});
            /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
            /* @__PURE__ */ new Set([nonExtensibleObject]);
          } catch (e3) {
            hasBadMapPolyfill = true;
          }
        }
        function FiberNode(tag, pendingProps, key, mode) {
          this.tag = tag;
          this.key = key;
          this.elementType = null;
          this.type = null;
          this.stateNode = null;
          this.return = null;
          this.child = null;
          this.sibling = null;
          this.index = 0;
          this.ref = null;
          this.pendingProps = pendingProps;
          this.memoizedProps = null;
          this.updateQueue = null;
          this.memoizedState = null;
          this.dependencies = null;
          this.mode = mode;
          this.flags = NoFlags;
          this.subtreeFlags = NoFlags;
          this.deletions = null;
          this.lanes = NoLanes;
          this.childLanes = NoLanes;
          this.alternate = null;
          {
            this.actualDuration = Number.NaN;
            this.actualStartTime = Number.NaN;
            this.selfBaseDuration = Number.NaN;
            this.treeBaseDuration = Number.NaN;
            this.actualDuration = 0;
            this.actualStartTime = -1;
            this.selfBaseDuration = 0;
            this.treeBaseDuration = 0;
          }
          {
            this._debugSource = null;
            this._debugOwner = null;
            this._debugNeedsRemount = false;
            this._debugHookTypes = null;
            if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") {
              Object.preventExtensions(this);
            }
          }
        }
        var createFiber = function(tag, pendingProps, key, mode) {
          return new FiberNode(tag, pendingProps, key, mode);
        };
        function shouldConstruct$1(Component2) {
          var prototype = Component2.prototype;
          return !!(prototype && prototype.isReactComponent);
        }
        function isSimpleFunctionComponent(type) {
          return typeof type === "function" && !shouldConstruct$1(type) && type.defaultProps === void 0;
        }
        function resolveLazyComponentTag(Component2) {
          if (typeof Component2 === "function") {
            return shouldConstruct$1(Component2) ? ClassComponent : FunctionComponent;
          } else if (Component2 !== void 0 && Component2 !== null) {
            var $$typeof = Component2.$$typeof;
            if ($$typeof === REACT_FORWARD_REF_TYPE) {
              return ForwardRef;
            }
            if ($$typeof === REACT_MEMO_TYPE) {
              return MemoComponent;
            }
          }
          return IndeterminateComponent;
        }
        function createWorkInProgress(current2, pendingProps) {
          var workInProgress2 = current2.alternate;
          if (workInProgress2 === null) {
            workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode);
            workInProgress2.elementType = current2.elementType;
            workInProgress2.type = current2.type;
            workInProgress2.stateNode = current2.stateNode;
            {
              workInProgress2._debugSource = current2._debugSource;
              workInProgress2._debugOwner = current2._debugOwner;
              workInProgress2._debugHookTypes = current2._debugHookTypes;
            }
            workInProgress2.alternate = current2;
            current2.alternate = workInProgress2;
          } else {
            workInProgress2.pendingProps = pendingProps;
            workInProgress2.type = current2.type;
            workInProgress2.flags = NoFlags;
            workInProgress2.subtreeFlags = NoFlags;
            workInProgress2.deletions = null;
            {
              workInProgress2.actualDuration = 0;
              workInProgress2.actualStartTime = -1;
            }
          }
          workInProgress2.flags = current2.flags & StaticMask;
          workInProgress2.childLanes = current2.childLanes;
          workInProgress2.lanes = current2.lanes;
          workInProgress2.child = current2.child;
          workInProgress2.memoizedProps = current2.memoizedProps;
          workInProgress2.memoizedState = current2.memoizedState;
          workInProgress2.updateQueue = current2.updateQueue;
          var currentDependencies = current2.dependencies;
          workInProgress2.dependencies = currentDependencies === null ? null : {
            lanes: currentDependencies.lanes,
            firstContext: currentDependencies.firstContext
          };
          workInProgress2.sibling = current2.sibling;
          workInProgress2.index = current2.index;
          workInProgress2.ref = current2.ref;
          {
            workInProgress2.selfBaseDuration = current2.selfBaseDuration;
            workInProgress2.treeBaseDuration = current2.treeBaseDuration;
          }
          {
            workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
            switch (workInProgress2.tag) {
              case IndeterminateComponent:
              case FunctionComponent:
              case SimpleMemoComponent:
                workInProgress2.type = resolveFunctionForHotReloading(current2.type);
                break;
              case ClassComponent:
                workInProgress2.type = resolveClassForHotReloading(current2.type);
                break;
              case ForwardRef:
                workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
                break;
            }
          }
          return workInProgress2;
        }
        function resetWorkInProgress(workInProgress2, renderLanes2) {
          workInProgress2.flags &= StaticMask | Placement;
          var current2 = workInProgress2.alternate;
          if (current2 === null) {
            workInProgress2.childLanes = NoLanes;
            workInProgress2.lanes = renderLanes2;
            workInProgress2.child = null;
            workInProgress2.subtreeFlags = NoFlags;
            workInProgress2.memoizedProps = null;
            workInProgress2.memoizedState = null;
            workInProgress2.updateQueue = null;
            workInProgress2.dependencies = null;
            workInProgress2.stateNode = null;
            {
              workInProgress2.selfBaseDuration = 0;
              workInProgress2.treeBaseDuration = 0;
            }
          } else {
            workInProgress2.childLanes = current2.childLanes;
            workInProgress2.lanes = current2.lanes;
            workInProgress2.child = current2.child;
            workInProgress2.subtreeFlags = NoFlags;
            workInProgress2.deletions = null;
            workInProgress2.memoizedProps = current2.memoizedProps;
            workInProgress2.memoizedState = current2.memoizedState;
            workInProgress2.updateQueue = current2.updateQueue;
            workInProgress2.type = current2.type;
            var currentDependencies = current2.dependencies;
            workInProgress2.dependencies = currentDependencies === null ? null : {
              lanes: currentDependencies.lanes,
              firstContext: currentDependencies.firstContext
            };
            {
              workInProgress2.selfBaseDuration = current2.selfBaseDuration;
              workInProgress2.treeBaseDuration = current2.treeBaseDuration;
            }
          }
          return workInProgress2;
        }
        function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
          var mode;
          if (tag === ConcurrentRoot) {
            mode = ConcurrentMode;
            if (isStrictMode === true) {
              mode |= StrictLegacyMode;
              {
                mode |= StrictEffectsMode;
              }
            }
          } else {
            mode = NoMode;
          }
          if (isDevToolsPresent) {
            mode |= ProfileMode;
          }
          return createFiber(HostRoot, null, null, mode);
        }
        function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
          var fiberTag = IndeterminateComponent;
          var resolvedType = type;
          if (typeof type === "function") {
            if (shouldConstruct$1(type)) {
              fiberTag = ClassComponent;
              {
                resolvedType = resolveClassForHotReloading(resolvedType);
              }
            } else {
              {
                resolvedType = resolveFunctionForHotReloading(resolvedType);
              }
            }
          } else if (typeof type === "string") {
            fiberTag = HostComponent;
          } else {
            getTag:
              switch (type) {
                case REACT_FRAGMENT_TYPE:
                  return createFiberFromFragment(pendingProps.children, mode, lanes, key);
                case REACT_STRICT_MODE_TYPE:
                  fiberTag = Mode;
                  mode |= StrictLegacyMode;
                  if ((mode & ConcurrentMode) !== NoMode) {
                    mode |= StrictEffectsMode;
                  }
                  break;
                case REACT_PROFILER_TYPE:
                  return createFiberFromProfiler(pendingProps, mode, lanes, key);
                case REACT_SUSPENSE_TYPE:
                  return createFiberFromSuspense(pendingProps, mode, lanes, key);
                case REACT_SUSPENSE_LIST_TYPE:
                  return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
                case REACT_OFFSCREEN_TYPE:
                  return createFiberFromOffscreen(pendingProps, mode, lanes, key);
                case REACT_LEGACY_HIDDEN_TYPE:
                case REACT_SCOPE_TYPE:
                case REACT_CACHE_TYPE:
                case REACT_TRACING_MARKER_TYPE:
                case REACT_DEBUG_TRACING_MODE_TYPE:
                default: {
                  if (typeof type === "object" && type !== null) {
                    switch (type.$$typeof) {
                      case REACT_PROVIDER_TYPE:
                        fiberTag = ContextProvider;
                        break getTag;
                      case REACT_CONTEXT_TYPE:
                        fiberTag = ContextConsumer;
                        break getTag;
                      case REACT_FORWARD_REF_TYPE:
                        fiberTag = ForwardRef;
                        {
                          resolvedType = resolveForwardRefForHotReloading(resolvedType);
                        }
                        break getTag;
                      case REACT_MEMO_TYPE:
                        fiberTag = MemoComponent;
                        break getTag;
                      case REACT_LAZY_TYPE:
                        fiberTag = LazyComponent;
                        resolvedType = null;
                        break getTag;
                    }
                  }
                  var info = "";
                  {
                    if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
                      info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
                    }
                    var ownerName = owner ? getComponentNameFromFiber(owner) : null;
                    if (ownerName) {
                      info += "\n\nCheck the render method of `" + ownerName + "`.";
                    }
                  }
                  throw new Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) " + ("but got: " + (type == null ? type : typeof type) + "." + info));
                }
              }
          }
          var fiber = createFiber(fiberTag, pendingProps, key, mode);
          fiber.elementType = type;
          fiber.type = resolvedType;
          fiber.lanes = lanes;
          {
            fiber._debugOwner = owner;
          }
          return fiber;
        }
        function createFiberFromElement(element, mode, lanes) {
          var owner = null;
          {
            owner = element._owner;
          }
          var type = element.type;
          var key = element.key;
          var pendingProps = element.props;
          var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
          {
            fiber._debugSource = element._source;
            fiber._debugOwner = element._owner;
          }
          return fiber;
        }
        function createFiberFromFragment(elements, mode, lanes, key) {
          var fiber = createFiber(Fragment21, elements, key, mode);
          fiber.lanes = lanes;
          return fiber;
        }
        function createFiberFromProfiler(pendingProps, mode, lanes, key) {
          {
            if (typeof pendingProps.id !== "string") {
              error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
            }
          }
          var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
          fiber.elementType = REACT_PROFILER_TYPE;
          fiber.lanes = lanes;
          {
            fiber.stateNode = {
              effectDuration: 0,
              passiveEffectDuration: 0
            };
          }
          return fiber;
        }
        function createFiberFromSuspense(pendingProps, mode, lanes, key) {
          var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
          fiber.elementType = REACT_SUSPENSE_TYPE;
          fiber.lanes = lanes;
          return fiber;
        }
        function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
          var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
          fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
          fiber.lanes = lanes;
          return fiber;
        }
        function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
          var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
          fiber.elementType = REACT_OFFSCREEN_TYPE;
          fiber.lanes = lanes;
          var primaryChildInstance = {
            isHidden: false
          };
          fiber.stateNode = primaryChildInstance;
          return fiber;
        }
        function createFiberFromText(content, mode, lanes) {
          var fiber = createFiber(HostText, content, null, mode);
          fiber.lanes = lanes;
          return fiber;
        }
        function createFiberFromHostInstanceForDeletion() {
          var fiber = createFiber(HostComponent, null, null, NoMode);
          fiber.elementType = "DELETED";
          return fiber;
        }
        function createFiberFromDehydratedFragment(dehydratedNode) {
          var fiber = createFiber(DehydratedFragment, null, null, NoMode);
          fiber.stateNode = dehydratedNode;
          return fiber;
        }
        function createFiberFromPortal(portal, mode, lanes) {
          var pendingProps = portal.children !== null ? portal.children : [];
          var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
          fiber.lanes = lanes;
          fiber.stateNode = {
            containerInfo: portal.containerInfo,
            pendingChildren: null,
            // Used by persistent updates
            implementation: portal.implementation
          };
          return fiber;
        }
        function assignFiberPropertiesInDEV(target, source) {
          if (target === null) {
            target = createFiber(IndeterminateComponent, null, null, NoMode);
          }
          target.tag = source.tag;
          target.key = source.key;
          target.elementType = source.elementType;
          target.type = source.type;
          target.stateNode = source.stateNode;
          target.return = source.return;
          target.child = source.child;
          target.sibling = source.sibling;
          target.index = source.index;
          target.ref = source.ref;
          target.pendingProps = source.pendingProps;
          target.memoizedProps = source.memoizedProps;
          target.updateQueue = source.updateQueue;
          target.memoizedState = source.memoizedState;
          target.dependencies = source.dependencies;
          target.mode = source.mode;
          target.flags = source.flags;
          target.subtreeFlags = source.subtreeFlags;
          target.deletions = source.deletions;
          target.lanes = source.lanes;
          target.childLanes = source.childLanes;
          target.alternate = source.alternate;
          {
            target.actualDuration = source.actualDuration;
            target.actualStartTime = source.actualStartTime;
            target.selfBaseDuration = source.selfBaseDuration;
            target.treeBaseDuration = source.treeBaseDuration;
          }
          target._debugSource = source._debugSource;
          target._debugOwner = source._debugOwner;
          target._debugNeedsRemount = source._debugNeedsRemount;
          target._debugHookTypes = source._debugHookTypes;
          return target;
        }
        function FiberRootNode(containerInfo, tag, hydrate2, identifierPrefix, onRecoverableError) {
          this.tag = tag;
          this.containerInfo = containerInfo;
          this.pendingChildren = null;
          this.current = null;
          this.pingCache = null;
          this.finishedWork = null;
          this.timeoutHandle = noTimeout;
          this.context = null;
          this.pendingContext = null;
          this.callbackNode = null;
          this.callbackPriority = NoLane;
          this.eventTimes = createLaneMap(NoLanes);
          this.expirationTimes = createLaneMap(NoTimestamp);
          this.pendingLanes = NoLanes;
          this.suspendedLanes = NoLanes;
          this.pingedLanes = NoLanes;
          this.expiredLanes = NoLanes;
          this.mutableReadLanes = NoLanes;
          this.finishedLanes = NoLanes;
          this.entangledLanes = NoLanes;
          this.entanglements = createLaneMap(NoLanes);
          this.identifierPrefix = identifierPrefix;
          this.onRecoverableError = onRecoverableError;
          {
            this.mutableSourceEagerHydrationData = null;
          }
          {
            this.effectDuration = 0;
            this.passiveEffectDuration = 0;
          }
          {
            this.memoizedUpdaters = /* @__PURE__ */ new Set();
            var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];
            for (var _i = 0; _i < TotalLanes; _i++) {
              pendingUpdatersLaneMap.push(/* @__PURE__ */ new Set());
            }
          }
          {
            switch (tag) {
              case ConcurrentRoot:
                this._debugRootType = hydrate2 ? "hydrateRoot()" : "createRoot()";
                break;
              case LegacyRoot:
                this._debugRootType = hydrate2 ? "hydrate()" : "render()";
                break;
            }
          }
        }
        function createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
          var root3 = new FiberRootNode(containerInfo, tag, hydrate2, identifierPrefix, onRecoverableError);
          var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
          root3.current = uninitializedFiber;
          uninitializedFiber.stateNode = root3;
          {
            var _initialState = {
              element: initialChildren,
              isDehydrated: hydrate2,
              cache: null,
              // not enabled yet
              transitions: null,
              pendingSuspenseBoundaries: null
            };
            uninitializedFiber.memoizedState = _initialState;
          }
          initializeUpdateQueue(uninitializedFiber);
          return root3;
        }
        var ReactVersion = "18.2.0";
        function createPortal2(children, containerInfo, implementation) {
          var key = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null;
          {
            checkKeyStringCoercion(key);
          }
          return {
            // This tag allow us to uniquely identify this as a React Portal
            $$typeof: REACT_PORTAL_TYPE,
            key: key == null ? null : "" + key,
            children,
            containerInfo,
            implementation
          };
        }
        var didWarnAboutNestedUpdates;
        var didWarnAboutFindNodeInStrictMode;
        {
          didWarnAboutNestedUpdates = false;
          didWarnAboutFindNodeInStrictMode = {};
        }
        function getContextForSubtree(parentComponent) {
          if (!parentComponent) {
            return emptyContextObject;
          }
          var fiber = get4(parentComponent);
          var parentContext = findCurrentUnmaskedContext(fiber);
          if (fiber.tag === ClassComponent) {
            var Component2 = fiber.type;
            if (isContextProvider(Component2)) {
              return processChildContext(fiber, Component2, parentContext);
            }
          }
          return parentContext;
        }
        function findHostInstanceWithWarning(component, methodName) {
          {
            var fiber = get4(component);
            if (fiber === void 0) {
              if (typeof component.render === "function") {
                throw new Error("Unable to find node on an unmounted component.");
              } else {
                var keys = Object.keys(component).join(",");
                throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
              }
            }
            var hostFiber = findCurrentHostFiber(fiber);
            if (hostFiber === null) {
              return null;
            }
            if (hostFiber.mode & StrictLegacyMode) {
              var componentName = getComponentNameFromFiber(fiber) || "Component";
              if (!didWarnAboutFindNodeInStrictMode[componentName]) {
                didWarnAboutFindNodeInStrictMode[componentName] = true;
                var previousFiber = current;
                try {
                  setCurrentFiber(hostFiber);
                  if (fiber.mode & StrictLegacyMode) {
                    error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
                  } else {
                    error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
                  }
                } finally {
                  if (previousFiber) {
                    setCurrentFiber(previousFiber);
                  } else {
                    resetCurrentFiber();
                  }
                }
              }
            }
            return hostFiber.stateNode;
          }
        }
        function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
          var hydrate2 = false;
          var initialChildren = null;
          return createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
        }
        function createHydrationContainer(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
          var hydrate2 = true;
          var root3 = createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
          root3.context = getContextForSubtree(null);
          var current2 = root3.current;
          var eventTime = requestEventTime();
          var lane = requestUpdateLane(current2);
          var update2 = createUpdate(eventTime, lane);
          update2.callback = callback !== void 0 && callback !== null ? callback : null;
          enqueueUpdate(current2, update2, lane);
          scheduleInitialHydrationOnRoot(root3, lane, eventTime);
          return root3;
        }
        function updateContainer(element, container, parentComponent, callback) {
          {
            onScheduleRoot(container, element);
          }
          var current$1 = container.current;
          var eventTime = requestEventTime();
          var lane = requestUpdateLane(current$1);
          {
            markRenderScheduled(lane);
          }
          var context = getContextForSubtree(parentComponent);
          if (container.context === null) {
            container.context = context;
          } else {
            container.pendingContext = context;
          }
          {
            if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
              didWarnAboutNestedUpdates = true;
              error("Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.", getComponentNameFromFiber(current) || "Unknown");
            }
          }
          var update2 = createUpdate(eventTime, lane);
          update2.payload = {
            element
          };
          callback = callback === void 0 ? null : callback;
          if (callback !== null) {
            {
              if (typeof callback !== "function") {
                error("render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callback);
              }
            }
            update2.callback = callback;
          }
          var root3 = enqueueUpdate(current$1, update2, lane);
          if (root3 !== null) {
            scheduleUpdateOnFiber(root3, current$1, lane, eventTime);
            entangleTransitions(root3, current$1, lane);
          }
          return lane;
        }
        function getPublicRootInstance(container) {
          var containerFiber = container.current;
          if (!containerFiber.child) {
            return null;
          }
          switch (containerFiber.child.tag) {
            case HostComponent:
              return getPublicInstance(containerFiber.child.stateNode);
            default:
              return containerFiber.child.stateNode;
          }
        }
        function attemptSynchronousHydration$1(fiber) {
          switch (fiber.tag) {
            case HostRoot: {
              var root3 = fiber.stateNode;
              if (isRootDehydrated(root3)) {
                var lanes = getHighestPriorityPendingLanes(root3);
                flushRoot(root3, lanes);
              }
              break;
            }
            case SuspenseComponent: {
              flushSync12(function() {
                var root4 = enqueueConcurrentRenderForLane(fiber, SyncLane);
                if (root4 !== null) {
                  var eventTime = requestEventTime();
                  scheduleUpdateOnFiber(root4, fiber, SyncLane, eventTime);
                }
              });
              var retryLane = SyncLane;
              markRetryLaneIfNotHydrated(fiber, retryLane);
              break;
            }
          }
        }
        function markRetryLaneImpl(fiber, retryLane) {
          var suspenseState = fiber.memoizedState;
          if (suspenseState !== null && suspenseState.dehydrated !== null) {
            suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
          }
        }
        function markRetryLaneIfNotHydrated(fiber, retryLane) {
          markRetryLaneImpl(fiber, retryLane);
          var alternate = fiber.alternate;
          if (alternate) {
            markRetryLaneImpl(alternate, retryLane);
          }
        }
        function attemptContinuousHydration$1(fiber) {
          if (fiber.tag !== SuspenseComponent) {
            return;
          }
          var lane = SelectiveHydrationLane;
          var root3 = enqueueConcurrentRenderForLane(fiber, lane);
          if (root3 !== null) {
            var eventTime = requestEventTime();
            scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
          }
          markRetryLaneIfNotHydrated(fiber, lane);
        }
        function attemptHydrationAtCurrentPriority$1(fiber) {
          if (fiber.tag !== SuspenseComponent) {
            return;
          }
          var lane = requestUpdateLane(fiber);
          var root3 = enqueueConcurrentRenderForLane(fiber, lane);
          if (root3 !== null) {
            var eventTime = requestEventTime();
            scheduleUpdateOnFiber(root3, fiber, lane, eventTime);
          }
          markRetryLaneIfNotHydrated(fiber, lane);
        }
        function findHostInstanceWithNoPortals(fiber) {
          var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
          if (hostFiber === null) {
            return null;
          }
          return hostFiber.stateNode;
        }
        var shouldErrorImpl = function(fiber) {
          return null;
        };
        function shouldError(fiber) {
          return shouldErrorImpl(fiber);
        }
        var shouldSuspendImpl = function(fiber) {
          return false;
        };
        function shouldSuspend(fiber) {
          return shouldSuspendImpl(fiber);
        }
        var overrideHookState = null;
        var overrideHookStateDeletePath = null;
        var overrideHookStateRenamePath = null;
        var overrideProps = null;
        var overridePropsDeletePath = null;
        var overridePropsRenamePath = null;
        var scheduleUpdate = null;
        var setErrorHandler = null;
        var setSuspenseHandler = null;
        {
          var copyWithDeleteImpl = function(obj, path, index3) {
            var key = path[index3];
            var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
            if (index3 + 1 === path.length) {
              if (isArray2(updated)) {
                updated.splice(key, 1);
              } else {
                delete updated[key];
              }
              return updated;
            }
            updated[key] = copyWithDeleteImpl(obj[key], path, index3 + 1);
            return updated;
          };
          var copyWithDelete = function(obj, path) {
            return copyWithDeleteImpl(obj, path, 0);
          };
          var copyWithRenameImpl = function(obj, oldPath, newPath, index3) {
            var oldKey = oldPath[index3];
            var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
            if (index3 + 1 === oldPath.length) {
              var newKey = newPath[index3];
              updated[newKey] = updated[oldKey];
              if (isArray2(updated)) {
                updated.splice(oldKey, 1);
              } else {
                delete updated[oldKey];
              }
            } else {
              updated[oldKey] = copyWithRenameImpl(
                // $FlowFixMe number or string is fine here
                obj[oldKey],
                oldPath,
                newPath,
                index3 + 1
              );
            }
            return updated;
          };
          var copyWithRename = function(obj, oldPath, newPath) {
            if (oldPath.length !== newPath.length) {
              warn2("copyWithRename() expects paths of the same length");
              return;
            } else {
              for (var i3 = 0; i3 < newPath.length - 1; i3++) {
                if (oldPath[i3] !== newPath[i3]) {
                  warn2("copyWithRename() expects paths to be the same except for the deepest key");
                  return;
                }
              }
            }
            return copyWithRenameImpl(obj, oldPath, newPath, 0);
          };
          var copyWithSetImpl = function(obj, path, index3, value) {
            if (index3 >= path.length) {
              return value;
            }
            var key = path[index3];
            var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
            updated[key] = copyWithSetImpl(obj[key], path, index3 + 1, value);
            return updated;
          };
          var copyWithSet = function(obj, path, value) {
            return copyWithSetImpl(obj, path, 0, value);
          };
          var findHook = function(fiber, id) {
            var currentHook2 = fiber.memoizedState;
            while (currentHook2 !== null && id > 0) {
              currentHook2 = currentHook2.next;
              id--;
            }
            return currentHook2;
          };
          overrideHookState = function(fiber, id, path, value) {
            var hook = findHook(fiber, id);
            if (hook !== null) {
              var newState = copyWithSet(hook.memoizedState, path, value);
              hook.memoizedState = newState;
              hook.baseState = newState;
              fiber.memoizedProps = assign({}, fiber.memoizedProps);
              var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
              if (root3 !== null) {
                scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
              }
            }
          };
          overrideHookStateDeletePath = function(fiber, id, path) {
            var hook = findHook(fiber, id);
            if (hook !== null) {
              var newState = copyWithDelete(hook.memoizedState, path);
              hook.memoizedState = newState;
              hook.baseState = newState;
              fiber.memoizedProps = assign({}, fiber.memoizedProps);
              var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
              if (root3 !== null) {
                scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
              }
            }
          };
          overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
            var hook = findHook(fiber, id);
            if (hook !== null) {
              var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
              hook.memoizedState = newState;
              hook.baseState = newState;
              fiber.memoizedProps = assign({}, fiber.memoizedProps);
              var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
              if (root3 !== null) {
                scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
              }
            }
          };
          overrideProps = function(fiber, path, value) {
            fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
            if (fiber.alternate) {
              fiber.alternate.pendingProps = fiber.pendingProps;
            }
            var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
            }
          };
          overridePropsDeletePath = function(fiber, path) {
            fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
            if (fiber.alternate) {
              fiber.alternate.pendingProps = fiber.pendingProps;
            }
            var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
            }
          };
          overridePropsRenamePath = function(fiber, oldPath, newPath) {
            fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
            if (fiber.alternate) {
              fiber.alternate.pendingProps = fiber.pendingProps;
            }
            var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
            }
          };
          scheduleUpdate = function(fiber) {
            var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root3 !== null) {
              scheduleUpdateOnFiber(root3, fiber, SyncLane, NoTimestamp);
            }
          };
          setErrorHandler = function(newShouldErrorImpl) {
            shouldErrorImpl = newShouldErrorImpl;
          };
          setSuspenseHandler = function(newShouldSuspendImpl) {
            shouldSuspendImpl = newShouldSuspendImpl;
          };
        }
        function findHostInstanceByFiber(fiber) {
          var hostFiber = findCurrentHostFiber(fiber);
          if (hostFiber === null) {
            return null;
          }
          return hostFiber.stateNode;
        }
        function emptyFindFiberByHostInstance(instance) {
          return null;
        }
        function getCurrentFiberForDevTools() {
          return current;
        }
        function injectIntoDevTools(devToolsConfig) {
          var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
          var ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher;
          return injectInternals({
            bundleType: devToolsConfig.bundleType,
            version: devToolsConfig.version,
            rendererPackageName: devToolsConfig.rendererPackageName,
            rendererConfig: devToolsConfig.rendererConfig,
            overrideHookState,
            overrideHookStateDeletePath,
            overrideHookStateRenamePath,
            overrideProps,
            overridePropsDeletePath,
            overridePropsRenamePath,
            setErrorHandler,
            setSuspenseHandler,
            scheduleUpdate,
            currentDispatcherRef: ReactCurrentDispatcher2,
            findHostInstanceByFiber,
            findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
            // React Refresh
            findHostInstancesForRefresh,
            scheduleRefresh,
            scheduleRoot,
            setRefreshHandler,
            // Enables DevTools to append owner stacks to error messages in DEV mode.
            getCurrentFiber: getCurrentFiberForDevTools,
            // Enables DevTools to detect reconciler version rather than renderer version
            // which may not match for third party renderers.
            reconcilerVersion: ReactVersion
          });
        }
        var defaultOnRecoverableError = typeof reportError === "function" ? (
          // In modern browsers, reportError will dispatch an error event,
          // emulating an uncaught JavaScript error.
          reportError
        ) : function(error2) {
          console["error"](error2);
        };
        function ReactDOMRoot(internalRoot) {
          this._internalRoot = internalRoot;
        }
        ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) {
          var root3 = this._internalRoot;
          if (root3 === null) {
            throw new Error("Cannot update an unmounted root.");
          }
          {
            if (typeof arguments[1] === "function") {
              error("render(...): does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
            } else if (isValidContainer(arguments[1])) {
              error("You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root.");
            } else if (typeof arguments[1] !== "undefined") {
              error("You passed a second argument to root.render(...) but it only accepts one argument.");
            }
            var container = root3.containerInfo;
            if (container.nodeType !== COMMENT_NODE) {
              var hostInstance = findHostInstanceWithNoPortals(root3.current);
              if (hostInstance) {
                if (hostInstance.parentNode !== container) {
                  error("render(...): It looks like the React-rendered content of the root container was removed without using React. This is not supported and will cause errors. Instead, call root.unmount() to empty a root's container.");
                }
              }
            }
          }
          updateContainer(children, root3, null, null);
        };
        ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
          {
            if (typeof arguments[0] === "function") {
              error("unmount(...): does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
            }
          }
          var root3 = this._internalRoot;
          if (root3 !== null) {
            this._internalRoot = null;
            var container = root3.containerInfo;
            {
              if (isAlreadyRendering()) {
                error("Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.");
              }
            }
            flushSync12(function() {
              updateContainer(null, root3, null, null);
            });
            unmarkContainerAsRoot(container);
          }
        };
        function createRoot7(container, options2) {
          if (!isValidContainer(container)) {
            throw new Error("createRoot(...): Target container is not a DOM element.");
          }
          warnIfReactDOMContainerInDEV(container);
          var isStrictMode = false;
          var concurrentUpdatesByDefaultOverride = false;
          var identifierPrefix = "";
          var onRecoverableError = defaultOnRecoverableError;
          var transitionCallbacks = null;
          if (options2 !== null && options2 !== void 0) {
            {
              if (options2.hydrate) {
                warn2("hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.");
              } else {
                if (typeof options2 === "object" && options2 !== null && options2.$$typeof === REACT_ELEMENT_TYPE) {
                  error("You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n  let root = createRoot(domContainer);\n  root.render(<App />);");
                }
              }
            }
            if (options2.unstable_strictMode === true) {
              isStrictMode = true;
            }
            if (options2.identifierPrefix !== void 0) {
              identifierPrefix = options2.identifierPrefix;
            }
            if (options2.onRecoverableError !== void 0) {
              onRecoverableError = options2.onRecoverableError;
            }
            if (options2.transitionCallbacks !== void 0) {
              transitionCallbacks = options2.transitionCallbacks;
            }
          }
          var root3 = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
          markContainerAsRoot(root3.current, container);
          var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
          listenToAllSupportedEvents(rootContainerElement);
          return new ReactDOMRoot(root3);
        }
        function ReactDOMHydrationRoot(internalRoot) {
          this._internalRoot = internalRoot;
        }
        function scheduleHydration(target) {
          if (target) {
            queueExplicitHydrationTarget(target);
          }
        }
        ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
        function hydrateRoot(container, initialChildren, options2) {
          if (!isValidContainer(container)) {
            throw new Error("hydrateRoot(...): Target container is not a DOM element.");
          }
          warnIfReactDOMContainerInDEV(container);
          {
            if (initialChildren === void 0) {
              error("Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)");
            }
          }
          var hydrationCallbacks = options2 != null ? options2 : null;
          var mutableSources = options2 != null && options2.hydratedSources || null;
          var isStrictMode = false;
          var concurrentUpdatesByDefaultOverride = false;
          var identifierPrefix = "";
          var onRecoverableError = defaultOnRecoverableError;
          if (options2 !== null && options2 !== void 0) {
            if (options2.unstable_strictMode === true) {
              isStrictMode = true;
            }
            if (options2.identifierPrefix !== void 0) {
              identifierPrefix = options2.identifierPrefix;
            }
            if (options2.onRecoverableError !== void 0) {
              onRecoverableError = options2.onRecoverableError;
            }
          }
          var root3 = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
          markContainerAsRoot(root3.current, container);
          listenToAllSupportedEvents(container);
          if (mutableSources) {
            for (var i3 = 0; i3 < mutableSources.length; i3++) {
              var mutableSource = mutableSources[i3];
              registerMutableSourceForHydration(root3, mutableSource);
            }
          }
          return new ReactDOMHydrationRoot(root3);
        }
        function isValidContainer(node) {
          return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers));
        }
        function isValidContainerLegacy(node) {
          return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === " react-mount-point-unstable "));
        }
        function warnIfReactDOMContainerInDEV(container) {
          {
            if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") {
              error("createRoot(): Creating roots directly with document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try using a container element created for your app.");
            }
            if (isContainerMarkedAsRoot(container)) {
              if (container._reactRootContainer) {
                error("You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported.");
              } else {
                error("You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.");
              }
            }
          }
        }
        var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
        var topLevelUpdateWarnings;
        {
          topLevelUpdateWarnings = function(container) {
            if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
              var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);
              if (hostInstance) {
                if (hostInstance.parentNode !== container) {
                  error("render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container.");
                }
              }
            }
            var isRootRenderedBySomeReact = !!container._reactRootContainer;
            var rootEl = getReactRootElementInContainer(container);
            var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
            if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
              error("render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.");
            }
            if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") {
              error("render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app.");
            }
          };
        }
        function getReactRootElementInContainer(container) {
          if (!container) {
            return null;
          }
          if (container.nodeType === DOCUMENT_NODE) {
            return container.documentElement;
          } else {
            return container.firstChild;
          }
        }
        function noopOnRecoverableError() {
        }
        function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
          if (isHydrationContainer) {
            if (typeof callback === "function") {
              var originalCallback = callback;
              callback = function() {
                var instance = getPublicRootInstance(root3);
                originalCallback.call(instance);
              };
            }
            var root3 = createHydrationContainer(
              initialChildren,
              callback,
              container,
              LegacyRoot,
              null,
              // hydrationCallbacks
              false,
              // isStrictMode
              false,
              // concurrentUpdatesByDefaultOverride,
              "",
              // identifierPrefix
              noopOnRecoverableError
            );
            container._reactRootContainer = root3;
            markContainerAsRoot(root3.current, container);
            var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
            listenToAllSupportedEvents(rootContainerElement);
            flushSync12();
            return root3;
          } else {
            var rootSibling;
            while (rootSibling = container.lastChild) {
              container.removeChild(rootSibling);
            }
            if (typeof callback === "function") {
              var _originalCallback = callback;
              callback = function() {
                var instance = getPublicRootInstance(_root);
                _originalCallback.call(instance);
              };
            }
            var _root = createContainer(
              container,
              LegacyRoot,
              null,
              // hydrationCallbacks
              false,
              // isStrictMode
              false,
              // concurrentUpdatesByDefaultOverride,
              "",
              // identifierPrefix
              noopOnRecoverableError
            );
            container._reactRootContainer = _root;
            markContainerAsRoot(_root.current, container);
            var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
            listenToAllSupportedEvents(_rootContainerElement);
            flushSync12(function() {
              updateContainer(initialChildren, _root, parentComponent, callback);
            });
            return _root;
          }
        }
        function warnOnInvalidCallback$1(callback, callerName) {
          {
            if (callback !== null && typeof callback !== "function") {
              error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
            }
          }
        }
        function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
          {
            topLevelUpdateWarnings(container);
            warnOnInvalidCallback$1(callback === void 0 ? null : callback, "render");
          }
          var maybeRoot = container._reactRootContainer;
          var root3;
          if (!maybeRoot) {
            root3 = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
          } else {
            root3 = maybeRoot;
            if (typeof callback === "function") {
              var originalCallback = callback;
              callback = function() {
                var instance = getPublicRootInstance(root3);
                originalCallback.call(instance);
              };
            }
            updateContainer(children, root3, parentComponent, callback);
          }
          return getPublicRootInstance(root3);
        }
        function findDOMNode(componentOrElement) {
          {
            var owner = ReactCurrentOwner$3.current;
            if (owner !== null && owner.stateNode !== null) {
              var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
              if (!warnedAboutRefsInRender) {
                error("%s is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromType(owner.type) || "A component");
              }
              owner.stateNode._warnedAboutRefsInRender = true;
            }
          }
          if (componentOrElement == null) {
            return null;
          }
          if (componentOrElement.nodeType === ELEMENT_NODE) {
            return componentOrElement;
          }
          {
            return findHostInstanceWithWarning(componentOrElement, "findDOMNode");
          }
        }
        function hydrate(element, container, callback) {
          {
            error("ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
          }
          if (!isValidContainerLegacy(container)) {
            throw new Error("Target container is not a DOM element.");
          }
          {
            var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
            if (isModernRoot) {
              error("You are calling ReactDOM.hydrate() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call hydrateRoot(container, element)?");
            }
          }
          return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
        }
        function render3(element, container, callback) {
          {
            error("ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
          }
          if (!isValidContainerLegacy(container)) {
            throw new Error("Target container is not a DOM element.");
          }
          {
            var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
            if (isModernRoot) {
              error("You are calling ReactDOM.render() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.render(element)?");
            }
          }
          return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
        }
        function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
          {
            error("ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported in React 18. Consider using a portal instead. Until you switch to the createRoot API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
          }
          if (!isValidContainerLegacy(containerNode)) {
            throw new Error("Target container is not a DOM element.");
          }
          if (parentComponent == null || !has2(parentComponent)) {
            throw new Error("parentComponent must be a valid React Component");
          }
          return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
        }
        function unmountComponentAtNode(container) {
          if (!isValidContainerLegacy(container)) {
            throw new Error("unmountComponentAtNode(...): Target container is not a DOM element.");
          }
          {
            var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
            if (isModernRoot) {
              error("You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?");
            }
          }
          if (container._reactRootContainer) {
            {
              var rootEl = getReactRootElementInContainer(container);
              var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
              if (renderedByDifferentReact) {
                error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.");
              }
            }
            flushSync12(function() {
              legacyRenderSubtreeIntoContainer(null, null, container, false, function() {
                container._reactRootContainer = null;
                unmarkContainerAsRoot(container);
              });
            });
            return true;
          } else {
            {
              var _rootEl = getReactRootElementInContainer(container);
              var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl));
              var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;
              if (hasNonRootReactChild) {
                error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s", isContainerReactRoot ? "You may have accidentally passed in a React root node instead of its container." : "Instead, have the parent component update its state and rerender in order to remove this component.");
              }
            }
            return false;
          }
        }
        setAttemptSynchronousHydration(attemptSynchronousHydration$1);
        setAttemptContinuousHydration(attemptContinuousHydration$1);
        setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
        setGetCurrentUpdatePriority(getCurrentUpdatePriority);
        setAttemptHydrationAtPriority(runWithPriority);
        {
          if (typeof Map !== "function" || // $FlowIssue Flow incorrectly thinks Map has no prototype
          Map.prototype == null || typeof Map.prototype.forEach !== "function" || typeof Set !== "function" || // $FlowIssue Flow incorrectly thinks Set has no prototype
          Set.prototype == null || typeof Set.prototype.clear !== "function" || typeof Set.prototype.forEach !== "function") {
            error("React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
          }
        }
        setRestoreImplementation(restoreControlledState$3);
        setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync12);
        function createPortal$1(children, container) {
          var key = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
          if (!isValidContainer(container)) {
            throw new Error("Target container is not a DOM element.");
          }
          return createPortal2(children, container, null, key);
        }
        function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
          return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
        }
        var Internals = {
          usingClientEntryPoint: false,
          // Keep in sync with ReactTestUtils.js.
          // This is an array for better minification.
          Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
        };
        function createRoot$1(container, options2) {
          {
            if (!Internals.usingClientEntryPoint && true) {
              error('You are importing createRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".');
            }
          }
          return createRoot7(container, options2);
        }
        function hydrateRoot$1(container, initialChildren, options2) {
          {
            if (!Internals.usingClientEntryPoint && true) {
              error('You are importing hydrateRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".');
            }
          }
          return hydrateRoot(container, initialChildren, options2);
        }
        function flushSync$1(fn) {
          {
            if (isAlreadyRendering()) {
              error("flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.");
            }
          }
          return flushSync12(fn);
        }
        var foundDevTools = injectIntoDevTools({
          findFiberByHostInstance: getClosestInstanceFromNode,
          bundleType: 1,
          version: ReactVersion,
          rendererPackageName: "react-dom"
        });
        {
          if (!foundDevTools && canUseDOM && window.top === window.self) {
            if (navigator.userAgent.indexOf("Chrome") > -1 && navigator.userAgent.indexOf("Edge") === -1 || navigator.userAgent.indexOf("Firefox") > -1) {
              var protocol = window.location.protocol;
              if (/^(https?|file):$/.test(protocol)) {
                console.info("%cDownload the React DevTools for a better development experience: https://reactjs.org/link/react-devtools" + (protocol === "file:" ? "\nYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq" : ""), "font-weight:bold");
              }
            }
          }
        }
        exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
        exports.createPortal = createPortal$1;
        exports.createRoot = createRoot$1;
        exports.findDOMNode = findDOMNode;
        exports.flushSync = flushSync$1;
        exports.hydrate = hydrate;
        exports.hydrateRoot = hydrateRoot$1;
        exports.render = render3;
        exports.unmountComponentAtNode = unmountComponentAtNode;
        exports.unstable_batchedUpdates = batchedUpdates$1;
        exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
        exports.version = ReactVersion;
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
        }
      })();
    }
  }
});

// node_modules/react-dom/index.js
var require_react_dom = __commonJS({
  "node_modules/react-dom/index.js"(exports, module2) {
    "use strict";
    if (false) {
      checkDCE();
      module2.exports = null;
    } else {
      module2.exports = require_react_dom_development();
    }
  }
});

// node_modules/react-dom/client.js
var require_client = __commonJS({
  "node_modules/react-dom/client.js"(exports) {
    "use strict";
    var m3 = require_react_dom();
    if (false) {
      exports.createRoot = m3.createRoot;
      exports.hydrateRoot = m3.hydrateRoot;
    } else {
      i3 = m3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      exports.createRoot = function(c4, o3) {
        i3.usingClientEntryPoint = true;
        try {
          return m3.createRoot(c4, o3);
        } finally {
          i3.usingClientEntryPoint = false;
        }
      };
      exports.hydrateRoot = function(c4, h3, o3) {
        i3.usingClientEntryPoint = true;
        try {
          return m3.hydrateRoot(c4, h3, o3);
        } finally {
          i3.usingClientEntryPoint = false;
        }
      };
    }
    var i3;
  }
});

// node_modules/react/cjs/react-jsx-runtime.development.js
var require_react_jsx_runtime_development = __commonJS({
  "node_modules/react/cjs/react-jsx-runtime.development.js"(exports) {
    "use strict";
    if (true) {
      (function() {
        "use strict";
        var React145 = require_react();
        var REACT_ELEMENT_TYPE = Symbol.for("react.element");
        var REACT_PORTAL_TYPE = Symbol.for("react.portal");
        var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
        var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
        var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
        var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
        var REACT_CONTEXT_TYPE = Symbol.for("react.context");
        var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
        var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
        var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
        var REACT_MEMO_TYPE = Symbol.for("react.memo");
        var REACT_LAZY_TYPE = Symbol.for("react.lazy");
        var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
        var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
        var FAUX_ITERATOR_SYMBOL = "@@iterator";
        function getIteratorFn(maybeIterable) {
          if (maybeIterable === null || typeof maybeIterable !== "object") {
            return null;
          }
          var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
          if (typeof maybeIterator === "function") {
            return maybeIterator;
          }
          return null;
        }
        var ReactSharedInternals = React145.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
        function error(format) {
          {
            {
              for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                args[_key2 - 1] = arguments[_key2];
              }
              printWarning("error", format, args);
            }
          }
        }
        function printWarning(level, format, args) {
          {
            var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
            var stack = ReactDebugCurrentFrame2.getStackAddendum();
            if (stack !== "") {
              format += "%s";
              args = args.concat([stack]);
            }
            var argsWithFormat = args.map(function(item) {
              return String(item);
            });
            argsWithFormat.unshift("Warning: " + format);
            Function.prototype.apply.call(console[level], console, argsWithFormat);
          }
        }
        var enableScopeAPI = false;
        var enableCacheElement = false;
        var enableTransitionTracing = false;
        var enableLegacyHidden = false;
        var enableDebugTracing = false;
        var REACT_MODULE_REFERENCE;
        {
          REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
        }
        function isValidElementType(type) {
          if (typeof type === "string" || typeof type === "function") {
            return true;
          }
          if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
            return true;
          }
          if (typeof type === "object" && type !== null) {
            if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
            // types supported by any Flight configuration anywhere since
            // we don't know which Flight build this will end up being used
            // with.
            type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) {
              return true;
            }
          }
          return false;
        }
        function getWrappedName(outerType, innerType, wrapperName) {
          var displayName = outerType.displayName;
          if (displayName) {
            return displayName;
          }
          var functionName = innerType.displayName || innerType.name || "";
          return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
        }
        function getContextName(type) {
          return type.displayName || "Context";
        }
        function getComponentNameFromType(type) {
          if (type == null) {
            return null;
          }
          {
            if (typeof type.tag === "number") {
              error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
            }
          }
          if (typeof type === "function") {
            return type.displayName || type.name || null;
          }
          if (typeof type === "string") {
            return type;
          }
          switch (type) {
            case REACT_FRAGMENT_TYPE:
              return "Fragment";
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_PROFILER_TYPE:
              return "Profiler";
            case REACT_STRICT_MODE_TYPE:
              return "StrictMode";
            case REACT_SUSPENSE_TYPE:
              return "Suspense";
            case REACT_SUSPENSE_LIST_TYPE:
              return "SuspenseList";
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_CONTEXT_TYPE:
                var context = type;
                return getContextName(context) + ".Consumer";
              case REACT_PROVIDER_TYPE:
                var provider = type;
                return getContextName(provider._context) + ".Provider";
              case REACT_FORWARD_REF_TYPE:
                return getWrappedName(type, type.render, "ForwardRef");
              case REACT_MEMO_TYPE:
                var outerName = type.displayName || null;
                if (outerName !== null) {
                  return outerName;
                }
                return getComponentNameFromType(type.type) || "Memo";
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return getComponentNameFromType(init(payload));
                } catch (x2) {
                  return null;
                }
              }
            }
          }
          return null;
        }
        var assign = Object.assign;
        var disabledDepth = 0;
        var prevLog;
        var prevInfo;
        var prevWarn;
        var prevError;
        var prevGroup;
        var prevGroupCollapsed;
        var prevGroupEnd;
        function disabledLog() {
        }
        disabledLog.__reactDisabledLog = true;
        function disableLogs() {
          {
            if (disabledDepth === 0) {
              prevLog = console.log;
              prevInfo = console.info;
              prevWarn = console.warn;
              prevError = console.error;
              prevGroup = console.group;
              prevGroupCollapsed = console.groupCollapsed;
              prevGroupEnd = console.groupEnd;
              var props = {
                configurable: true,
                enumerable: true,
                value: disabledLog,
                writable: true
              };
              Object.defineProperties(console, {
                info: props,
                log: props,
                warn: props,
                error: props,
                group: props,
                groupCollapsed: props,
                groupEnd: props
              });
            }
            disabledDepth++;
          }
        }
        function reenableLogs() {
          {
            disabledDepth--;
            if (disabledDepth === 0) {
              var props = {
                configurable: true,
                enumerable: true,
                writable: true
              };
              Object.defineProperties(console, {
                log: assign({}, props, {
                  value: prevLog
                }),
                info: assign({}, props, {
                  value: prevInfo
                }),
                warn: assign({}, props, {
                  value: prevWarn
                }),
                error: assign({}, props, {
                  value: prevError
                }),
                group: assign({}, props, {
                  value: prevGroup
                }),
                groupCollapsed: assign({}, props, {
                  value: prevGroupCollapsed
                }),
                groupEnd: assign({}, props, {
                  value: prevGroupEnd
                })
              });
            }
            if (disabledDepth < 0) {
              error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
            }
          }
        }
        var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
        var prefix;
        function describeBuiltInComponentFrame(name, source, ownerFn) {
          {
            if (prefix === void 0) {
              try {
                throw Error();
              } catch (x2) {
                var match2 = x2.stack.trim().match(/\n( *(at )?)/);
                prefix = match2 && match2[1] || "";
              }
            }
            return "\n" + prefix + name;
          }
        }
        var reentry = false;
        var componentFrameCache;
        {
          var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
          componentFrameCache = new PossiblyWeakMap();
        }
        function describeNativeComponentFrame(fn, construct) {
          if (!fn || reentry) {
            return "";
          }
          {
            var frame = componentFrameCache.get(fn);
            if (frame !== void 0) {
              return frame;
            }
          }
          var control;
          reentry = true;
          var previousPrepareStackTrace = Error.prepareStackTrace;
          Error.prepareStackTrace = void 0;
          var previousDispatcher;
          {
            previousDispatcher = ReactCurrentDispatcher.current;
            ReactCurrentDispatcher.current = null;
            disableLogs();
          }
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if (typeof Reflect === "object" && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x2) {
                  control = x2;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x2) {
                control = x2;
              }
              fn();
            }
          } catch (sample) {
            if (sample && control && typeof sample.stack === "string") {
              var sampleLines = sample.stack.split("\n");
              var controlLines = control.stack.split("\n");
              var s4 = sampleLines.length - 1;
              var c4 = controlLines.length - 1;
              while (s4 >= 1 && c4 >= 0 && sampleLines[s4] !== controlLines[c4]) {
                c4--;
              }
              for (; s4 >= 1 && c4 >= 0; s4--, c4--) {
                if (sampleLines[s4] !== controlLines[c4]) {
                  if (s4 !== 1 || c4 !== 1) {
                    do {
                      s4--;
                      c4--;
                      if (c4 < 0 || sampleLines[s4] !== controlLines[c4]) {
                        var _frame = "\n" + sampleLines[s4].replace(" at new ", " at ");
                        if (fn.displayName && _frame.includes("<anonymous>")) {
                          _frame = _frame.replace("<anonymous>", fn.displayName);
                        }
                        {
                          if (typeof fn === "function") {
                            componentFrameCache.set(fn, _frame);
                          }
                        }
                        return _frame;
                      }
                    } while (s4 >= 1 && c4 >= 0);
                  }
                  break;
                }
              }
            }
          } finally {
            reentry = false;
            {
              ReactCurrentDispatcher.current = previousDispatcher;
              reenableLogs();
            }
            Error.prepareStackTrace = previousPrepareStackTrace;
          }
          var name = fn ? fn.displayName || fn.name : "";
          var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
          {
            if (typeof fn === "function") {
              componentFrameCache.set(fn, syntheticFrame);
            }
          }
          return syntheticFrame;
        }
        function describeFunctionComponentFrame(fn, source, ownerFn) {
          {
            return describeNativeComponentFrame(fn, false);
          }
        }
        function shouldConstruct(Component2) {
          var prototype = Component2.prototype;
          return !!(prototype && prototype.isReactComponent);
        }
        function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
          if (type == null) {
            return "";
          }
          if (typeof type === "function") {
            {
              return describeNativeComponentFrame(type, shouldConstruct(type));
            }
          }
          if (typeof type === "string") {
            return describeBuiltInComponentFrame(type);
          }
          switch (type) {
            case REACT_SUSPENSE_TYPE:
              return describeBuiltInComponentFrame("Suspense");
            case REACT_SUSPENSE_LIST_TYPE:
              return describeBuiltInComponentFrame("SuspenseList");
          }
          if (typeof type === "object") {
            switch (type.$$typeof) {
              case REACT_FORWARD_REF_TYPE:
                return describeFunctionComponentFrame(type.render);
              case REACT_MEMO_TYPE:
                return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
              case REACT_LAZY_TYPE: {
                var lazyComponent = type;
                var payload = lazyComponent._payload;
                var init = lazyComponent._init;
                try {
                  return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
                } catch (x2) {
                }
              }
            }
          }
          return "";
        }
        var hasOwnProperty3 = Object.prototype.hasOwnProperty;
        var loggedTypeFailures = {};
        var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
        function setCurrentlyValidatingElement(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              ReactDebugCurrentFrame.setExtraStackFrame(stack);
            } else {
              ReactDebugCurrentFrame.setExtraStackFrame(null);
            }
          }
        }
        function checkPropTypes(typeSpecs, values, location2, componentName, element) {
          {
            var has2 = Function.call.bind(hasOwnProperty3);
            for (var typeSpecName in typeSpecs) {
              if (has2(typeSpecs, typeSpecName)) {
                var error$1 = void 0;
                try {
                  if (typeof typeSpecs[typeSpecName] !== "function") {
                    var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                    err.name = "Invariant Violation";
                    throw err;
                  }
                  error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
                } catch (ex) {
                  error$1 = ex;
                }
                if (error$1 && !(error$1 instanceof Error)) {
                  setCurrentlyValidatingElement(element);
                  error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1);
                  setCurrentlyValidatingElement(null);
                }
                if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                  loggedTypeFailures[error$1.message] = true;
                  setCurrentlyValidatingElement(element);
                  error("Failed %s type: %s", location2, error$1.message);
                  setCurrentlyValidatingElement(null);
                }
              }
            }
          }
        }
        var isArrayImpl = Array.isArray;
        function isArray2(a3) {
          return isArrayImpl(a3);
        }
        function typeName(value) {
          {
            var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
            var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
            return type;
          }
        }
        function willCoercionThrow(value) {
          {
            try {
              testStringCoercion(value);
              return false;
            } catch (e3) {
              return true;
            }
          }
        }
        function testStringCoercion(value) {
          return "" + value;
        }
        function checkKeyStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
        var RESERVED_PROPS = {
          key: true,
          ref: true,
          __self: true,
          __source: true
        };
        var specialPropKeyWarningShown;
        var specialPropRefWarningShown;
        var didWarnAboutStringRefs;
        {
          didWarnAboutStringRefs = {};
        }
        function hasValidRef(config) {
          {
            if (hasOwnProperty3.call(config, "ref")) {
              var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.ref !== void 0;
        }
        function hasValidKey(config) {
          {
            if (hasOwnProperty3.call(config, "key")) {
              var getter = Object.getOwnPropertyDescriptor(config, "key").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.key !== void 0;
        }
        function warnIfStringRefCannotBeAutoConverted(config, self2) {
          {
            if (typeof config.ref === "string" && ReactCurrentOwner.current && self2 && ReactCurrentOwner.current.stateNode !== self2) {
              var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
              if (!didWarnAboutStringRefs[componentName]) {
                error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
                didWarnAboutStringRefs[componentName] = true;
              }
            }
          }
        }
        function defineKeyPropWarningGetter(props, displayName) {
          {
            var warnAboutAccessingKey = function() {
              if (!specialPropKeyWarningShown) {
                specialPropKeyWarningShown = true;
                error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            };
            warnAboutAccessingKey.isReactWarning = true;
            Object.defineProperty(props, "key", {
              get: warnAboutAccessingKey,
              configurable: true
            });
          }
        }
        function defineRefPropWarningGetter(props, displayName) {
          {
            var warnAboutAccessingRef = function() {
              if (!specialPropRefWarningShown) {
                specialPropRefWarningShown = true;
                error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            };
            warnAboutAccessingRef.isReactWarning = true;
            Object.defineProperty(props, "ref", {
              get: warnAboutAccessingRef,
              configurable: true
            });
          }
        }
        var ReactElement = function(type, key, ref, self2, source, owner, props) {
          var element = {
            // This tag allows us to uniquely identify this as a React Element
            $$typeof: REACT_ELEMENT_TYPE,
            // Built-in properties that belong on the element
            type,
            key,
            ref,
            props,
            // Record the component responsible for creating this element.
            _owner: owner
          };
          {
            element._store = {};
            Object.defineProperty(element._store, "validated", {
              configurable: false,
              enumerable: false,
              writable: true,
              value: false
            });
            Object.defineProperty(element, "_self", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: self2
            });
            Object.defineProperty(element, "_source", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: source
            });
            if (Object.freeze) {
              Object.freeze(element.props);
              Object.freeze(element);
            }
          }
          return element;
        };
        function jsxDEV(type, config, maybeKey, source, self2) {
          {
            var propName;
            var props = {};
            var key = null;
            var ref = null;
            if (maybeKey !== void 0) {
              {
                checkKeyStringCoercion(maybeKey);
              }
              key = "" + maybeKey;
            }
            if (hasValidKey(config)) {
              {
                checkKeyStringCoercion(config.key);
              }
              key = "" + config.key;
            }
            if (hasValidRef(config)) {
              ref = config.ref;
              warnIfStringRefCannotBeAutoConverted(config, self2);
            }
            for (propName in config) {
              if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
                props[propName] = config[propName];
              }
            }
            if (type && type.defaultProps) {
              var defaultProps2 = type.defaultProps;
              for (propName in defaultProps2) {
                if (props[propName] === void 0) {
                  props[propName] = defaultProps2[propName];
                }
              }
            }
            if (key || ref) {
              var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
              if (key) {
                defineKeyPropWarningGetter(props, displayName);
              }
              if (ref) {
                defineRefPropWarningGetter(props, displayName);
              }
            }
            return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props);
          }
        }
        var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
        var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
        function setCurrentlyValidatingElement$1(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
            } else {
              ReactDebugCurrentFrame$1.setExtraStackFrame(null);
            }
          }
        }
        var propTypesMisspellWarningShown;
        {
          propTypesMisspellWarningShown = false;
        }
        function isValidElement11(object) {
          {
            return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
          }
        }
        function getDeclarationErrorAddendum() {
          {
            if (ReactCurrentOwner$1.current) {
              var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
              if (name) {
                return "\n\nCheck the render method of `" + name + "`.";
              }
            }
            return "";
          }
        }
        function getSourceInfoErrorAddendum(source) {
          {
            if (source !== void 0) {
              var fileName = source.fileName.replace(/^.*[\\\/]/, "");
              var lineNumber = source.lineNumber;
              return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
            }
            return "";
          }
        }
        var ownerHasKeyUseWarning = {};
        function getCurrentComponentErrorInfo(parentType) {
          {
            var info = getDeclarationErrorAddendum();
            if (!info) {
              var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
              if (parentName) {
                info = "\n\nCheck the top-level render call using <" + parentName + ">.";
              }
            }
            return info;
          }
        }
        function validateExplicitKey(element, parentType) {
          {
            if (!element._store || element._store.validated || element.key != null) {
              return;
            }
            element._store.validated = true;
            var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
            if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
              return;
            }
            ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
            var childOwner = "";
            if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
              childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
            }
            setCurrentlyValidatingElement$1(element);
            error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
            setCurrentlyValidatingElement$1(null);
          }
        }
        function validateChildKeys(node, parentType) {
          {
            if (typeof node !== "object") {
              return;
            }
            if (isArray2(node)) {
              for (var i3 = 0; i3 < node.length; i3++) {
                var child = node[i3];
                if (isValidElement11(child)) {
                  validateExplicitKey(child, parentType);
                }
              }
            } else if (isValidElement11(node)) {
              if (node._store) {
                node._store.validated = true;
              }
            } else if (node) {
              var iteratorFn = getIteratorFn(node);
              if (typeof iteratorFn === "function") {
                if (iteratorFn !== node.entries) {
                  var iterator = iteratorFn.call(node);
                  var step;
                  while (!(step = iterator.next()).done) {
                    if (isValidElement11(step.value)) {
                      validateExplicitKey(step.value, parentType);
                    }
                  }
                }
              }
            }
          }
        }
        function validatePropTypes(element) {
          {
            var type = element.type;
            if (type === null || type === void 0 || typeof type === "string") {
              return;
            }
            var propTypes;
            if (typeof type === "function") {
              propTypes = type.propTypes;
            } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
            // Inner props are checked in the reconciler.
            type.$$typeof === REACT_MEMO_TYPE)) {
              propTypes = type.propTypes;
            } else {
              return;
            }
            if (propTypes) {
              var name = getComponentNameFromType(type);
              checkPropTypes(propTypes, element.props, "prop", name, element);
            } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
              propTypesMisspellWarningShown = true;
              var _name = getComponentNameFromType(type);
              error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
            }
            if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
              error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
            }
          }
        }
        function validateFragmentProps(fragment) {
          {
            var keys = Object.keys(fragment.props);
            for (var i3 = 0; i3 < keys.length; i3++) {
              var key = keys[i3];
              if (key !== "children" && key !== "key") {
                setCurrentlyValidatingElement$1(fragment);
                error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
                setCurrentlyValidatingElement$1(null);
                break;
              }
            }
            if (fragment.ref !== null) {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid attribute `ref` supplied to `React.Fragment`.");
              setCurrentlyValidatingElement$1(null);
            }
          }
        }
        function jsxWithValidation(type, props, key, isStaticChildren, source, self2) {
          {
            var validType = isValidElementType(type);
            if (!validType) {
              var info = "";
              if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
                info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
              }
              var sourceInfo = getSourceInfoErrorAddendum(source);
              if (sourceInfo) {
                info += sourceInfo;
              } else {
                info += getDeclarationErrorAddendum();
              }
              var typeString;
              if (type === null) {
                typeString = "null";
              } else if (isArray2(type)) {
                typeString = "array";
              } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
                typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
                info = " Did you accidentally export a JSX literal instead of a component?";
              } else {
                typeString = typeof type;
              }
              error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
            }
            var element = jsxDEV(type, props, key, source, self2);
            if (element == null) {
              return element;
            }
            if (validType) {
              var children = props.children;
              if (children !== void 0) {
                if (isStaticChildren) {
                  if (isArray2(children)) {
                    for (var i3 = 0; i3 < children.length; i3++) {
                      validateChildKeys(children[i3], type);
                    }
                    if (Object.freeze) {
                      Object.freeze(children);
                    }
                  } else {
                    error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
                  }
                } else {
                  validateChildKeys(children, type);
                }
              }
            }
            if (type === REACT_FRAGMENT_TYPE) {
              validateFragmentProps(element);
            } else {
              validatePropTypes(element);
            }
            return element;
          }
        }
        function jsxWithValidationStatic(type, props, key) {
          {
            return jsxWithValidation(type, props, key, true);
          }
        }
        function jsxWithValidationDynamic(type, props, key) {
          {
            return jsxWithValidation(type, props, key, false);
          }
        }
        var jsx63 = jsxWithValidationDynamic;
        var jsxs6 = jsxWithValidationStatic;
        exports.Fragment = REACT_FRAGMENT_TYPE;
        exports.jsx = jsx63;
        exports.jsxs = jsxs6;
      })();
    }
  }
});

// node_modules/react/jsx-runtime.js
var require_jsx_runtime = __commonJS({
  "node_modules/react/jsx-runtime.js"(exports, module2) {
    "use strict";
    if (false) {
      module2.exports = null;
    } else {
      module2.exports = require_react_jsx_runtime_development();
    }
  }
});

// node_modules/moment/moment.js
var require_moment = __commonJS({
  "node_modules/moment/moment.js"(exports, module2) {
    (function(global2, factory) {
      typeof exports === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.moment = factory();
    })(exports, function() {
      "use strict";
      var hookCallback;
      function hooks() {
        return hookCallback.apply(null, arguments);
      }
      function setHookCallback(callback) {
        hookCallback = callback;
      }
      function isArray2(input) {
        return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]";
      }
      function isObject2(input) {
        return input != null && Object.prototype.toString.call(input) === "[object Object]";
      }
      function hasOwnProp(a3, b3) {
        return Object.prototype.hasOwnProperty.call(a3, b3);
      }
      function isObjectEmpty(obj) {
        if (Object.getOwnPropertyNames) {
          return Object.getOwnPropertyNames(obj).length === 0;
        } else {
          var k3;
          for (k3 in obj) {
            if (hasOwnProp(obj, k3)) {
              return false;
            }
          }
          return true;
        }
      }
      function isUndefined2(input) {
        return input === void 0;
      }
      function isNumber3(input) {
        return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]";
      }
      function isDate2(input) {
        return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]";
      }
      function map(arr2, fn) {
        var res = [], i3, arrLen = arr2.length;
        for (i3 = 0; i3 < arrLen; ++i3) {
          res.push(fn(arr2[i3], i3));
        }
        return res;
      }
      function extend(a3, b3) {
        for (var i3 in b3) {
          if (hasOwnProp(b3, i3)) {
            a3[i3] = b3[i3];
          }
        }
        if (hasOwnProp(b3, "toString")) {
          a3.toString = b3.toString;
        }
        if (hasOwnProp(b3, "valueOf")) {
          a3.valueOf = b3.valueOf;
        }
        return a3;
      }
      function createUTC(input, format2, locale2, strict2) {
        return createLocalOrUTC(input, format2, locale2, strict2, true).utc();
      }
      function defaultParsingFlags() {
        return {
          empty: false,
          unusedTokens: [],
          unusedInput: [],
          overflow: -2,
          charsLeftOver: 0,
          nullInput: false,
          invalidEra: null,
          invalidMonth: null,
          invalidFormat: false,
          userInvalidated: false,
          iso: false,
          parsedDateParts: [],
          era: null,
          meridiem: null,
          rfc2822: false,
          weekdayMismatch: false
        };
      }
      function getParsingFlags(m3) {
        if (m3._pf == null) {
          m3._pf = defaultParsingFlags();
        }
        return m3._pf;
      }
      var some;
      if (Array.prototype.some) {
        some = Array.prototype.some;
      } else {
        some = function(fun) {
          var t3 = Object(this), len = t3.length >>> 0, i3;
          for (i3 = 0; i3 < len; i3++) {
            if (i3 in t3 && fun.call(this, t3[i3], i3, t3)) {
              return true;
            }
          }
          return false;
        };
      }
      function isValid2(m3) {
        if (m3._isValid == null) {
          var flags = getParsingFlags(m3), parsedParts = some.call(flags.parsedDateParts, function(i3) {
            return i3 != null;
          }), isNowValid = !isNaN(m3._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
          if (m3._strict) {
            isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === void 0;
          }
          if (Object.isFrozen == null || !Object.isFrozen(m3)) {
            m3._isValid = isNowValid;
          } else {
            return isNowValid;
          }
        }
        return m3._isValid;
      }
      function createInvalid(flags) {
        var m3 = createUTC(NaN);
        if (flags != null) {
          extend(getParsingFlags(m3), flags);
        } else {
          getParsingFlags(m3).userInvalidated = true;
        }
        return m3;
      }
      var momentProperties = hooks.momentProperties = [], updateInProgress = false;
      function copyConfig(to2, from2) {
        var i3, prop, val2, momentPropertiesLen = momentProperties.length;
        if (!isUndefined2(from2._isAMomentObject)) {
          to2._isAMomentObject = from2._isAMomentObject;
        }
        if (!isUndefined2(from2._i)) {
          to2._i = from2._i;
        }
        if (!isUndefined2(from2._f)) {
          to2._f = from2._f;
        }
        if (!isUndefined2(from2._l)) {
          to2._l = from2._l;
        }
        if (!isUndefined2(from2._strict)) {
          to2._strict = from2._strict;
        }
        if (!isUndefined2(from2._tzm)) {
          to2._tzm = from2._tzm;
        }
        if (!isUndefined2(from2._isUTC)) {
          to2._isUTC = from2._isUTC;
        }
        if (!isUndefined2(from2._offset)) {
          to2._offset = from2._offset;
        }
        if (!isUndefined2(from2._pf)) {
          to2._pf = getParsingFlags(from2);
        }
        if (!isUndefined2(from2._locale)) {
          to2._locale = from2._locale;
        }
        if (momentPropertiesLen > 0) {
          for (i3 = 0; i3 < momentPropertiesLen; i3++) {
            prop = momentProperties[i3];
            val2 = from2[prop];
            if (!isUndefined2(val2)) {
              to2[prop] = val2;
            }
          }
        }
        return to2;
      }
      function Moment(config) {
        copyConfig(this, config);
        this._d = new Date(config._d != null ? config._d.getTime() : NaN);
        if (!this.isValid()) {
          this._d = new Date(NaN);
        }
        if (updateInProgress === false) {
          updateInProgress = true;
          hooks.updateOffset(this);
          updateInProgress = false;
        }
      }
      function isMoment(obj) {
        return obj instanceof Moment || obj != null && obj._isAMomentObject != null;
      }
      function warn2(msg) {
        if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) {
          console.warn("Deprecation warning: " + msg);
        }
      }
      function deprecate(msg, fn) {
        var firstTime = true;
        return extend(function() {
          if (hooks.deprecationHandler != null) {
            hooks.deprecationHandler(null, msg);
          }
          if (firstTime) {
            var args = [], arg, i3, key, argLen = arguments.length;
            for (i3 = 0; i3 < argLen; i3++) {
              arg = "";
              if (typeof arguments[i3] === "object") {
                arg += "\n[" + i3 + "] ";
                for (key in arguments[0]) {
                  if (hasOwnProp(arguments[0], key)) {
                    arg += key + ": " + arguments[0][key] + ", ";
                  }
                }
                arg = arg.slice(0, -2);
              } else {
                arg = arguments[i3];
              }
              args.push(arg);
            }
            warn2(
              msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack
            );
            firstTime = false;
          }
          return fn.apply(this, arguments);
        }, fn);
      }
      var deprecations = {};
      function deprecateSimple(name, msg) {
        if (hooks.deprecationHandler != null) {
          hooks.deprecationHandler(name, msg);
        }
        if (!deprecations[name]) {
          warn2(msg);
          deprecations[name] = true;
        }
      }
      hooks.suppressDeprecationWarnings = false;
      hooks.deprecationHandler = null;
      function isFunction2(input) {
        return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]";
      }
      function set(config) {
        var prop, i3;
        for (i3 in config) {
          if (hasOwnProp(config, i3)) {
            prop = config[i3];
            if (isFunction2(prop)) {
              this[i3] = prop;
            } else {
              this["_" + i3] = prop;
            }
          }
        }
        this._config = config;
        this._dayOfMonthOrdinalParseLenient = new RegExp(
          (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source
        );
      }
      function mergeConfigs3(parentConfig, childConfig) {
        var res = extend({}, parentConfig), prop;
        for (prop in childConfig) {
          if (hasOwnProp(childConfig, prop)) {
            if (isObject2(parentConfig[prop]) && isObject2(childConfig[prop])) {
              res[prop] = {};
              extend(res[prop], parentConfig[prop]);
              extend(res[prop], childConfig[prop]);
            } else if (childConfig[prop] != null) {
              res[prop] = childConfig[prop];
            } else {
              delete res[prop];
            }
          }
        }
        for (prop in parentConfig) {
          if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject2(parentConfig[prop])) {
            res[prop] = extend({}, res[prop]);
          }
        }
        return res;
      }
      function Locale2(config) {
        if (config != null) {
          this.set(config);
        }
      }
      var keys;
      if (Object.keys) {
        keys = Object.keys;
      } else {
        keys = function(obj) {
          var i3, res = [];
          for (i3 in obj) {
            if (hasOwnProp(obj, i3)) {
              res.push(i3);
            }
          }
          return res;
        };
      }
      var defaultCalendar = {
        sameDay: "[Today at] LT",
        nextDay: "[Tomorrow at] LT",
        nextWeek: "dddd [at] LT",
        lastDay: "[Yesterday at] LT",
        lastWeek: "[Last] dddd [at] LT",
        sameElse: "L"
      };
      function calendar(key, mom, now4) {
        var output = this._calendar[key] || this._calendar["sameElse"];
        return isFunction2(output) ? output.call(mom, now4) : output;
      }
      function zeroFill(number, targetLength, forceSign) {
        var absNumber = "" + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign2 = number >= 0;
        return (sign2 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
      }
      var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {};
      function addFormatToken(token2, padded, ordinal2, callback) {
        var func = callback;
        if (typeof callback === "string") {
          func = function() {
            return this[callback]();
          };
        }
        if (token2) {
          formatTokenFunctions[token2] = func;
        }
        if (padded) {
          formatTokenFunctions[padded[0]] = function() {
            return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
          };
        }
        if (ordinal2) {
          formatTokenFunctions[ordinal2] = function() {
            return this.localeData().ordinal(
              func.apply(this, arguments),
              token2
            );
          };
        }
      }
      function removeFormattingTokens(input) {
        if (input.match(/\[[\s\S]/)) {
          return input.replace(/^\[|\]$/g, "");
        }
        return input.replace(/\\/g, "");
      }
      function makeFormatFunction(format2) {
        var array = format2.match(formattingTokens), i3, length;
        for (i3 = 0, length = array.length; i3 < length; i3++) {
          if (formatTokenFunctions[array[i3]]) {
            array[i3] = formatTokenFunctions[array[i3]];
          } else {
            array[i3] = removeFormattingTokens(array[i3]);
          }
        }
        return function(mom) {
          var output = "", i4;
          for (i4 = 0; i4 < length; i4++) {
            output += isFunction2(array[i4]) ? array[i4].call(mom, format2) : array[i4];
          }
          return output;
        };
      }
      function formatMoment(m3, format2) {
        if (!m3.isValid()) {
          return m3.localeData().invalidDate();
        }
        format2 = expandFormat(format2, m3.localeData());
        formatFunctions[format2] = formatFunctions[format2] || makeFormatFunction(format2);
        return formatFunctions[format2](m3);
      }
      function expandFormat(format2, locale2) {
        var i3 = 5;
        function replaceLongDateFormatTokens(input) {
          return locale2.longDateFormat(input) || input;
        }
        localFormattingTokens.lastIndex = 0;
        while (i3 >= 0 && localFormattingTokens.test(format2)) {
          format2 = format2.replace(
            localFormattingTokens,
            replaceLongDateFormatTokens
          );
          localFormattingTokens.lastIndex = 0;
          i3 -= 1;
        }
        return format2;
      }
      var defaultLongDateFormat = {
        LTS: "h:mm:ss A",
        LT: "h:mm A",
        L: "MM/DD/YYYY",
        LL: "MMMM D, YYYY",
        LLL: "MMMM D, YYYY h:mm A",
        LLLL: "dddd, MMMM D, YYYY h:mm A"
      };
      function longDateFormat(key) {
        var format2 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()];
        if (format2 || !formatUpper) {
          return format2;
        }
        this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) {
          if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") {
            return tok.slice(1);
          }
          return tok;
        }).join("");
        return this._longDateFormat[key];
      }
      var defaultInvalidDate = "Invalid date";
      function invalidDate() {
        return this._invalidDate;
      }
      var defaultOrdinal = "%d", defaultDayOfMonthOrdinalParse = /\d{1,2}/;
      function ordinal(number) {
        return this._ordinal.replace("%d", number);
      }
      var defaultRelativeTime = {
        future: "in %s",
        past: "%s ago",
        s: "a few seconds",
        ss: "%d seconds",
        m: "a minute",
        mm: "%d minutes",
        h: "an hour",
        hh: "%d hours",
        d: "a day",
        dd: "%d days",
        w: "a week",
        ww: "%d weeks",
        M: "a month",
        MM: "%d months",
        y: "a year",
        yy: "%d years"
      };
      function relativeTime(number, withoutSuffix, string, isFuture) {
        var output = this._relativeTime[string];
        return isFunction2(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
      }
      function pastFuture(diff2, output) {
        var format2 = this._relativeTime[diff2 > 0 ? "future" : "past"];
        return isFunction2(format2) ? format2(output) : format2.replace(/%s/i, output);
      }
      var aliases = {};
      function addUnitAlias(unit, shorthand) {
        var lowerCase = unit.toLowerCase();
        aliases[lowerCase] = aliases[lowerCase + "s"] = aliases[shorthand] = unit;
      }
      function normalizeUnits(units) {
        return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0;
      }
      function normalizeObjectUnits(inputObject) {
        var normalizedInput = {}, normalizedProp, prop;
        for (prop in inputObject) {
          if (hasOwnProp(inputObject, prop)) {
            normalizedProp = normalizeUnits(prop);
            if (normalizedProp) {
              normalizedInput[normalizedProp] = inputObject[prop];
            }
          }
        }
        return normalizedInput;
      }
      var priorities = {};
      function addUnitPriority(unit, priority) {
        priorities[unit] = priority;
      }
      function getPrioritizedUnits(unitsObj) {
        var units = [], u3;
        for (u3 in unitsObj) {
          if (hasOwnProp(unitsObj, u3)) {
            units.push({ unit: u3, priority: priorities[u3] });
          }
        }
        units.sort(function(a3, b3) {
          return a3.priority - b3.priority;
        });
        return units;
      }
      function isLeapYear4(year) {
        return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
      }
      function absFloor(number) {
        if (number < 0) {
          return Math.ceil(number) || 0;
        } else {
          return Math.floor(number);
        }
      }
      function toInt(argumentForCoercion) {
        var coercedNumber = +argumentForCoercion, value = 0;
        if (coercedNumber !== 0 && isFinite(coercedNumber)) {
          value = absFloor(coercedNumber);
        }
        return value;
      }
      function makeGetSet(unit, keepTime) {
        return function(value) {
          if (value != null) {
            set$1(this, unit, value);
            hooks.updateOffset(this, keepTime);
            return this;
          } else {
            return get4(this, unit);
          }
        };
      }
      function get4(mom, unit) {
        return mom.isValid() ? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]() : NaN;
      }
      function set$1(mom, unit, value) {
        if (mom.isValid() && !isNaN(value)) {
          if (unit === "FullYear" && isLeapYear4(mom.year()) && mom.month() === 1 && mom.date() === 29) {
            value = toInt(value);
            mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](
              value,
              mom.month(),
              daysInMonth2(value, mom.month())
            );
          } else {
            mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value);
          }
        }
      }
      function stringGet(units) {
        units = normalizeUnits(units);
        if (isFunction2(this[units])) {
          return this[units]();
        }
        return this;
      }
      function stringSet(units, value) {
        if (typeof units === "object") {
          units = normalizeObjectUnits(units);
          var prioritized = getPrioritizedUnits(units), i3, prioritizedLen = prioritized.length;
          for (i3 = 0; i3 < prioritizedLen; i3++) {
            this[prioritized[i3].unit](units[prioritized[i3].unit]);
          }
        } else {
          units = normalizeUnits(units);
          if (isFunction2(this[units])) {
            return this[units](value);
          }
        }
        return this;
      }
      var match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, regexes;
      regexes = {};
      function addRegexToken(token2, regex2, strictRegex) {
        regexes[token2] = isFunction2(regex2) ? regex2 : function(isStrict, localeData2) {
          return isStrict && strictRegex ? strictRegex : regex2;
        };
      }
      function getParseRegexForToken(token2, config) {
        if (!hasOwnProp(regexes, token2)) {
          return new RegExp(unescapeFormat(token2));
        }
        return regexes[token2](config._strict, config._locale);
      }
      function unescapeFormat(s4) {
        return regexEscape(
          s4.replace("\\", "").replace(
            /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
            function(matched, p1, p22, p3, p4) {
              return p1 || p22 || p3 || p4;
            }
          )
        );
      }
      function regexEscape(s4) {
        return s4.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
      }
      var tokens = {};
      function addParseToken(token2, callback) {
        var i3, func = callback, tokenLen;
        if (typeof token2 === "string") {
          token2 = [token2];
        }
        if (isNumber3(callback)) {
          func = function(input, array) {
            array[callback] = toInt(input);
          };
        }
        tokenLen = token2.length;
        for (i3 = 0; i3 < tokenLen; i3++) {
          tokens[token2[i3]] = func;
        }
      }
      function addWeekParseToken(token2, callback) {
        addParseToken(token2, function(input, array, config, token3) {
          config._w = config._w || {};
          callback(input, config._w, config, token3);
        });
      }
      function addTimeToArrayFromToken(token2, input, config) {
        if (input != null && hasOwnProp(tokens, token2)) {
          tokens[token2](input, config._a, config, token2);
        }
      }
      var YEAR = 0, MONTH = 1, DATE2 = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8;
      function mod(n4, x2) {
        return (n4 % x2 + x2) % x2;
      }
      var indexOf;
      if (Array.prototype.indexOf) {
        indexOf = Array.prototype.indexOf;
      } else {
        indexOf = function(o3) {
          var i3;
          for (i3 = 0; i3 < this.length; ++i3) {
            if (this[i3] === o3) {
              return i3;
            }
          }
          return -1;
        };
      }
      function daysInMonth2(year, month) {
        if (isNaN(year) || isNaN(month)) {
          return NaN;
        }
        var modMonth = mod(month, 12);
        year += (month - modMonth) / 12;
        return modMonth === 1 ? isLeapYear4(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
      }
      addFormatToken("M", ["MM", 2], "Mo", function() {
        return this.month() + 1;
      });
      addFormatToken("MMM", 0, 0, function(format2) {
        return this.localeData().monthsShort(this, format2);
      });
      addFormatToken("MMMM", 0, 0, function(format2) {
        return this.localeData().months(this, format2);
      });
      addUnitAlias("month", "M");
      addUnitPriority("month", 8);
      addRegexToken("M", match1to2);
      addRegexToken("MM", match1to2, match2);
      addRegexToken("MMM", function(isStrict, locale2) {
        return locale2.monthsShortRegex(isStrict);
      });
      addRegexToken("MMMM", function(isStrict, locale2) {
        return locale2.monthsRegex(isStrict);
      });
      addParseToken(["M", "MM"], function(input, array) {
        array[MONTH] = toInt(input) - 1;
      });
      addParseToken(["MMM", "MMMM"], function(input, array, config, token2) {
        var month = config._locale.monthsParse(input, token2, config._strict);
        if (month != null) {
          array[MONTH] = month;
        } else {
          getParsingFlags(config).invalidMonth = input;
        }
      });
      var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split(
        "_"
      ), defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord;
      function localeMonths(m3, format2) {
        if (!m3) {
          return isArray2(this._months) ? this._months : this._months["standalone"];
        }
        return isArray2(this._months) ? this._months[m3.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format2) ? "format" : "standalone"][m3.month()];
      }
      function localeMonthsShort(m3, format2) {
        if (!m3) {
          return isArray2(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"];
        }
        return isArray2(this._monthsShort) ? this._monthsShort[m3.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format2) ? "format" : "standalone"][m3.month()];
      }
      function handleStrictParse(monthName, format2, strict2) {
        var i3, ii, mom, llc = monthName.toLocaleLowerCase();
        if (!this._monthsParse) {
          this._monthsParse = [];
          this._longMonthsParse = [];
          this._shortMonthsParse = [];
          for (i3 = 0; i3 < 12; ++i3) {
            mom = createUTC([2e3, i3]);
            this._shortMonthsParse[i3] = this.monthsShort(
              mom,
              ""
            ).toLocaleLowerCase();
            this._longMonthsParse[i3] = this.months(mom, "").toLocaleLowerCase();
          }
        }
        if (strict2) {
          if (format2 === "MMM") {
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
          } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
          }
        } else {
          if (format2 === "MMM") {
            ii = indexOf.call(this._shortMonthsParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._longMonthsParse, llc);
            return ii !== -1 ? ii : null;
          } else {
            ii = indexOf.call(this._longMonthsParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._shortMonthsParse, llc);
            return ii !== -1 ? ii : null;
          }
        }
      }
      function localeMonthsParse(monthName, format2, strict2) {
        var i3, mom, regex2;
        if (this._monthsParseExact) {
          return handleStrictParse.call(this, monthName, format2, strict2);
        }
        if (!this._monthsParse) {
          this._monthsParse = [];
          this._longMonthsParse = [];
          this._shortMonthsParse = [];
        }
        for (i3 = 0; i3 < 12; i3++) {
          mom = createUTC([2e3, i3]);
          if (strict2 && !this._longMonthsParse[i3]) {
            this._longMonthsParse[i3] = new RegExp(
              "^" + this.months(mom, "").replace(".", "") + "$",
              "i"
            );
            this._shortMonthsParse[i3] = new RegExp(
              "^" + this.monthsShort(mom, "").replace(".", "") + "$",
              "i"
            );
          }
          if (!strict2 && !this._monthsParse[i3]) {
            regex2 = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, "");
            this._monthsParse[i3] = new RegExp(regex2.replace(".", ""), "i");
          }
          if (strict2 && format2 === "MMMM" && this._longMonthsParse[i3].test(monthName)) {
            return i3;
          } else if (strict2 && format2 === "MMM" && this._shortMonthsParse[i3].test(monthName)) {
            return i3;
          } else if (!strict2 && this._monthsParse[i3].test(monthName)) {
            return i3;
          }
        }
      }
      function setMonth(mom, value) {
        var dayOfMonth;
        if (!mom.isValid()) {
          return mom;
        }
        if (typeof value === "string") {
          if (/^\d+$/.test(value)) {
            value = toInt(value);
          } else {
            value = mom.localeData().monthsParse(value);
            if (!isNumber3(value)) {
              return mom;
            }
          }
        }
        dayOfMonth = Math.min(mom.date(), daysInMonth2(mom.year(), value));
        mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth);
        return mom;
      }
      function getSetMonth(value) {
        if (value != null) {
          setMonth(this, value);
          hooks.updateOffset(this, true);
          return this;
        } else {
          return get4(this, "Month");
        }
      }
      function getDaysInMonth() {
        return daysInMonth2(this.year(), this.month());
      }
      function monthsShortRegex(isStrict) {
        if (this._monthsParseExact) {
          if (!hasOwnProp(this, "_monthsRegex")) {
            computeMonthsParse.call(this);
          }
          if (isStrict) {
            return this._monthsShortStrictRegex;
          } else {
            return this._monthsShortRegex;
          }
        } else {
          if (!hasOwnProp(this, "_monthsShortRegex")) {
            this._monthsShortRegex = defaultMonthsShortRegex;
          }
          return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex;
        }
      }
      function monthsRegex(isStrict) {
        if (this._monthsParseExact) {
          if (!hasOwnProp(this, "_monthsRegex")) {
            computeMonthsParse.call(this);
          }
          if (isStrict) {
            return this._monthsStrictRegex;
          } else {
            return this._monthsRegex;
          }
        } else {
          if (!hasOwnProp(this, "_monthsRegex")) {
            this._monthsRegex = defaultMonthsRegex;
          }
          return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex;
        }
      }
      function computeMonthsParse() {
        function cmpLenRev(a3, b3) {
          return b3.length - a3.length;
        }
        var shortPieces = [], longPieces = [], mixedPieces = [], i3, mom;
        for (i3 = 0; i3 < 12; i3++) {
          mom = createUTC([2e3, i3]);
          shortPieces.push(this.monthsShort(mom, ""));
          longPieces.push(this.months(mom, ""));
          mixedPieces.push(this.months(mom, ""));
          mixedPieces.push(this.monthsShort(mom, ""));
        }
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        for (i3 = 0; i3 < 12; i3++) {
          shortPieces[i3] = regexEscape(shortPieces[i3]);
          longPieces[i3] = regexEscape(longPieces[i3]);
        }
        for (i3 = 0; i3 < 24; i3++) {
          mixedPieces[i3] = regexEscape(mixedPieces[i3]);
        }
        this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
        this._monthsShortRegex = this._monthsRegex;
        this._monthsStrictRegex = new RegExp(
          "^(" + longPieces.join("|") + ")",
          "i"
        );
        this._monthsShortStrictRegex = new RegExp(
          "^(" + shortPieces.join("|") + ")",
          "i"
        );
      }
      addFormatToken("Y", 0, 0, function() {
        var y2 = this.year();
        return y2 <= 9999 ? zeroFill(y2, 4) : "+" + y2;
      });
      addFormatToken(0, ["YY", 2], 0, function() {
        return this.year() % 100;
      });
      addFormatToken(0, ["YYYY", 4], 0, "year");
      addFormatToken(0, ["YYYYY", 5], 0, "year");
      addFormatToken(0, ["YYYYYY", 6, true], 0, "year");
      addUnitAlias("year", "y");
      addUnitPriority("year", 1);
      addRegexToken("Y", matchSigned);
      addRegexToken("YY", match1to2, match2);
      addRegexToken("YYYY", match1to4, match4);
      addRegexToken("YYYYY", match1to6, match6);
      addRegexToken("YYYYYY", match1to6, match6);
      addParseToken(["YYYYY", "YYYYYY"], YEAR);
      addParseToken("YYYY", function(input, array) {
        array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
      });
      addParseToken("YY", function(input, array) {
        array[YEAR] = hooks.parseTwoDigitYear(input);
      });
      addParseToken("Y", function(input, array) {
        array[YEAR] = parseInt(input, 10);
      });
      function daysInYear2(year) {
        return isLeapYear4(year) ? 366 : 365;
      }
      hooks.parseTwoDigitYear = function(input) {
        return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3);
      };
      var getSetYear = makeGetSet("FullYear", true);
      function getIsLeapYear() {
        return isLeapYear4(this.year());
      }
      function createDate(y2, m3, d3, h3, M, s4, ms) {
        var date2;
        if (y2 < 100 && y2 >= 0) {
          date2 = new Date(y2 + 400, m3, d3, h3, M, s4, ms);
          if (isFinite(date2.getFullYear())) {
            date2.setFullYear(y2);
          }
        } else {
          date2 = new Date(y2, m3, d3, h3, M, s4, ms);
        }
        return date2;
      }
      function createUTCDate(y2) {
        var date2, args;
        if (y2 < 100 && y2 >= 0) {
          args = Array.prototype.slice.call(arguments);
          args[0] = y2 + 400;
          date2 = new Date(Date.UTC.apply(null, args));
          if (isFinite(date2.getUTCFullYear())) {
            date2.setUTCFullYear(y2);
          }
        } else {
          date2 = new Date(Date.UTC.apply(null, arguments));
        }
        return date2;
      }
      function firstWeekOffset2(year, dow, doy) {
        var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
        return -fwdlw + fwd - 1;
      }
      function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
        var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset2(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear;
        if (dayOfYear <= 0) {
          resYear = year - 1;
          resDayOfYear = daysInYear2(resYear) + dayOfYear;
        } else if (dayOfYear > daysInYear2(year)) {
          resYear = year + 1;
          resDayOfYear = dayOfYear - daysInYear2(year);
        } else {
          resYear = year;
          resDayOfYear = dayOfYear;
        }
        return {
          year: resYear,
          dayOfYear: resDayOfYear
        };
      }
      function weekOfYear(mom, dow, doy) {
        var weekOffset = firstWeekOffset2(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear;
        if (week < 1) {
          resYear = mom.year() - 1;
          resWeek = week + weeksInYear(resYear, dow, doy);
        } else if (week > weeksInYear(mom.year(), dow, doy)) {
          resWeek = week - weeksInYear(mom.year(), dow, doy);
          resYear = mom.year() + 1;
        } else {
          resYear = mom.year();
          resWeek = week;
        }
        return {
          week: resWeek,
          year: resYear
        };
      }
      function weeksInYear(year, dow, doy) {
        var weekOffset = firstWeekOffset2(year, dow, doy), weekOffsetNext = firstWeekOffset2(year + 1, dow, doy);
        return (daysInYear2(year) - weekOffset + weekOffsetNext) / 7;
      }
      addFormatToken("w", ["ww", 2], "wo", "week");
      addFormatToken("W", ["WW", 2], "Wo", "isoWeek");
      addUnitAlias("week", "w");
      addUnitAlias("isoWeek", "W");
      addUnitPriority("week", 5);
      addUnitPriority("isoWeek", 5);
      addRegexToken("w", match1to2);
      addRegexToken("ww", match1to2, match2);
      addRegexToken("W", match1to2);
      addRegexToken("WW", match1to2, match2);
      addWeekParseToken(
        ["w", "ww", "W", "WW"],
        function(input, week, config, token2) {
          week[token2.substr(0, 1)] = toInt(input);
        }
      );
      function localeWeek(mom) {
        return weekOfYear(mom, this._week.dow, this._week.doy).week;
      }
      var defaultLocaleWeek = {
        dow: 0,
        // Sunday is the first day of the week.
        doy: 6
        // The week that contains Jan 6th is the first week of the year.
      };
      function localeFirstDayOfWeek() {
        return this._week.dow;
      }
      function localeFirstDayOfYear() {
        return this._week.doy;
      }
      function getSetWeek(input) {
        var week = this.localeData().week(this);
        return input == null ? week : this.add((input - week) * 7, "d");
      }
      function getSetISOWeek(input) {
        var week = weekOfYear(this, 1, 4).week;
        return input == null ? week : this.add((input - week) * 7, "d");
      }
      addFormatToken("d", 0, "do", "day");
      addFormatToken("dd", 0, 0, function(format2) {
        return this.localeData().weekdaysMin(this, format2);
      });
      addFormatToken("ddd", 0, 0, function(format2) {
        return this.localeData().weekdaysShort(this, format2);
      });
      addFormatToken("dddd", 0, 0, function(format2) {
        return this.localeData().weekdays(this, format2);
      });
      addFormatToken("e", 0, 0, "weekday");
      addFormatToken("E", 0, 0, "isoWeekday");
      addUnitAlias("day", "d");
      addUnitAlias("weekday", "e");
      addUnitAlias("isoWeekday", "E");
      addUnitPriority("day", 11);
      addUnitPriority("weekday", 11);
      addUnitPriority("isoWeekday", 11);
      addRegexToken("d", match1to2);
      addRegexToken("e", match1to2);
      addRegexToken("E", match1to2);
      addRegexToken("dd", function(isStrict, locale2) {
        return locale2.weekdaysMinRegex(isStrict);
      });
      addRegexToken("ddd", function(isStrict, locale2) {
        return locale2.weekdaysShortRegex(isStrict);
      });
      addRegexToken("dddd", function(isStrict, locale2) {
        return locale2.weekdaysRegex(isStrict);
      });
      addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config, token2) {
        var weekday = config._locale.weekdaysParse(input, token2, config._strict);
        if (weekday != null) {
          week.d = weekday;
        } else {
          getParsingFlags(config).invalidWeekday = input;
        }
      });
      addWeekParseToken(["d", "e", "E"], function(input, week, config, token2) {
        week[token2] = toInt(input);
      });
      function parseWeekday(input, locale2) {
        if (typeof input !== "string") {
          return input;
        }
        if (!isNaN(input)) {
          return parseInt(input, 10);
        }
        input = locale2.weekdaysParse(input);
        if (typeof input === "number") {
          return input;
        }
        return null;
      }
      function parseIsoWeekday(input, locale2) {
        if (typeof input === "string") {
          return locale2.weekdaysParse(input) % 7 || 7;
        }
        return isNaN(input) ? null : input;
      }
      function shiftWeekdays(ws, n4) {
        return ws.slice(n4, 7).concat(ws.slice(0, n4));
      }
      var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord;
      function localeWeekdays(m3, format2) {
        var weekdays2 = isArray2(this._weekdays) ? this._weekdays : this._weekdays[m3 && m3 !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"];
        return m3 === true ? shiftWeekdays(weekdays2, this._week.dow) : m3 ? weekdays2[m3.day()] : weekdays2;
      }
      function localeWeekdaysShort(m3) {
        return m3 === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m3 ? this._weekdaysShort[m3.day()] : this._weekdaysShort;
      }
      function localeWeekdaysMin(m3) {
        return m3 === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m3 ? this._weekdaysMin[m3.day()] : this._weekdaysMin;
      }
      function handleStrictParse$1(weekdayName, format2, strict2) {
        var i3, ii, mom, llc = weekdayName.toLocaleLowerCase();
        if (!this._weekdaysParse) {
          this._weekdaysParse = [];
          this._shortWeekdaysParse = [];
          this._minWeekdaysParse = [];
          for (i3 = 0; i3 < 7; ++i3) {
            mom = createUTC([2e3, 1]).day(i3);
            this._minWeekdaysParse[i3] = this.weekdaysMin(
              mom,
              ""
            ).toLocaleLowerCase();
            this._shortWeekdaysParse[i3] = this.weekdaysShort(
              mom,
              ""
            ).toLocaleLowerCase();
            this._weekdaysParse[i3] = this.weekdays(mom, "").toLocaleLowerCase();
          }
        }
        if (strict2) {
          if (format2 === "dddd") {
            ii = indexOf.call(this._weekdaysParse, llc);
            return ii !== -1 ? ii : null;
          } else if (format2 === "ddd") {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
          } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
          }
        } else {
          if (format2 === "dddd") {
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
          } else if (format2 === "ddd") {
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._minWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
          } else {
            ii = indexOf.call(this._minWeekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._weekdaysParse, llc);
            if (ii !== -1) {
              return ii;
            }
            ii = indexOf.call(this._shortWeekdaysParse, llc);
            return ii !== -1 ? ii : null;
          }
        }
      }
      function localeWeekdaysParse(weekdayName, format2, strict2) {
        var i3, mom, regex2;
        if (this._weekdaysParseExact) {
          return handleStrictParse$1.call(this, weekdayName, format2, strict2);
        }
        if (!this._weekdaysParse) {
          this._weekdaysParse = [];
          this._minWeekdaysParse = [];
          this._shortWeekdaysParse = [];
          this._fullWeekdaysParse = [];
        }
        for (i3 = 0; i3 < 7; i3++) {
          mom = createUTC([2e3, 1]).day(i3);
          if (strict2 && !this._fullWeekdaysParse[i3]) {
            this._fullWeekdaysParse[i3] = new RegExp(
              "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$",
              "i"
            );
            this._shortWeekdaysParse[i3] = new RegExp(
              "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$",
              "i"
            );
            this._minWeekdaysParse[i3] = new RegExp(
              "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$",
              "i"
            );
          }
          if (!this._weekdaysParse[i3]) {
            regex2 = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, "");
            this._weekdaysParse[i3] = new RegExp(regex2.replace(".", ""), "i");
          }
          if (strict2 && format2 === "dddd" && this._fullWeekdaysParse[i3].test(weekdayName)) {
            return i3;
          } else if (strict2 && format2 === "ddd" && this._shortWeekdaysParse[i3].test(weekdayName)) {
            return i3;
          } else if (strict2 && format2 === "dd" && this._minWeekdaysParse[i3].test(weekdayName)) {
            return i3;
          } else if (!strict2 && this._weekdaysParse[i3].test(weekdayName)) {
            return i3;
          }
        }
      }
      function getSetDayOfWeek(input) {
        if (!this.isValid()) {
          return input != null ? this : NaN;
        }
        var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
        if (input != null) {
          input = parseWeekday(input, this.localeData());
          return this.add(input - day, "d");
        } else {
          return day;
        }
      }
      function getSetLocaleDayOfWeek(input) {
        if (!this.isValid()) {
          return input != null ? this : NaN;
        }
        var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
        return input == null ? weekday : this.add(input - weekday, "d");
      }
      function getSetISODayOfWeek(input) {
        if (!this.isValid()) {
          return input != null ? this : NaN;
        }
        if (input != null) {
          var weekday = parseIsoWeekday(input, this.localeData());
          return this.day(this.day() % 7 ? weekday : weekday - 7);
        } else {
          return this.day() || 7;
        }
      }
      function weekdaysRegex(isStrict) {
        if (this._weekdaysParseExact) {
          if (!hasOwnProp(this, "_weekdaysRegex")) {
            computeWeekdaysParse.call(this);
          }
          if (isStrict) {
            return this._weekdaysStrictRegex;
          } else {
            return this._weekdaysRegex;
          }
        } else {
          if (!hasOwnProp(this, "_weekdaysRegex")) {
            this._weekdaysRegex = defaultWeekdaysRegex;
          }
          return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex;
        }
      }
      function weekdaysShortRegex(isStrict) {
        if (this._weekdaysParseExact) {
          if (!hasOwnProp(this, "_weekdaysRegex")) {
            computeWeekdaysParse.call(this);
          }
          if (isStrict) {
            return this._weekdaysShortStrictRegex;
          } else {
            return this._weekdaysShortRegex;
          }
        } else {
          if (!hasOwnProp(this, "_weekdaysShortRegex")) {
            this._weekdaysShortRegex = defaultWeekdaysShortRegex;
          }
          return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
        }
      }
      function weekdaysMinRegex(isStrict) {
        if (this._weekdaysParseExact) {
          if (!hasOwnProp(this, "_weekdaysRegex")) {
            computeWeekdaysParse.call(this);
          }
          if (isStrict) {
            return this._weekdaysMinStrictRegex;
          } else {
            return this._weekdaysMinRegex;
          }
        } else {
          if (!hasOwnProp(this, "_weekdaysMinRegex")) {
            this._weekdaysMinRegex = defaultWeekdaysMinRegex;
          }
          return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
        }
      }
      function computeWeekdaysParse() {
        function cmpLenRev(a3, b3) {
          return b3.length - a3.length;
        }
        var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i3, mom, minp, shortp, longp;
        for (i3 = 0; i3 < 7; i3++) {
          mom = createUTC([2e3, 1]).day(i3);
          minp = regexEscape(this.weekdaysMin(mom, ""));
          shortp = regexEscape(this.weekdaysShort(mom, ""));
          longp = regexEscape(this.weekdays(mom, ""));
          minPieces.push(minp);
          shortPieces.push(shortp);
          longPieces.push(longp);
          mixedPieces.push(minp);
          mixedPieces.push(shortp);
          mixedPieces.push(longp);
        }
        minPieces.sort(cmpLenRev);
        shortPieces.sort(cmpLenRev);
        longPieces.sort(cmpLenRev);
        mixedPieces.sort(cmpLenRev);
        this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
        this._weekdaysShortRegex = this._weekdaysRegex;
        this._weekdaysMinRegex = this._weekdaysRegex;
        this._weekdaysStrictRegex = new RegExp(
          "^(" + longPieces.join("|") + ")",
          "i"
        );
        this._weekdaysShortStrictRegex = new RegExp(
          "^(" + shortPieces.join("|") + ")",
          "i"
        );
        this._weekdaysMinStrictRegex = new RegExp(
          "^(" + minPieces.join("|") + ")",
          "i"
        );
      }
      function hFormat() {
        return this.hours() % 12 || 12;
      }
      function kFormat() {
        return this.hours() || 24;
      }
      addFormatToken("H", ["HH", 2], 0, "hour");
      addFormatToken("h", ["hh", 2], 0, hFormat);
      addFormatToken("k", ["kk", 2], 0, kFormat);
      addFormatToken("hmm", 0, 0, function() {
        return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2);
      });
      addFormatToken("hmmss", 0, 0, function() {
        return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
      });
      addFormatToken("Hmm", 0, 0, function() {
        return "" + this.hours() + zeroFill(this.minutes(), 2);
      });
      addFormatToken("Hmmss", 0, 0, function() {
        return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
      });
      function meridiem(token2, lowercase) {
        addFormatToken(token2, 0, 0, function() {
          return this.localeData().meridiem(
            this.hours(),
            this.minutes(),
            lowercase
          );
        });
      }
      meridiem("a", true);
      meridiem("A", false);
      addUnitAlias("hour", "h");
      addUnitPriority("hour", 13);
      function matchMeridiem(isStrict, locale2) {
        return locale2._meridiemParse;
      }
      addRegexToken("a", matchMeridiem);
      addRegexToken("A", matchMeridiem);
      addRegexToken("H", match1to2);
      addRegexToken("h", match1to2);
      addRegexToken("k", match1to2);
      addRegexToken("HH", match1to2, match2);
      addRegexToken("hh", match1to2, match2);
      addRegexToken("kk", match1to2, match2);
      addRegexToken("hmm", match3to4);
      addRegexToken("hmmss", match5to6);
      addRegexToken("Hmm", match3to4);
      addRegexToken("Hmmss", match5to6);
      addParseToken(["H", "HH"], HOUR);
      addParseToken(["k", "kk"], function(input, array, config) {
        var kInput = toInt(input);
        array[HOUR] = kInput === 24 ? 0 : kInput;
      });
      addParseToken(["a", "A"], function(input, array, config) {
        config._isPm = config._locale.isPM(input);
        config._meridiem = input;
      });
      addParseToken(["h", "hh"], function(input, array, config) {
        array[HOUR] = toInt(input);
        getParsingFlags(config).bigHour = true;
      });
      addParseToken("hmm", function(input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
        getParsingFlags(config).bigHour = true;
      });
      addParseToken("hmmss", function(input, array, config) {
        var pos1 = input.length - 4, pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
        getParsingFlags(config).bigHour = true;
      });
      addParseToken("Hmm", function(input, array, config) {
        var pos = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos));
        array[MINUTE] = toInt(input.substr(pos));
      });
      addParseToken("Hmmss", function(input, array, config) {
        var pos1 = input.length - 4, pos2 = input.length - 2;
        array[HOUR] = toInt(input.substr(0, pos1));
        array[MINUTE] = toInt(input.substr(pos1, 2));
        array[SECOND] = toInt(input.substr(pos2));
      });
      function localeIsPM(input) {
        return (input + "").toLowerCase().charAt(0) === "p";
      }
      var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, getSetHour = makeGetSet("Hours", true);
      function localeMeridiem(hours2, minutes2, isLower) {
        if (hours2 > 11) {
          return isLower ? "pm" : "PM";
        } else {
          return isLower ? "am" : "AM";
        }
      }
      var baseConfig = {
        calendar: defaultCalendar,
        longDateFormat: defaultLongDateFormat,
        invalidDate: defaultInvalidDate,
        ordinal: defaultOrdinal,
        dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
        relativeTime: defaultRelativeTime,
        months: defaultLocaleMonths,
        monthsShort: defaultLocaleMonthsShort,
        week: defaultLocaleWeek,
        weekdays: defaultLocaleWeekdays,
        weekdaysMin: defaultLocaleWeekdaysMin,
        weekdaysShort: defaultLocaleWeekdaysShort,
        meridiemParse: defaultLocaleMeridiemParse
      };
      var locales = {}, localeFamilies = {}, globalLocale;
      function commonPrefix(arr1, arr2) {
        var i3, minl = Math.min(arr1.length, arr2.length);
        for (i3 = 0; i3 < minl; i3 += 1) {
          if (arr1[i3] !== arr2[i3]) {
            return i3;
          }
        }
        return minl;
      }
      function normalizeLocale(key) {
        return key ? key.toLowerCase().replace("_", "-") : key;
      }
      function chooseLocale(names) {
        var i3 = 0, j3, next, locale2, split;
        while (i3 < names.length) {
          split = normalizeLocale(names[i3]).split("-");
          j3 = split.length;
          next = normalizeLocale(names[i3 + 1]);
          next = next ? next.split("-") : null;
          while (j3 > 0) {
            locale2 = loadLocale(split.slice(0, j3).join("-"));
            if (locale2) {
              return locale2;
            }
            if (next && next.length >= j3 && commonPrefix(split, next) >= j3 - 1) {
              break;
            }
            j3--;
          }
          i3++;
        }
        return globalLocale;
      }
      function isLocaleNameSane(name) {
        return name.match("^[^/\\\\]*$") != null;
      }
      function loadLocale(name) {
        var oldLocale = null, aliasedRequire;
        if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name)) {
          try {
            oldLocale = globalLocale._abbr;
            aliasedRequire = require;
            aliasedRequire("./locale/" + name);
            getSetGlobalLocale(oldLocale);
          } catch (e3) {
            locales[name] = null;
          }
        }
        return locales[name];
      }
      function getSetGlobalLocale(key, values) {
        var data;
        if (key) {
          if (isUndefined2(values)) {
            data = getLocale2(key);
          } else {
            data = defineLocale(key, values);
          }
          if (data) {
            globalLocale = data;
          } else {
            if (typeof console !== "undefined" && console.warn) {
              console.warn(
                "Locale " + key + " not found. Did you forget to load it?"
              );
            }
          }
        }
        return globalLocale._abbr;
      }
      function defineLocale(name, config) {
        if (config !== null) {
          var locale2, parentConfig = baseConfig;
          config.abbr = name;
          if (locales[name] != null) {
            deprecateSimple(
              "defineLocaleOverride",
              "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."
            );
            parentConfig = locales[name]._config;
          } else if (config.parentLocale != null) {
            if (locales[config.parentLocale] != null) {
              parentConfig = locales[config.parentLocale]._config;
            } else {
              locale2 = loadLocale(config.parentLocale);
              if (locale2 != null) {
                parentConfig = locale2._config;
              } else {
                if (!localeFamilies[config.parentLocale]) {
                  localeFamilies[config.parentLocale] = [];
                }
                localeFamilies[config.parentLocale].push({
                  name,
                  config
                });
                return null;
              }
            }
          }
          locales[name] = new Locale2(mergeConfigs3(parentConfig, config));
          if (localeFamilies[name]) {
            localeFamilies[name].forEach(function(x2) {
              defineLocale(x2.name, x2.config);
            });
          }
          getSetGlobalLocale(name);
          return locales[name];
        } else {
          delete locales[name];
          return null;
        }
      }
      function updateLocale(name, config) {
        if (config != null) {
          var locale2, tmpLocale, parentConfig = baseConfig;
          if (locales[name] != null && locales[name].parentLocale != null) {
            locales[name].set(mergeConfigs3(locales[name]._config, config));
          } else {
            tmpLocale = loadLocale(name);
            if (tmpLocale != null) {
              parentConfig = tmpLocale._config;
            }
            config = mergeConfigs3(parentConfig, config);
            if (tmpLocale == null) {
              config.abbr = name;
            }
            locale2 = new Locale2(config);
            locale2.parentLocale = locales[name];
            locales[name] = locale2;
          }
          getSetGlobalLocale(name);
        } else {
          if (locales[name] != null) {
            if (locales[name].parentLocale != null) {
              locales[name] = locales[name].parentLocale;
              if (name === getSetGlobalLocale()) {
                getSetGlobalLocale(name);
              }
            } else if (locales[name] != null) {
              delete locales[name];
            }
          }
        }
        return locales[name];
      }
      function getLocale2(key) {
        var locale2;
        if (key && key._locale && key._locale._abbr) {
          key = key._locale._abbr;
        }
        if (!key) {
          return globalLocale;
        }
        if (!isArray2(key)) {
          locale2 = loadLocale(key);
          if (locale2) {
            return locale2;
          }
          key = [key];
        }
        return chooseLocale(key);
      }
      function listLocales() {
        return keys(locales);
      }
      function checkOverflow(m3) {
        var overflow, a3 = m3._a;
        if (a3 && getParsingFlags(m3).overflow === -2) {
          overflow = a3[MONTH] < 0 || a3[MONTH] > 11 ? MONTH : a3[DATE2] < 1 || a3[DATE2] > daysInMonth2(a3[YEAR], a3[MONTH]) ? DATE2 : a3[HOUR] < 0 || a3[HOUR] > 24 || a3[HOUR] === 24 && (a3[MINUTE] !== 0 || a3[SECOND] !== 0 || a3[MILLISECOND] !== 0) ? HOUR : a3[MINUTE] < 0 || a3[MINUTE] > 59 ? MINUTE : a3[SECOND] < 0 || a3[SECOND] > 59 ? SECOND : a3[MILLISECOND] < 0 || a3[MILLISECOND] > 999 ? MILLISECOND : -1;
          if (getParsingFlags(m3)._overflowDayOfYear && (overflow < YEAR || overflow > DATE2)) {
            overflow = DATE2;
          }
          if (getParsingFlags(m3)._overflowWeeks && overflow === -1) {
            overflow = WEEK;
          }
          if (getParsingFlags(m3)._overflowWeekday && overflow === -1) {
            overflow = WEEKDAY;
          }
          getParsingFlags(m3).overflow = overflow;
        }
        return m3;
      }
      var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [
        ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/],
        ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/],
        ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/],
        ["GGGG-[W]WW", /\d{4}-W\d\d/, false],
        ["YYYY-DDD", /\d{4}-\d{3}/],
        ["YYYY-MM", /\d{4}-\d\d/, false],
        ["YYYYYYMMDD", /[+-]\d{10}/],
        ["YYYYMMDD", /\d{8}/],
        ["GGGG[W]WWE", /\d{4}W\d{3}/],
        ["GGGG[W]WW", /\d{4}W\d{2}/, false],
        ["YYYYDDD", /\d{7}/],
        ["YYYYMM", /\d{6}/, false],
        ["YYYY", /\d{4}/, false]
      ], isoTimes = [
        ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/],
        ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/],
        ["HH:mm:ss", /\d\d:\d\d:\d\d/],
        ["HH:mm", /\d\d:\d\d/],
        ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/],
        ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/],
        ["HHmmss", /\d\d\d\d\d\d/],
        ["HHmm", /\d\d\d\d/],
        ["HH", /\d\d/]
      ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, rfc28222 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets2 = {
        UT: 0,
        GMT: 0,
        EDT: -4 * 60,
        EST: -5 * 60,
        CDT: -5 * 60,
        CST: -6 * 60,
        MDT: -6 * 60,
        MST: -7 * 60,
        PDT: -7 * 60,
        PST: -8 * 60
      };
      function configFromISO(config) {
        var i3, l4, string = config._i, match5 = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length;
        if (match5) {
          getParsingFlags(config).iso = true;
          for (i3 = 0, l4 = isoDatesLen; i3 < l4; i3++) {
            if (isoDates[i3][1].exec(match5[1])) {
              dateFormat = isoDates[i3][0];
              allowTime = isoDates[i3][2] !== false;
              break;
            }
          }
          if (dateFormat == null) {
            config._isValid = false;
            return;
          }
          if (match5[3]) {
            for (i3 = 0, l4 = isoTimesLen; i3 < l4; i3++) {
              if (isoTimes[i3][1].exec(match5[3])) {
                timeFormat = (match5[2] || " ") + isoTimes[i3][0];
                break;
              }
            }
            if (timeFormat == null) {
              config._isValid = false;
              return;
            }
          }
          if (!allowTime && timeFormat != null) {
            config._isValid = false;
            return;
          }
          if (match5[4]) {
            if (tzRegex.exec(match5[4])) {
              tzFormat = "Z";
            } else {
              config._isValid = false;
              return;
            }
          }
          config._f = dateFormat + (timeFormat || "") + (tzFormat || "");
          configFromStringAndFormat(config);
        } else {
          config._isValid = false;
        }
      }
      function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
        var result = [
          untruncateYear2(yearStr),
          defaultLocaleMonthsShort.indexOf(monthStr),
          parseInt(dayStr, 10),
          parseInt(hourStr, 10),
          parseInt(minuteStr, 10)
        ];
        if (secondStr) {
          result.push(parseInt(secondStr, 10));
        }
        return result;
      }
      function untruncateYear2(yearStr) {
        var year = parseInt(yearStr, 10);
        if (year <= 49) {
          return 2e3 + year;
        } else if (year <= 999) {
          return 1900 + year;
        }
        return year;
      }
      function preprocessRFC28222(s4) {
        return s4.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, "");
      }
      function checkWeekday(weekdayStr, parsedInput, config) {
        if (weekdayStr) {
          var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date(
            parsedInput[0],
            parsedInput[1],
            parsedInput[2]
          ).getDay();
          if (weekdayProvided !== weekdayActual) {
            getParsingFlags(config).weekdayMismatch = true;
            config._isValid = false;
            return false;
          }
        }
        return true;
      }
      function calculateOffset(obsOffset, militaryOffset, numOffset) {
        if (obsOffset) {
          return obsOffsets2[obsOffset];
        } else if (militaryOffset) {
          return 0;
        } else {
          var hm = parseInt(numOffset, 10), m3 = hm % 100, h3 = (hm - m3) / 100;
          return h3 * 60 + m3;
        }
      }
      function configFromRFC2822(config) {
        var match5 = rfc28222.exec(preprocessRFC28222(config._i)), parsedArray;
        if (match5) {
          parsedArray = extractFromRFC2822Strings(
            match5[4],
            match5[3],
            match5[2],
            match5[5],
            match5[6],
            match5[7]
          );
          if (!checkWeekday(match5[1], parsedArray, config)) {
            return;
          }
          config._a = parsedArray;
          config._tzm = calculateOffset(match5[8], match5[9], match5[10]);
          config._d = createUTCDate.apply(null, config._a);
          config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
          getParsingFlags(config).rfc2822 = true;
        } else {
          config._isValid = false;
        }
      }
      function configFromString(config) {
        var matched = aspNetJsonRegex.exec(config._i);
        if (matched !== null) {
          config._d = new Date(+matched[1]);
          return;
        }
        configFromISO(config);
        if (config._isValid === false) {
          delete config._isValid;
        } else {
          return;
        }
        configFromRFC2822(config);
        if (config._isValid === false) {
          delete config._isValid;
        } else {
          return;
        }
        if (config._strict) {
          config._isValid = false;
        } else {
          hooks.createFromInputFallback(config);
        }
      }
      hooks.createFromInputFallback = deprecate(
        "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",
        function(config) {
          config._d = new Date(config._i + (config._useUTC ? " UTC" : ""));
        }
      );
      function defaults2(a3, b3, c4) {
        if (a3 != null) {
          return a3;
        }
        if (b3 != null) {
          return b3;
        }
        return c4;
      }
      function currentDateArray(config) {
        var nowValue = new Date(hooks.now());
        if (config._useUTC) {
          return [
            nowValue.getUTCFullYear(),
            nowValue.getUTCMonth(),
            nowValue.getUTCDate()
          ];
        }
        return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
      }
      function configFromArray(config) {
        var i3, date2, input = [], currentDate, expectedWeekday, yearToUse;
        if (config._d) {
          return;
        }
        currentDate = currentDateArray(config);
        if (config._w && config._a[DATE2] == null && config._a[MONTH] == null) {
          dayOfYearFromWeekInfo(config);
        }
        if (config._dayOfYear != null) {
          yearToUse = defaults2(config._a[YEAR], currentDate[YEAR]);
          if (config._dayOfYear > daysInYear2(yearToUse) || config._dayOfYear === 0) {
            getParsingFlags(config)._overflowDayOfYear = true;
          }
          date2 = createUTCDate(yearToUse, 0, config._dayOfYear);
          config._a[MONTH] = date2.getUTCMonth();
          config._a[DATE2] = date2.getUTCDate();
        }
        for (i3 = 0; i3 < 3 && config._a[i3] == null; ++i3) {
          config._a[i3] = input[i3] = currentDate[i3];
        }
        for (; i3 < 7; i3++) {
          config._a[i3] = input[i3] = config._a[i3] == null ? i3 === 2 ? 1 : 0 : config._a[i3];
        }
        if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) {
          config._nextDay = true;
          config._a[HOUR] = 0;
        }
        config._d = (config._useUTC ? createUTCDate : createDate).apply(
          null,
          input
        );
        expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
        if (config._tzm != null) {
          config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
        }
        if (config._nextDay) {
          config._a[HOUR] = 24;
        }
        if (config._w && typeof config._w.d !== "undefined" && config._w.d !== expectedWeekday) {
          getParsingFlags(config).weekdayMismatch = true;
        }
      }
      function dayOfYearFromWeekInfo(config) {
        var w2, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
        w2 = config._w;
        if (w2.GG != null || w2.W != null || w2.E != null) {
          dow = 1;
          doy = 4;
          weekYear = defaults2(
            w2.GG,
            config._a[YEAR],
            weekOfYear(createLocal(), 1, 4).year
          );
          week = defaults2(w2.W, 1);
          weekday = defaults2(w2.E, 1);
          if (weekday < 1 || weekday > 7) {
            weekdayOverflow = true;
          }
        } else {
          dow = config._locale._week.dow;
          doy = config._locale._week.doy;
          curWeek = weekOfYear(createLocal(), dow, doy);
          weekYear = defaults2(w2.gg, config._a[YEAR], curWeek.year);
          week = defaults2(w2.w, curWeek.week);
          if (w2.d != null) {
            weekday = w2.d;
            if (weekday < 0 || weekday > 6) {
              weekdayOverflow = true;
            }
          } else if (w2.e != null) {
            weekday = w2.e + dow;
            if (w2.e < 0 || w2.e > 6) {
              weekdayOverflow = true;
            }
          } else {
            weekday = dow;
          }
        }
        if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
          getParsingFlags(config)._overflowWeeks = true;
        } else if (weekdayOverflow != null) {
          getParsingFlags(config)._overflowWeekday = true;
        } else {
          temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
          config._a[YEAR] = temp.year;
          config._dayOfYear = temp.dayOfYear;
        }
      }
      hooks.ISO_8601 = function() {
      };
      hooks.RFC_2822 = function() {
      };
      function configFromStringAndFormat(config) {
        if (config._f === hooks.ISO_8601) {
          configFromISO(config);
          return;
        }
        if (config._f === hooks.RFC_2822) {
          configFromRFC2822(config);
          return;
        }
        config._a = [];
        getParsingFlags(config).empty = true;
        var string = "" + config._i, i3, parsedInput, tokens2, token2, skipped, stringLength = string.length, totalParsedInputLength = 0, era, tokenLen;
        tokens2 = expandFormat(config._f, config._locale).match(formattingTokens) || [];
        tokenLen = tokens2.length;
        for (i3 = 0; i3 < tokenLen; i3++) {
          token2 = tokens2[i3];
          parsedInput = (string.match(getParseRegexForToken(token2, config)) || [])[0];
          if (parsedInput) {
            skipped = string.substr(0, string.indexOf(parsedInput));
            if (skipped.length > 0) {
              getParsingFlags(config).unusedInput.push(skipped);
            }
            string = string.slice(
              string.indexOf(parsedInput) + parsedInput.length
            );
            totalParsedInputLength += parsedInput.length;
          }
          if (formatTokenFunctions[token2]) {
            if (parsedInput) {
              getParsingFlags(config).empty = false;
            } else {
              getParsingFlags(config).unusedTokens.push(token2);
            }
            addTimeToArrayFromToken(token2, parsedInput, config);
          } else if (config._strict && !parsedInput) {
            getParsingFlags(config).unusedTokens.push(token2);
          }
        }
        getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
        if (string.length > 0) {
          getParsingFlags(config).unusedInput.push(string);
        }
        if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) {
          getParsingFlags(config).bigHour = void 0;
        }
        getParsingFlags(config).parsedDateParts = config._a.slice(0);
        getParsingFlags(config).meridiem = config._meridiem;
        config._a[HOUR] = meridiemFixWrap(
          config._locale,
          config._a[HOUR],
          config._meridiem
        );
        era = getParsingFlags(config).era;
        if (era !== null) {
          config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
        }
        configFromArray(config);
        checkOverflow(config);
      }
      function meridiemFixWrap(locale2, hour, meridiem2) {
        var isPm;
        if (meridiem2 == null) {
          return hour;
        }
        if (locale2.meridiemHour != null) {
          return locale2.meridiemHour(hour, meridiem2);
        } else if (locale2.isPM != null) {
          isPm = locale2.isPM(meridiem2);
          if (isPm && hour < 12) {
            hour += 12;
          }
          if (!isPm && hour === 12) {
            hour = 0;
          }
          return hour;
        } else {
          return hour;
        }
      }
      function configFromStringAndArray(config) {
        var tempConfig, bestMoment, scoreToBeat, i3, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config._f.length;
        if (configfLen === 0) {
          getParsingFlags(config).invalidFormat = true;
          config._d = new Date(NaN);
          return;
        }
        for (i3 = 0; i3 < configfLen; i3++) {
          currentScore = 0;
          validFormatFound = false;
          tempConfig = copyConfig({}, config);
          if (config._useUTC != null) {
            tempConfig._useUTC = config._useUTC;
          }
          tempConfig._f = config._f[i3];
          configFromStringAndFormat(tempConfig);
          if (isValid2(tempConfig)) {
            validFormatFound = true;
          }
          currentScore += getParsingFlags(tempConfig).charsLeftOver;
          currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
          getParsingFlags(tempConfig).score = currentScore;
          if (!bestFormatIsValid) {
            if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) {
              scoreToBeat = currentScore;
              bestMoment = tempConfig;
              if (validFormatFound) {
                bestFormatIsValid = true;
              }
            }
          } else {
            if (currentScore < scoreToBeat) {
              scoreToBeat = currentScore;
              bestMoment = tempConfig;
            }
          }
        }
        extend(config, bestMoment || tempConfig);
      }
      function configFromObject(config) {
        if (config._d) {
          return;
        }
        var i3 = normalizeObjectUnits(config._i), dayOrDate = i3.day === void 0 ? i3.date : i3.day;
        config._a = map(
          [i3.year, i3.month, dayOrDate, i3.hour, i3.minute, i3.second, i3.millisecond],
          function(obj) {
            return obj && parseInt(obj, 10);
          }
        );
        configFromArray(config);
      }
      function createFromConfig(config) {
        var res = new Moment(checkOverflow(prepareConfig(config)));
        if (res._nextDay) {
          res.add(1, "d");
          res._nextDay = void 0;
        }
        return res;
      }
      function prepareConfig(config) {
        var input = config._i, format2 = config._f;
        config._locale = config._locale || getLocale2(config._l);
        if (input === null || format2 === void 0 && input === "") {
          return createInvalid({ nullInput: true });
        }
        if (typeof input === "string") {
          config._i = input = config._locale.preparse(input);
        }
        if (isMoment(input)) {
          return new Moment(checkOverflow(input));
        } else if (isDate2(input)) {
          config._d = input;
        } else if (isArray2(format2)) {
          configFromStringAndArray(config);
        } else if (format2) {
          configFromStringAndFormat(config);
        } else {
          configFromInput(config);
        }
        if (!isValid2(config)) {
          config._d = null;
        }
        return config;
      }
      function configFromInput(config) {
        var input = config._i;
        if (isUndefined2(input)) {
          config._d = new Date(hooks.now());
        } else if (isDate2(input)) {
          config._d = new Date(input.valueOf());
        } else if (typeof input === "string") {
          configFromString(config);
        } else if (isArray2(input)) {
          config._a = map(input.slice(0), function(obj) {
            return parseInt(obj, 10);
          });
          configFromArray(config);
        } else if (isObject2(input)) {
          configFromObject(config);
        } else if (isNumber3(input)) {
          config._d = new Date(input);
        } else {
          hooks.createFromInputFallback(config);
        }
      }
      function createLocalOrUTC(input, format2, locale2, strict2, isUTC) {
        var c4 = {};
        if (format2 === true || format2 === false) {
          strict2 = format2;
          format2 = void 0;
        }
        if (locale2 === true || locale2 === false) {
          strict2 = locale2;
          locale2 = void 0;
        }
        if (isObject2(input) && isObjectEmpty(input) || isArray2(input) && input.length === 0) {
          input = void 0;
        }
        c4._isAMomentObject = true;
        c4._useUTC = c4._isUTC = isUTC;
        c4._l = locale2;
        c4._i = input;
        c4._f = format2;
        c4._strict = strict2;
        return createFromConfig(c4);
      }
      function createLocal(input, format2, locale2, strict2) {
        return createLocalOrUTC(input, format2, locale2, strict2, false);
      }
      var prototypeMin = deprecate(
        "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",
        function() {
          var other = createLocal.apply(null, arguments);
          if (this.isValid() && other.isValid()) {
            return other < this ? this : other;
          } else {
            return createInvalid();
          }
        }
      ), prototypeMax = deprecate(
        "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",
        function() {
          var other = createLocal.apply(null, arguments);
          if (this.isValid() && other.isValid()) {
            return other > this ? this : other;
          } else {
            return createInvalid();
          }
        }
      );
      function pickBy(fn, moments) {
        var res, i3;
        if (moments.length === 1 && isArray2(moments[0])) {
          moments = moments[0];
        }
        if (!moments.length) {
          return createLocal();
        }
        res = moments[0];
        for (i3 = 1; i3 < moments.length; ++i3) {
          if (!moments[i3].isValid() || moments[i3][fn](res)) {
            res = moments[i3];
          }
        }
        return res;
      }
      function min2() {
        var args = [].slice.call(arguments, 0);
        return pickBy("isBefore", args);
      }
      function max2() {
        var args = [].slice.call(arguments, 0);
        return pickBy("isAfter", args);
      }
      var now3 = function() {
        return Date.now ? Date.now() : +new Date();
      };
      var ordering = [
        "year",
        "quarter",
        "month",
        "week",
        "day",
        "hour",
        "minute",
        "second",
        "millisecond"
      ];
      function isDurationValid(m3) {
        var key, unitHasDecimal = false, i3, orderLen = ordering.length;
        for (key in m3) {
          if (hasOwnProp(m3, key) && !(indexOf.call(ordering, key) !== -1 && (m3[key] == null || !isNaN(m3[key])))) {
            return false;
          }
        }
        for (i3 = 0; i3 < orderLen; ++i3) {
          if (m3[ordering[i3]]) {
            if (unitHasDecimal) {
              return false;
            }
            if (parseFloat(m3[ordering[i3]]) !== toInt(m3[ordering[i3]])) {
              unitHasDecimal = true;
            }
          }
        }
        return true;
      }
      function isValid$1() {
        return this._isValid;
      }
      function createInvalid$1() {
        return createDuration(NaN);
      }
      function Duration2(duration) {
        var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months3 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0;
        this._isValid = isDurationValid(normalizedInput);
        this._milliseconds = +milliseconds2 + seconds2 * 1e3 + // 1000
        minutes2 * 6e4 + // 1000 * 60
        hours2 * 1e3 * 60 * 60;
        this._days = +days2 + weeks2 * 7;
        this._months = +months3 + quarters * 3 + years2 * 12;
        this._data = {};
        this._locale = getLocale2();
        this._bubble();
      }
      function isDuration(obj) {
        return obj instanceof Duration2;
      }
      function absRound(number) {
        if (number < 0) {
          return Math.round(-1 * number) * -1;
        } else {
          return Math.round(number);
        }
      }
      function compareArrays(array1, array2, dontConvert) {
        var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i3;
        for (i3 = 0; i3 < len; i3++) {
          if (dontConvert && array1[i3] !== array2[i3] || !dontConvert && toInt(array1[i3]) !== toInt(array2[i3])) {
            diffs++;
          }
        }
        return diffs + lengthDiff;
      }
      function offset5(token2, separator) {
        addFormatToken(token2, 0, 0, function() {
          var offset6 = this.utcOffset(), sign2 = "+";
          if (offset6 < 0) {
            offset6 = -offset6;
            sign2 = "-";
          }
          return sign2 + zeroFill(~~(offset6 / 60), 2) + separator + zeroFill(~~offset6 % 60, 2);
        });
      }
      offset5("Z", ":");
      offset5("ZZ", "");
      addRegexToken("Z", matchShortOffset);
      addRegexToken("ZZ", matchShortOffset);
      addParseToken(["Z", "ZZ"], function(input, array, config) {
        config._useUTC = true;
        config._tzm = offsetFromString(matchShortOffset, input);
      });
      var chunkOffset = /([\+\-]|\d\d)/gi;
      function offsetFromString(matcher, string) {
        var matches = (string || "").match(matcher), chunk, parts, minutes2;
        if (matches === null) {
          return null;
        }
        chunk = matches[matches.length - 1] || [];
        parts = (chunk + "").match(chunkOffset) || ["-", 0, 0];
        minutes2 = +(parts[1] * 60) + toInt(parts[2]);
        return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2;
      }
      function cloneWithOffset(input, model) {
        var res, diff2;
        if (model._isUTC) {
          res = model.clone();
          diff2 = (isMoment(input) || isDate2(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
          res._d.setTime(res._d.valueOf() + diff2);
          hooks.updateOffset(res, false);
          return res;
        } else {
          return createLocal(input).local();
        }
      }
      function getDateOffset(m3) {
        return -Math.round(m3._d.getTimezoneOffset());
      }
      hooks.updateOffset = function() {
      };
      function getSetOffset(input, keepLocalTime, keepMinutes) {
        var offset6 = this._offset || 0, localAdjust;
        if (!this.isValid()) {
          return input != null ? this : NaN;
        }
        if (input != null) {
          if (typeof input === "string") {
            input = offsetFromString(matchShortOffset, input);
            if (input === null) {
              return this;
            }
          } else if (Math.abs(input) < 16 && !keepMinutes) {
            input = input * 60;
          }
          if (!this._isUTC && keepLocalTime) {
            localAdjust = getDateOffset(this);
          }
          this._offset = input;
          this._isUTC = true;
          if (localAdjust != null) {
            this.add(localAdjust, "m");
          }
          if (offset6 !== input) {
            if (!keepLocalTime || this._changeInProgress) {
              addSubtract(
                this,
                createDuration(input - offset6, "m"),
                1,
                false
              );
            } else if (!this._changeInProgress) {
              this._changeInProgress = true;
              hooks.updateOffset(this, true);
              this._changeInProgress = null;
            }
          }
          return this;
        } else {
          return this._isUTC ? offset6 : getDateOffset(this);
        }
      }
      function getSetZone(input, keepLocalTime) {
        if (input != null) {
          if (typeof input !== "string") {
            input = -input;
          }
          this.utcOffset(input, keepLocalTime);
          return this;
        } else {
          return -this.utcOffset();
        }
      }
      function setOffsetToUTC(keepLocalTime) {
        return this.utcOffset(0, keepLocalTime);
      }
      function setOffsetToLocal(keepLocalTime) {
        if (this._isUTC) {
          this.utcOffset(0, keepLocalTime);
          this._isUTC = false;
          if (keepLocalTime) {
            this.subtract(getDateOffset(this), "m");
          }
        }
        return this;
      }
      function setOffsetToParsedOffset() {
        if (this._tzm != null) {
          this.utcOffset(this._tzm, false, true);
        } else if (typeof this._i === "string") {
          var tZone = offsetFromString(matchOffset, this._i);
          if (tZone != null) {
            this.utcOffset(tZone);
          } else {
            this.utcOffset(0, true);
          }
        }
        return this;
      }
      function hasAlignedHourOffset(input) {
        if (!this.isValid()) {
          return false;
        }
        input = input ? createLocal(input).utcOffset() : 0;
        return (this.utcOffset() - input) % 60 === 0;
      }
      function isDaylightSavingTime() {
        return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
      }
      function isDaylightSavingTimeShifted() {
        if (!isUndefined2(this._isDSTShifted)) {
          return this._isDSTShifted;
        }
        var c4 = {}, other;
        copyConfig(c4, this);
        c4 = prepareConfig(c4);
        if (c4._a) {
          other = c4._isUTC ? createUTC(c4._a) : createLocal(c4._a);
          this._isDSTShifted = this.isValid() && compareArrays(c4._a, other.toArray()) > 0;
        } else {
          this._isDSTShifted = false;
        }
        return this._isDSTShifted;
      }
      function isLocal() {
        return this.isValid() ? !this._isUTC : false;
      }
      function isUtcOffset() {
        return this.isValid() ? this._isUTC : false;
      }
      function isUtc() {
        return this.isValid() ? this._isUTC && this._offset === 0 : false;
      }
      var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
      function createDuration(input, key) {
        var duration = input, match5 = null, sign2, ret, diffRes;
        if (isDuration(input)) {
          duration = {
            ms: input._milliseconds,
            d: input._days,
            M: input._months
          };
        } else if (isNumber3(input) || !isNaN(+input)) {
          duration = {};
          if (key) {
            duration[key] = +input;
          } else {
            duration.milliseconds = +input;
          }
        } else if (match5 = aspNetRegex.exec(input)) {
          sign2 = match5[1] === "-" ? -1 : 1;
          duration = {
            y: 0,
            d: toInt(match5[DATE2]) * sign2,
            h: toInt(match5[HOUR]) * sign2,
            m: toInt(match5[MINUTE]) * sign2,
            s: toInt(match5[SECOND]) * sign2,
            ms: toInt(absRound(match5[MILLISECOND] * 1e3)) * sign2
            // the millisecond decimal point is included in the match
          };
        } else if (match5 = isoRegex.exec(input)) {
          sign2 = match5[1] === "-" ? -1 : 1;
          duration = {
            y: parseIso(match5[2], sign2),
            M: parseIso(match5[3], sign2),
            w: parseIso(match5[4], sign2),
            d: parseIso(match5[5], sign2),
            h: parseIso(match5[6], sign2),
            m: parseIso(match5[7], sign2),
            s: parseIso(match5[8], sign2)
          };
        } else if (duration == null) {
          duration = {};
        } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) {
          diffRes = momentsDifference(
            createLocal(duration.from),
            createLocal(duration.to)
          );
          duration = {};
          duration.ms = diffRes.milliseconds;
          duration.M = diffRes.months;
        }
        ret = new Duration2(duration);
        if (isDuration(input) && hasOwnProp(input, "_locale")) {
          ret._locale = input._locale;
        }
        if (isDuration(input) && hasOwnProp(input, "_isValid")) {
          ret._isValid = input._isValid;
        }
        return ret;
      }
      createDuration.fn = Duration2.prototype;
      createDuration.invalid = createInvalid$1;
      function parseIso(inp, sign2) {
        var res = inp && parseFloat(inp.replace(",", "."));
        return (isNaN(res) ? 0 : res) * sign2;
      }
      function positiveMomentsDifference(base, other) {
        var res = {};
        res.months = other.month() - base.month() + (other.year() - base.year()) * 12;
        if (base.clone().add(res.months, "M").isAfter(other)) {
          --res.months;
        }
        res.milliseconds = +other - +base.clone().add(res.months, "M");
        return res;
      }
      function momentsDifference(base, other) {
        var res;
        if (!(base.isValid() && other.isValid())) {
          return { milliseconds: 0, months: 0 };
        }
        other = cloneWithOffset(other, base);
        if (base.isBefore(other)) {
          res = positiveMomentsDifference(base, other);
        } else {
          res = positiveMomentsDifference(other, base);
          res.milliseconds = -res.milliseconds;
          res.months = -res.months;
        }
        return res;
      }
      function createAdder(direction, name) {
        return function(val2, period) {
          var dur, tmp;
          if (period !== null && !isNaN(+period)) {
            deprecateSimple(
              name,
              "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."
            );
            tmp = val2;
            val2 = period;
            period = tmp;
          }
          dur = createDuration(val2, period);
          addSubtract(this, dur, direction);
          return this;
        };
      }
      function addSubtract(mom, duration, isAdding, updateOffset) {
        var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months3 = absRound(duration._months);
        if (!mom.isValid()) {
          return;
        }
        updateOffset = updateOffset == null ? true : updateOffset;
        if (months3) {
          setMonth(mom, get4(mom, "Month") + months3 * isAdding);
        }
        if (days2) {
          set$1(mom, "Date", get4(mom, "Date") + days2 * isAdding);
        }
        if (milliseconds2) {
          mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding);
        }
        if (updateOffset) {
          hooks.updateOffset(mom, days2 || months3);
        }
      }
      var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract");
      function isString2(input) {
        return typeof input === "string" || input instanceof String;
      }
      function isMomentInput(input) {
        return isMoment(input) || isDate2(input) || isString2(input) || isNumber3(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0;
      }
      function isMomentInputObject(input) {
        var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [
          "years",
          "year",
          "y",
          "months",
          "month",
          "M",
          "days",
          "day",
          "d",
          "dates",
          "date",
          "D",
          "hours",
          "hour",
          "h",
          "minutes",
          "minute",
          "m",
          "seconds",
          "second",
          "s",
          "milliseconds",
          "millisecond",
          "ms"
        ], i3, property, propertyLen = properties.length;
        for (i3 = 0; i3 < propertyLen; i3 += 1) {
          property = properties[i3];
          propertyTest = propertyTest || hasOwnProp(input, property);
        }
        return objectTest && propertyTest;
      }
      function isNumberOrStringArray(input) {
        var arrayTest = isArray2(input), dataTypeTest = false;
        if (arrayTest) {
          dataTypeTest = input.filter(function(item) {
            return !isNumber3(item) && isString2(input);
          }).length === 0;
        }
        return arrayTest && dataTypeTest;
      }
      function isCalendarSpec(input) {
        var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [
          "sameDay",
          "nextDay",
          "lastDay",
          "nextWeek",
          "lastWeek",
          "sameElse"
        ], i3, property;
        for (i3 = 0; i3 < properties.length; i3 += 1) {
          property = properties[i3];
          propertyTest = propertyTest || hasOwnProp(input, property);
        }
        return objectTest && propertyTest;
      }
      function getCalendarFormat(myMoment, now4) {
        var diff2 = myMoment.diff(now4, "days", true);
        return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse";
      }
      function calendar$1(time2, formats) {
        if (arguments.length === 1) {
          if (!arguments[0]) {
            time2 = void 0;
            formats = void 0;
          } else if (isMomentInput(arguments[0])) {
            time2 = arguments[0];
            formats = void 0;
          } else if (isCalendarSpec(arguments[0])) {
            formats = arguments[0];
            time2 = void 0;
          }
        }
        var now4 = time2 || createLocal(), sod = cloneWithOffset(now4, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now4) : formats[format2]);
        return this.format(
          output || this.localeData().calendar(format2, this, createLocal(now4))
        );
      }
      function clone3() {
        return new Moment(this);
      }
      function isAfter(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
          return false;
        }
        units = normalizeUnits(units) || "millisecond";
        if (units === "millisecond") {
          return this.valueOf() > localInput.valueOf();
        } else {
          return localInput.valueOf() < this.clone().startOf(units).valueOf();
        }
      }
      function isBefore(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input);
        if (!(this.isValid() && localInput.isValid())) {
          return false;
        }
        units = normalizeUnits(units) || "millisecond";
        if (units === "millisecond") {
          return this.valueOf() < localInput.valueOf();
        } else {
          return this.clone().endOf(units).valueOf() < localInput.valueOf();
        }
      }
      function isBetween(from2, to2, units, inclusivity) {
        var localFrom = isMoment(from2) ? from2 : createLocal(from2), localTo = isMoment(to2) ? to2 : createLocal(to2);
        if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
          return false;
        }
        inclusivity = inclusivity || "()";
        return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
      }
      function isSame(input, units) {
        var localInput = isMoment(input) ? input : createLocal(input), inputMs;
        if (!(this.isValid() && localInput.isValid())) {
          return false;
        }
        units = normalizeUnits(units) || "millisecond";
        if (units === "millisecond") {
          return this.valueOf() === localInput.valueOf();
        } else {
          inputMs = localInput.valueOf();
          return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
        }
      }
      function isSameOrAfter(input, units) {
        return this.isSame(input, units) || this.isAfter(input, units);
      }
      function isSameOrBefore(input, units) {
        return this.isSame(input, units) || this.isBefore(input, units);
      }
      function diff(input, units, asFloat) {
        var that, zoneDelta, output;
        if (!this.isValid()) {
          return NaN;
        }
        that = cloneWithOffset(input, this);
        if (!that.isValid()) {
          return NaN;
        }
        zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
        units = normalizeUnits(units);
        switch (units) {
          case "year":
            output = monthDiff(this, that) / 12;
            break;
          case "month":
            output = monthDiff(this, that);
            break;
          case "quarter":
            output = monthDiff(this, that) / 3;
            break;
          case "second":
            output = (this - that) / 1e3;
            break;
          case "minute":
            output = (this - that) / 6e4;
            break;
          case "hour":
            output = (this - that) / 36e5;
            break;
          case "day":
            output = (this - that - zoneDelta) / 864e5;
            break;
          case "week":
            output = (this - that - zoneDelta) / 6048e5;
            break;
          default:
            output = this - that;
        }
        return asFloat ? output : absFloor(output);
      }
      function monthDiff(a3, b3) {
        if (a3.date() < b3.date()) {
          return -monthDiff(b3, a3);
        }
        var wholeMonthDiff = (b3.year() - a3.year()) * 12 + (b3.month() - a3.month()), anchor = a3.clone().add(wholeMonthDiff, "months"), anchor2, adjust;
        if (b3 - anchor < 0) {
          anchor2 = a3.clone().add(wholeMonthDiff - 1, "months");
          adjust = (b3 - anchor) / (anchor - anchor2);
        } else {
          anchor2 = a3.clone().add(wholeMonthDiff + 1, "months");
          adjust = (b3 - anchor) / (anchor2 - anchor);
        }
        return -(wholeMonthDiff + adjust) || 0;
      }
      hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ";
      hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]";
      function toString() {
        return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
      }
      function toISOString(keepOffset) {
        if (!this.isValid()) {
          return null;
        }
        var utc = keepOffset !== true, m3 = utc ? this.clone().utc() : this;
        if (m3.year() < 0 || m3.year() > 9999) {
          return formatMoment(
            m3,
            utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"
          );
        }
        if (isFunction2(Date.prototype.toISOString)) {
          if (utc) {
            return this.toDate().toISOString();
          } else {
            return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m3, "Z"));
          }
        }
        return formatMoment(
          m3,
          utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ"
        );
      }
      function inspect() {
        if (!this.isValid()) {
          return "moment.invalid(/* " + this._i + " */)";
        }
        var func = "moment", zone = "", prefix, year, datetime, suffix;
        if (!this.isLocal()) {
          func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone";
          zone = "Z";
        }
        prefix = "[" + func + '("]';
        year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY";
        datetime = "-MM-DD[T]HH:mm:ss.SSS";
        suffix = zone + '[")]';
        return this.format(prefix + year + datetime + suffix);
      }
      function format(inputString) {
        if (!inputString) {
          inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
        }
        var output = formatMoment(this, inputString);
        return this.localeData().postformat(output);
      }
      function from(time2, withoutSuffix) {
        if (this.isValid() && (isMoment(time2) && time2.isValid() || createLocal(time2).isValid())) {
          return createDuration({ to: this, from: time2 }).locale(this.locale()).humanize(!withoutSuffix);
        } else {
          return this.localeData().invalidDate();
        }
      }
      function fromNow(withoutSuffix) {
        return this.from(createLocal(), withoutSuffix);
      }
      function to(time2, withoutSuffix) {
        if (this.isValid() && (isMoment(time2) && time2.isValid() || createLocal(time2).isValid())) {
          return createDuration({ from: this, to: time2 }).locale(this.locale()).humanize(!withoutSuffix);
        } else {
          return this.localeData().invalidDate();
        }
      }
      function toNow(withoutSuffix) {
        return this.to(createLocal(), withoutSuffix);
      }
      function locale(key) {
        var newLocaleData;
        if (key === void 0) {
          return this._locale._abbr;
        } else {
          newLocaleData = getLocale2(key);
          if (newLocaleData != null) {
            this._locale = newLocaleData;
          }
          return this;
        }
      }
      var lang = deprecate(
        "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",
        function(key) {
          if (key === void 0) {
            return this.localeData();
          } else {
            return this.locale(key);
          }
        }
      );
      function localeData() {
        return this._locale;
      }
      var MS_PER_SECOND = 1e3, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
      function mod$1(dividend, divisor) {
        return (dividend % divisor + divisor) % divisor;
      }
      function localStartOfDate(y2, m3, d3) {
        if (y2 < 100 && y2 >= 0) {
          return new Date(y2 + 400, m3, d3) - MS_PER_400_YEARS;
        } else {
          return new Date(y2, m3, d3).valueOf();
        }
      }
      function utcStartOfDate(y2, m3, d3) {
        if (y2 < 100 && y2 >= 0) {
          return Date.UTC(y2 + 400, m3, d3) - MS_PER_400_YEARS;
        } else {
          return Date.UTC(y2, m3, d3);
        }
      }
      function startOf(units) {
        var time2, startOfDate;
        units = normalizeUnits(units);
        if (units === void 0 || units === "millisecond" || !this.isValid()) {
          return this;
        }
        startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
        switch (units) {
          case "year":
            time2 = startOfDate(this.year(), 0, 1);
            break;
          case "quarter":
            time2 = startOfDate(
              this.year(),
              this.month() - this.month() % 3,
              1
            );
            break;
          case "month":
            time2 = startOfDate(this.year(), this.month(), 1);
            break;
          case "week":
            time2 = startOfDate(
              this.year(),
              this.month(),
              this.date() - this.weekday()
            );
            break;
          case "isoWeek":
            time2 = startOfDate(
              this.year(),
              this.month(),
              this.date() - (this.isoWeekday() - 1)
            );
            break;
          case "day":
          case "date":
            time2 = startOfDate(this.year(), this.month(), this.date());
            break;
          case "hour":
            time2 = this._d.valueOf();
            time2 -= mod$1(
              time2 + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
              MS_PER_HOUR
            );
            break;
          case "minute":
            time2 = this._d.valueOf();
            time2 -= mod$1(time2, MS_PER_MINUTE);
            break;
          case "second":
            time2 = this._d.valueOf();
            time2 -= mod$1(time2, MS_PER_SECOND);
            break;
        }
        this._d.setTime(time2);
        hooks.updateOffset(this, true);
        return this;
      }
      function endOf(units) {
        var time2, startOfDate;
        units = normalizeUnits(units);
        if (units === void 0 || units === "millisecond" || !this.isValid()) {
          return this;
        }
        startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
        switch (units) {
          case "year":
            time2 = startOfDate(this.year() + 1, 0, 1) - 1;
            break;
          case "quarter":
            time2 = startOfDate(
              this.year(),
              this.month() - this.month() % 3 + 3,
              1
            ) - 1;
            break;
          case "month":
            time2 = startOfDate(this.year(), this.month() + 1, 1) - 1;
            break;
          case "week":
            time2 = startOfDate(
              this.year(),
              this.month(),
              this.date() - this.weekday() + 7
            ) - 1;
            break;
          case "isoWeek":
            time2 = startOfDate(
              this.year(),
              this.month(),
              this.date() - (this.isoWeekday() - 1) + 7
            ) - 1;
            break;
          case "day":
          case "date":
            time2 = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
            break;
          case "hour":
            time2 = this._d.valueOf();
            time2 += MS_PER_HOUR - mod$1(
              time2 + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
              MS_PER_HOUR
            ) - 1;
            break;
          case "minute":
            time2 = this._d.valueOf();
            time2 += MS_PER_MINUTE - mod$1(time2, MS_PER_MINUTE) - 1;
            break;
          case "second":
            time2 = this._d.valueOf();
            time2 += MS_PER_SECOND - mod$1(time2, MS_PER_SECOND) - 1;
            break;
        }
        this._d.setTime(time2);
        hooks.updateOffset(this, true);
        return this;
      }
      function valueOf() {
        return this._d.valueOf() - (this._offset || 0) * 6e4;
      }
      function unix() {
        return Math.floor(this.valueOf() / 1e3);
      }
      function toDate2() {
        return new Date(this.valueOf());
      }
      function toArray2() {
        var m3 = this;
        return [
          m3.year(),
          m3.month(),
          m3.date(),
          m3.hour(),
          m3.minute(),
          m3.second(),
          m3.millisecond()
        ];
      }
      function toObject() {
        var m3 = this;
        return {
          years: m3.year(),
          months: m3.month(),
          date: m3.date(),
          hours: m3.hours(),
          minutes: m3.minutes(),
          seconds: m3.seconds(),
          milliseconds: m3.milliseconds()
        };
      }
      function toJSON() {
        return this.isValid() ? this.toISOString() : null;
      }
      function isValid$2() {
        return isValid2(this);
      }
      function parsingFlags() {
        return extend({}, getParsingFlags(this));
      }
      function invalidAt() {
        return getParsingFlags(this).overflow;
      }
      function creationData() {
        return {
          input: this._i,
          format: this._f,
          locale: this._locale,
          isUTC: this._isUTC,
          strict: this._strict
        };
      }
      addFormatToken("N", 0, 0, "eraAbbr");
      addFormatToken("NN", 0, 0, "eraAbbr");
      addFormatToken("NNN", 0, 0, "eraAbbr");
      addFormatToken("NNNN", 0, 0, "eraName");
      addFormatToken("NNNNN", 0, 0, "eraNarrow");
      addFormatToken("y", ["y", 1], "yo", "eraYear");
      addFormatToken("y", ["yy", 2], 0, "eraYear");
      addFormatToken("y", ["yyy", 3], 0, "eraYear");
      addFormatToken("y", ["yyyy", 4], 0, "eraYear");
      addRegexToken("N", matchEraAbbr);
      addRegexToken("NN", matchEraAbbr);
      addRegexToken("NNN", matchEraAbbr);
      addRegexToken("NNNN", matchEraName);
      addRegexToken("NNNNN", matchEraNarrow);
      addParseToken(
        ["N", "NN", "NNN", "NNNN", "NNNNN"],
        function(input, array, config, token2) {
          var era = config._locale.erasParse(input, token2, config._strict);
          if (era) {
            getParsingFlags(config).era = era;
          } else {
            getParsingFlags(config).invalidEra = input;
          }
        }
      );
      addRegexToken("y", matchUnsigned);
      addRegexToken("yy", matchUnsigned);
      addRegexToken("yyy", matchUnsigned);
      addRegexToken("yyyy", matchUnsigned);
      addRegexToken("yo", matchEraYearOrdinal);
      addParseToken(["y", "yy", "yyy", "yyyy"], YEAR);
      addParseToken(["yo"], function(input, array, config, token2) {
        var match5;
        if (config._locale._eraYearOrdinalRegex) {
          match5 = input.match(config._locale._eraYearOrdinalRegex);
        }
        if (config._locale.eraYearOrdinalParse) {
          array[YEAR] = config._locale.eraYearOrdinalParse(input, match5);
        } else {
          array[YEAR] = parseInt(input, 10);
        }
      });
      function localeEras(m3, format2) {
        var i3, l4, date2, eras2 = this._eras || getLocale2("en")._eras;
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          switch (typeof eras2[i3].since) {
            case "string":
              date2 = hooks(eras2[i3].since).startOf("day");
              eras2[i3].since = date2.valueOf();
              break;
          }
          switch (typeof eras2[i3].until) {
            case "undefined":
              eras2[i3].until = Infinity;
              break;
            case "string":
              date2 = hooks(eras2[i3].until).startOf("day").valueOf();
              eras2[i3].until = date2.valueOf();
              break;
          }
        }
        return eras2;
      }
      function localeErasParse(eraName, format2, strict2) {
        var i3, l4, eras2 = this.eras(), name, abbr, narrow;
        eraName = eraName.toUpperCase();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          name = eras2[i3].name.toUpperCase();
          abbr = eras2[i3].abbr.toUpperCase();
          narrow = eras2[i3].narrow.toUpperCase();
          if (strict2) {
            switch (format2) {
              case "N":
              case "NN":
              case "NNN":
                if (abbr === eraName) {
                  return eras2[i3];
                }
                break;
              case "NNNN":
                if (name === eraName) {
                  return eras2[i3];
                }
                break;
              case "NNNNN":
                if (narrow === eraName) {
                  return eras2[i3];
                }
                break;
            }
          } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
            return eras2[i3];
          }
        }
      }
      function localeErasConvertYear(era, year) {
        var dir = era.since <= era.until ? 1 : -1;
        if (year === void 0) {
          return hooks(era.since).year();
        } else {
          return hooks(era.since).year() + (year - era.offset) * dir;
        }
      }
      function getEraName() {
        var i3, l4, val2, eras2 = this.localeData().eras();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          val2 = this.clone().startOf("day").valueOf();
          if (eras2[i3].since <= val2 && val2 <= eras2[i3].until) {
            return eras2[i3].name;
          }
          if (eras2[i3].until <= val2 && val2 <= eras2[i3].since) {
            return eras2[i3].name;
          }
        }
        return "";
      }
      function getEraNarrow() {
        var i3, l4, val2, eras2 = this.localeData().eras();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          val2 = this.clone().startOf("day").valueOf();
          if (eras2[i3].since <= val2 && val2 <= eras2[i3].until) {
            return eras2[i3].narrow;
          }
          if (eras2[i3].until <= val2 && val2 <= eras2[i3].since) {
            return eras2[i3].narrow;
          }
        }
        return "";
      }
      function getEraAbbr() {
        var i3, l4, val2, eras2 = this.localeData().eras();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          val2 = this.clone().startOf("day").valueOf();
          if (eras2[i3].since <= val2 && val2 <= eras2[i3].until) {
            return eras2[i3].abbr;
          }
          if (eras2[i3].until <= val2 && val2 <= eras2[i3].since) {
            return eras2[i3].abbr;
          }
        }
        return "";
      }
      function getEraYear() {
        var i3, l4, dir, val2, eras2 = this.localeData().eras();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          dir = eras2[i3].since <= eras2[i3].until ? 1 : -1;
          val2 = this.clone().startOf("day").valueOf();
          if (eras2[i3].since <= val2 && val2 <= eras2[i3].until || eras2[i3].until <= val2 && val2 <= eras2[i3].since) {
            return (this.year() - hooks(eras2[i3].since).year()) * dir + eras2[i3].offset;
          }
        }
        return this.year();
      }
      function erasNameRegex(isStrict) {
        if (!hasOwnProp(this, "_erasNameRegex")) {
          computeErasParse.call(this);
        }
        return isStrict ? this._erasNameRegex : this._erasRegex;
      }
      function erasAbbrRegex(isStrict) {
        if (!hasOwnProp(this, "_erasAbbrRegex")) {
          computeErasParse.call(this);
        }
        return isStrict ? this._erasAbbrRegex : this._erasRegex;
      }
      function erasNarrowRegex(isStrict) {
        if (!hasOwnProp(this, "_erasNarrowRegex")) {
          computeErasParse.call(this);
        }
        return isStrict ? this._erasNarrowRegex : this._erasRegex;
      }
      function matchEraAbbr(isStrict, locale2) {
        return locale2.erasAbbrRegex(isStrict);
      }
      function matchEraName(isStrict, locale2) {
        return locale2.erasNameRegex(isStrict);
      }
      function matchEraNarrow(isStrict, locale2) {
        return locale2.erasNarrowRegex(isStrict);
      }
      function matchEraYearOrdinal(isStrict, locale2) {
        return locale2._eraYearOrdinalRegex || matchUnsigned;
      }
      function computeErasParse() {
        var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i3, l4, eras2 = this.eras();
        for (i3 = 0, l4 = eras2.length; i3 < l4; ++i3) {
          namePieces.push(regexEscape(eras2[i3].name));
          abbrPieces.push(regexEscape(eras2[i3].abbr));
          narrowPieces.push(regexEscape(eras2[i3].narrow));
          mixedPieces.push(regexEscape(eras2[i3].name));
          mixedPieces.push(regexEscape(eras2[i3].abbr));
          mixedPieces.push(regexEscape(eras2[i3].narrow));
        }
        this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
        this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i");
        this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i");
        this._erasNarrowRegex = new RegExp(
          "^(" + narrowPieces.join("|") + ")",
          "i"
        );
      }
      addFormatToken(0, ["gg", 2], 0, function() {
        return this.weekYear() % 100;
      });
      addFormatToken(0, ["GG", 2], 0, function() {
        return this.isoWeekYear() % 100;
      });
      function addWeekYearFormatToken(token2, getter) {
        addFormatToken(0, [token2, token2.length], 0, getter);
      }
      addWeekYearFormatToken("gggg", "weekYear");
      addWeekYearFormatToken("ggggg", "weekYear");
      addWeekYearFormatToken("GGGG", "isoWeekYear");
      addWeekYearFormatToken("GGGGG", "isoWeekYear");
      addUnitAlias("weekYear", "gg");
      addUnitAlias("isoWeekYear", "GG");
      addUnitPriority("weekYear", 1);
      addUnitPriority("isoWeekYear", 1);
      addRegexToken("G", matchSigned);
      addRegexToken("g", matchSigned);
      addRegexToken("GG", match1to2, match2);
      addRegexToken("gg", match1to2, match2);
      addRegexToken("GGGG", match1to4, match4);
      addRegexToken("gggg", match1to4, match4);
      addRegexToken("GGGGG", match1to6, match6);
      addRegexToken("ggggg", match1to6, match6);
      addWeekParseToken(
        ["gggg", "ggggg", "GGGG", "GGGGG"],
        function(input, week, config, token2) {
          week[token2.substr(0, 2)] = toInt(input);
        }
      );
      addWeekParseToken(["gg", "GG"], function(input, week, config, token2) {
        week[token2] = hooks.parseTwoDigitYear(input);
      });
      function getSetWeekYear(input) {
        return getSetWeekYearHelper.call(
          this,
          input,
          this.week(),
          this.weekday(),
          this.localeData()._week.dow,
          this.localeData()._week.doy
        );
      }
      function getSetISOWeekYear(input) {
        return getSetWeekYearHelper.call(
          this,
          input,
          this.isoWeek(),
          this.isoWeekday(),
          1,
          4
        );
      }
      function getISOWeeksInYear() {
        return weeksInYear(this.year(), 1, 4);
      }
      function getISOWeeksInISOWeekYear() {
        return weeksInYear(this.isoWeekYear(), 1, 4);
      }
      function getWeeksInYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
      }
      function getWeeksInWeekYear() {
        var weekInfo = this.localeData()._week;
        return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
      }
      function getSetWeekYearHelper(input, week, weekday, dow, doy) {
        var weeksTarget;
        if (input == null) {
          return weekOfYear(this, dow, doy).year;
        } else {
          weeksTarget = weeksInYear(input, dow, doy);
          if (week > weeksTarget) {
            week = weeksTarget;
          }
          return setWeekAll.call(this, input, week, weekday, dow, doy);
        }
      }
      function setWeekAll(weekYear, week, weekday, dow, doy) {
        var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date2 = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
        this.year(date2.getUTCFullYear());
        this.month(date2.getUTCMonth());
        this.date(date2.getUTCDate());
        return this;
      }
      addFormatToken("Q", 0, "Qo", "quarter");
      addUnitAlias("quarter", "Q");
      addUnitPriority("quarter", 7);
      addRegexToken("Q", match1);
      addParseToken("Q", function(input, array) {
        array[MONTH] = (toInt(input) - 1) * 3;
      });
      function getSetQuarter(input) {
        return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
      }
      addFormatToken("D", ["DD", 2], "Do", "date");
      addUnitAlias("date", "D");
      addUnitPriority("date", 9);
      addRegexToken("D", match1to2);
      addRegexToken("DD", match1to2, match2);
      addRegexToken("Do", function(isStrict, locale2) {
        return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient;
      });
      addParseToken(["D", "DD"], DATE2);
      addParseToken("Do", function(input, array) {
        array[DATE2] = toInt(input.match(match1to2)[0]);
      });
      var getSetDayOfMonth = makeGetSet("Date", true);
      addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear");
      addUnitAlias("dayOfYear", "DDD");
      addUnitPriority("dayOfYear", 4);
      addRegexToken("DDD", match1to3);
      addRegexToken("DDDD", match3);
      addParseToken(["DDD", "DDDD"], function(input, array, config) {
        config._dayOfYear = toInt(input);
      });
      function getSetDayOfYear(input) {
        var dayOfYear = Math.round(
          (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5
        ) + 1;
        return input == null ? dayOfYear : this.add(input - dayOfYear, "d");
      }
      addFormatToken("m", ["mm", 2], 0, "minute");
      addUnitAlias("minute", "m");
      addUnitPriority("minute", 14);
      addRegexToken("m", match1to2);
      addRegexToken("mm", match1to2, match2);
      addParseToken(["m", "mm"], MINUTE);
      var getSetMinute = makeGetSet("Minutes", false);
      addFormatToken("s", ["ss", 2], 0, "second");
      addUnitAlias("second", "s");
      addUnitPriority("second", 15);
      addRegexToken("s", match1to2);
      addRegexToken("ss", match1to2, match2);
      addParseToken(["s", "ss"], SECOND);
      var getSetSecond = makeGetSet("Seconds", false);
      addFormatToken("S", 0, 0, function() {
        return ~~(this.millisecond() / 100);
      });
      addFormatToken(0, ["SS", 2], 0, function() {
        return ~~(this.millisecond() / 10);
      });
      addFormatToken(0, ["SSS", 3], 0, "millisecond");
      addFormatToken(0, ["SSSS", 4], 0, function() {
        return this.millisecond() * 10;
      });
      addFormatToken(0, ["SSSSS", 5], 0, function() {
        return this.millisecond() * 100;
      });
      addFormatToken(0, ["SSSSSS", 6], 0, function() {
        return this.millisecond() * 1e3;
      });
      addFormatToken(0, ["SSSSSSS", 7], 0, function() {
        return this.millisecond() * 1e4;
      });
      addFormatToken(0, ["SSSSSSSS", 8], 0, function() {
        return this.millisecond() * 1e5;
      });
      addFormatToken(0, ["SSSSSSSSS", 9], 0, function() {
        return this.millisecond() * 1e6;
      });
      addUnitAlias("millisecond", "ms");
      addUnitPriority("millisecond", 16);
      addRegexToken("S", match1to3, match1);
      addRegexToken("SS", match1to3, match2);
      addRegexToken("SSS", match1to3, match3);
      var token, getSetMillisecond;
      for (token = "SSSS"; token.length <= 9; token += "S") {
        addRegexToken(token, matchUnsigned);
      }
      function parseMs(input, array) {
        array[MILLISECOND] = toInt(("0." + input) * 1e3);
      }
      for (token = "S"; token.length <= 9; token += "S") {
        addParseToken(token, parseMs);
      }
      getSetMillisecond = makeGetSet("Milliseconds", false);
      addFormatToken("z", 0, 0, "zoneAbbr");
      addFormatToken("zz", 0, 0, "zoneName");
      function getZoneAbbr() {
        return this._isUTC ? "UTC" : "";
      }
      function getZoneName() {
        return this._isUTC ? "Coordinated Universal Time" : "";
      }
      var proto = Moment.prototype;
      proto.add = add;
      proto.calendar = calendar$1;
      proto.clone = clone3;
      proto.diff = diff;
      proto.endOf = endOf;
      proto.format = format;
      proto.from = from;
      proto.fromNow = fromNow;
      proto.to = to;
      proto.toNow = toNow;
      proto.get = stringGet;
      proto.invalidAt = invalidAt;
      proto.isAfter = isAfter;
      proto.isBefore = isBefore;
      proto.isBetween = isBetween;
      proto.isSame = isSame;
      proto.isSameOrAfter = isSameOrAfter;
      proto.isSameOrBefore = isSameOrBefore;
      proto.isValid = isValid$2;
      proto.lang = lang;
      proto.locale = locale;
      proto.localeData = localeData;
      proto.max = prototypeMax;
      proto.min = prototypeMin;
      proto.parsingFlags = parsingFlags;
      proto.set = stringSet;
      proto.startOf = startOf;
      proto.subtract = subtract;
      proto.toArray = toArray2;
      proto.toObject = toObject;
      proto.toDate = toDate2;
      proto.toISOString = toISOString;
      proto.inspect = inspect;
      if (typeof Symbol !== "undefined" && Symbol.for != null) {
        proto[Symbol.for("nodejs.util.inspect.custom")] = function() {
          return "Moment<" + this.format() + ">";
        };
      }
      proto.toJSON = toJSON;
      proto.toString = toString;
      proto.unix = unix;
      proto.valueOf = valueOf;
      proto.creationData = creationData;
      proto.eraName = getEraName;
      proto.eraNarrow = getEraNarrow;
      proto.eraAbbr = getEraAbbr;
      proto.eraYear = getEraYear;
      proto.year = getSetYear;
      proto.isLeapYear = getIsLeapYear;
      proto.weekYear = getSetWeekYear;
      proto.isoWeekYear = getSetISOWeekYear;
      proto.quarter = proto.quarters = getSetQuarter;
      proto.month = getSetMonth;
      proto.daysInMonth = getDaysInMonth;
      proto.week = proto.weeks = getSetWeek;
      proto.isoWeek = proto.isoWeeks = getSetISOWeek;
      proto.weeksInYear = getWeeksInYear;
      proto.weeksInWeekYear = getWeeksInWeekYear;
      proto.isoWeeksInYear = getISOWeeksInYear;
      proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
      proto.date = getSetDayOfMonth;
      proto.day = proto.days = getSetDayOfWeek;
      proto.weekday = getSetLocaleDayOfWeek;
      proto.isoWeekday = getSetISODayOfWeek;
      proto.dayOfYear = getSetDayOfYear;
      proto.hour = proto.hours = getSetHour;
      proto.minute = proto.minutes = getSetMinute;
      proto.second = proto.seconds = getSetSecond;
      proto.millisecond = proto.milliseconds = getSetMillisecond;
      proto.utcOffset = getSetOffset;
      proto.utc = setOffsetToUTC;
      proto.local = setOffsetToLocal;
      proto.parseZone = setOffsetToParsedOffset;
      proto.hasAlignedHourOffset = hasAlignedHourOffset;
      proto.isDST = isDaylightSavingTime;
      proto.isLocal = isLocal;
      proto.isUtcOffset = isUtcOffset;
      proto.isUtc = isUtc;
      proto.isUTC = isUtc;
      proto.zoneAbbr = getZoneAbbr;
      proto.zoneName = getZoneName;
      proto.dates = deprecate(
        "dates accessor is deprecated. Use date instead.",
        getSetDayOfMonth
      );
      proto.months = deprecate(
        "months accessor is deprecated. Use month instead",
        getSetMonth
      );
      proto.years = deprecate(
        "years accessor is deprecated. Use year instead",
        getSetYear
      );
      proto.zone = deprecate(
        "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",
        getSetZone
      );
      proto.isDSTShifted = deprecate(
        "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",
        isDaylightSavingTimeShifted
      );
      function createUnix(input) {
        return createLocal(input * 1e3);
      }
      function createInZone() {
        return createLocal.apply(null, arguments).parseZone();
      }
      function preParsePostFormat(string) {
        return string;
      }
      var proto$1 = Locale2.prototype;
      proto$1.calendar = calendar;
      proto$1.longDateFormat = longDateFormat;
      proto$1.invalidDate = invalidDate;
      proto$1.ordinal = ordinal;
      proto$1.preparse = preParsePostFormat;
      proto$1.postformat = preParsePostFormat;
      proto$1.relativeTime = relativeTime;
      proto$1.pastFuture = pastFuture;
      proto$1.set = set;
      proto$1.eras = localeEras;
      proto$1.erasParse = localeErasParse;
      proto$1.erasConvertYear = localeErasConvertYear;
      proto$1.erasAbbrRegex = erasAbbrRegex;
      proto$1.erasNameRegex = erasNameRegex;
      proto$1.erasNarrowRegex = erasNarrowRegex;
      proto$1.months = localeMonths;
      proto$1.monthsShort = localeMonthsShort;
      proto$1.monthsParse = localeMonthsParse;
      proto$1.monthsRegex = monthsRegex;
      proto$1.monthsShortRegex = monthsShortRegex;
      proto$1.week = localeWeek;
      proto$1.firstDayOfYear = localeFirstDayOfYear;
      proto$1.firstDayOfWeek = localeFirstDayOfWeek;
      proto$1.weekdays = localeWeekdays;
      proto$1.weekdaysMin = localeWeekdaysMin;
      proto$1.weekdaysShort = localeWeekdaysShort;
      proto$1.weekdaysParse = localeWeekdaysParse;
      proto$1.weekdaysRegex = weekdaysRegex;
      proto$1.weekdaysShortRegex = weekdaysShortRegex;
      proto$1.weekdaysMinRegex = weekdaysMinRegex;
      proto$1.isPM = localeIsPM;
      proto$1.meridiem = localeMeridiem;
      function get$1(format2, index2, field, setter) {
        var locale2 = getLocale2(), utc = createUTC().set(setter, index2);
        return locale2[field](utc, format2);
      }
      function listMonthsImpl(format2, index2, field) {
        if (isNumber3(format2)) {
          index2 = format2;
          format2 = void 0;
        }
        format2 = format2 || "";
        if (index2 != null) {
          return get$1(format2, index2, field, "month");
        }
        var i3, out = [];
        for (i3 = 0; i3 < 12; i3++) {
          out[i3] = get$1(format2, i3, field, "month");
        }
        return out;
      }
      function listWeekdaysImpl(localeSorted, format2, index2, field) {
        if (typeof localeSorted === "boolean") {
          if (isNumber3(format2)) {
            index2 = format2;
            format2 = void 0;
          }
          format2 = format2 || "";
        } else {
          format2 = localeSorted;
          index2 = format2;
          localeSorted = false;
          if (isNumber3(format2)) {
            index2 = format2;
            format2 = void 0;
          }
          format2 = format2 || "";
        }
        var locale2 = getLocale2(), shift4 = localeSorted ? locale2._week.dow : 0, i3, out = [];
        if (index2 != null) {
          return get$1(format2, (index2 + shift4) % 7, field, "day");
        }
        for (i3 = 0; i3 < 7; i3++) {
          out[i3] = get$1(format2, (i3 + shift4) % 7, field, "day");
        }
        return out;
      }
      function listMonths(format2, index2) {
        return listMonthsImpl(format2, index2, "months");
      }
      function listMonthsShort(format2, index2) {
        return listMonthsImpl(format2, index2, "monthsShort");
      }
      function listWeekdays(localeSorted, format2, index2) {
        return listWeekdaysImpl(localeSorted, format2, index2, "weekdays");
      }
      function listWeekdaysShort(localeSorted, format2, index2) {
        return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysShort");
      }
      function listWeekdaysMin(localeSorted, format2, index2) {
        return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysMin");
      }
      getSetGlobalLocale("en", {
        eras: [
          {
            since: "0001-01-01",
            until: Infinity,
            offset: 1,
            name: "Anno Domini",
            narrow: "AD",
            abbr: "AD"
          },
          {
            since: "0000-12-31",
            until: -Infinity,
            offset: 1,
            name: "Before Christ",
            narrow: "BC",
            abbr: "BC"
          }
        ],
        dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
        ordinal: function(number) {
          var b3 = number % 10, output = toInt(number % 100 / 10) === 1 ? "th" : b3 === 1 ? "st" : b3 === 2 ? "nd" : b3 === 3 ? "rd" : "th";
          return number + output;
        }
      });
      hooks.lang = deprecate(
        "moment.lang is deprecated. Use moment.locale instead.",
        getSetGlobalLocale
      );
      hooks.langData = deprecate(
        "moment.langData is deprecated. Use moment.localeData instead.",
        getLocale2
      );
      var mathAbs = Math.abs;
      function abs() {
        var data = this._data;
        this._milliseconds = mathAbs(this._milliseconds);
        this._days = mathAbs(this._days);
        this._months = mathAbs(this._months);
        data.milliseconds = mathAbs(data.milliseconds);
        data.seconds = mathAbs(data.seconds);
        data.minutes = mathAbs(data.minutes);
        data.hours = mathAbs(data.hours);
        data.months = mathAbs(data.months);
        data.years = mathAbs(data.years);
        return this;
      }
      function addSubtract$1(duration, input, value, direction) {
        var other = createDuration(input, value);
        duration._milliseconds += direction * other._milliseconds;
        duration._days += direction * other._days;
        duration._months += direction * other._months;
        return duration._bubble();
      }
      function add$1(input, value) {
        return addSubtract$1(this, input, value, 1);
      }
      function subtract$1(input, value) {
        return addSubtract$1(this, input, value, -1);
      }
      function absCeil(number) {
        if (number < 0) {
          return Math.floor(number);
        } else {
          return Math.ceil(number);
        }
      }
      function bubble() {
        var milliseconds2 = this._milliseconds, days2 = this._days, months3 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays;
        if (!(milliseconds2 >= 0 && days2 >= 0 && months3 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months3 <= 0)) {
          milliseconds2 += absCeil(monthsToDays(months3) + days2) * 864e5;
          days2 = 0;
          months3 = 0;
        }
        data.milliseconds = milliseconds2 % 1e3;
        seconds2 = absFloor(milliseconds2 / 1e3);
        data.seconds = seconds2 % 60;
        minutes2 = absFloor(seconds2 / 60);
        data.minutes = minutes2 % 60;
        hours2 = absFloor(minutes2 / 60);
        data.hours = hours2 % 24;
        days2 += absFloor(hours2 / 24);
        monthsFromDays = absFloor(daysToMonths(days2));
        months3 += monthsFromDays;
        days2 -= absCeil(monthsToDays(monthsFromDays));
        years2 = absFloor(months3 / 12);
        months3 %= 12;
        data.days = days2;
        data.months = months3;
        data.years = years2;
        return this;
      }
      function daysToMonths(days2) {
        return days2 * 4800 / 146097;
      }
      function monthsToDays(months3) {
        return months3 * 146097 / 4800;
      }
      function as(units) {
        if (!this.isValid()) {
          return NaN;
        }
        var days2, months3, milliseconds2 = this._milliseconds;
        units = normalizeUnits(units);
        if (units === "month" || units === "quarter" || units === "year") {
          days2 = this._days + milliseconds2 / 864e5;
          months3 = this._months + daysToMonths(days2);
          switch (units) {
            case "month":
              return months3;
            case "quarter":
              return months3 / 3;
            case "year":
              return months3 / 12;
          }
        } else {
          days2 = this._days + Math.round(monthsToDays(this._months));
          switch (units) {
            case "week":
              return days2 / 7 + milliseconds2 / 6048e5;
            case "day":
              return days2 + milliseconds2 / 864e5;
            case "hour":
              return days2 * 24 + milliseconds2 / 36e5;
            case "minute":
              return days2 * 1440 + milliseconds2 / 6e4;
            case "second":
              return days2 * 86400 + milliseconds2 / 1e3;
            case "millisecond":
              return Math.floor(days2 * 864e5) + milliseconds2;
            default:
              throw new Error("Unknown unit " + units);
          }
        }
      }
      function valueOf$1() {
        if (!this.isValid()) {
          return NaN;
        }
        return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6;
      }
      function makeAs(alias) {
        return function() {
          return this.as(alias);
        };
      }
      var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y");
      function clone$1() {
        return createDuration(this);
      }
      function get$2(units) {
        units = normalizeUnits(units);
        return this.isValid() ? this[units + "s"]() : NaN;
      }
      function makeGetter(name) {
        return function() {
          return this.isValid() ? this._data[name] : NaN;
        };
      }
      var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months2 = makeGetter("months"), years = makeGetter("years");
      function weeks() {
        return absFloor(this.days() / 7);
      }
      var round2 = Math.round, thresholds = {
        ss: 44,
        // a few seconds to seconds
        s: 45,
        // seconds to minute
        m: 45,
        // minutes to hour
        h: 22,
        // hours to day
        d: 26,
        // days to month/week
        w: null,
        // weeks to month
        M: 11
        // months to year
      };
      function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale2) {
        return locale2.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
      }
      function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) {
        var duration = createDuration(posNegDuration).abs(), seconds2 = round2(duration.as("s")), minutes2 = round2(duration.as("m")), hours2 = round2(duration.as("h")), days2 = round2(duration.as("d")), months3 = round2(duration.as("M")), weeks2 = round2(duration.as("w")), years2 = round2(duration.as("y")), a3 = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2];
        if (thresholds2.w != null) {
          a3 = a3 || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2];
        }
        a3 = a3 || months3 <= 1 && ["M"] || months3 < thresholds2.M && ["MM", months3] || years2 <= 1 && ["y"] || ["yy", years2];
        a3[2] = withoutSuffix;
        a3[3] = +posNegDuration > 0;
        a3[4] = locale2;
        return substituteTimeAgo.apply(null, a3);
      }
      function getSetRelativeTimeRounding(roundingFunction) {
        if (roundingFunction === void 0) {
          return round2;
        }
        if (typeof roundingFunction === "function") {
          round2 = roundingFunction;
          return true;
        }
        return false;
      }
      function getSetRelativeTimeThreshold(threshold, limit2) {
        if (thresholds[threshold] === void 0) {
          return false;
        }
        if (limit2 === void 0) {
          return thresholds[threshold];
        }
        thresholds[threshold] = limit2;
        if (threshold === "s") {
          thresholds.ss = limit2 - 1;
        }
        return true;
      }
      function humanize(argWithSuffix, argThresholds) {
        if (!this.isValid()) {
          return this.localeData().invalidDate();
        }
        var withSuffix = false, th = thresholds, locale2, output;
        if (typeof argWithSuffix === "object") {
          argThresholds = argWithSuffix;
          argWithSuffix = false;
        }
        if (typeof argWithSuffix === "boolean") {
          withSuffix = argWithSuffix;
        }
        if (typeof argThresholds === "object") {
          th = Object.assign({}, thresholds, argThresholds);
          if (argThresholds.s != null && argThresholds.ss == null) {
            th.ss = argThresholds.s - 1;
          }
        }
        locale2 = this.localeData();
        output = relativeTime$1(this, !withSuffix, th, locale2);
        if (withSuffix) {
          output = locale2.pastFuture(+this, output);
        }
        return locale2.postformat(output);
      }
      var abs$1 = Math.abs;
      function sign(x2) {
        return (x2 > 0) - (x2 < 0) || +x2;
      }
      function toISOString$1() {
        if (!this.isValid()) {
          return this.localeData().invalidDate();
        }
        var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months3 = abs$1(this._months), minutes2, hours2, years2, s4, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign;
        if (!total) {
          return "P0D";
        }
        minutes2 = absFloor(seconds2 / 60);
        hours2 = absFloor(minutes2 / 60);
        seconds2 %= 60;
        minutes2 %= 60;
        years2 = absFloor(months3 / 12);
        months3 %= 12;
        s4 = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : "";
        totalSign = total < 0 ? "-" : "";
        ymSign = sign(this._months) !== sign(total) ? "-" : "";
        daysSign = sign(this._days) !== sign(total) ? "-" : "";
        hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : "";
        return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months3 ? ymSign + months3 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s4 + "S" : "");
      }
      var proto$2 = Duration2.prototype;
      proto$2.isValid = isValid$1;
      proto$2.abs = abs;
      proto$2.add = add$1;
      proto$2.subtract = subtract$1;
      proto$2.as = as;
      proto$2.asMilliseconds = asMilliseconds;
      proto$2.asSeconds = asSeconds;
      proto$2.asMinutes = asMinutes;
      proto$2.asHours = asHours;
      proto$2.asDays = asDays;
      proto$2.asWeeks = asWeeks;
      proto$2.asMonths = asMonths;
      proto$2.asQuarters = asQuarters;
      proto$2.asYears = asYears;
      proto$2.valueOf = valueOf$1;
      proto$2._bubble = bubble;
      proto$2.clone = clone$1;
      proto$2.get = get$2;
      proto$2.milliseconds = milliseconds;
      proto$2.seconds = seconds;
      proto$2.minutes = minutes;
      proto$2.hours = hours;
      proto$2.days = days;
      proto$2.weeks = weeks;
      proto$2.months = months2;
      proto$2.years = years;
      proto$2.humanize = humanize;
      proto$2.toISOString = toISOString$1;
      proto$2.toString = toISOString$1;
      proto$2.toJSON = toISOString$1;
      proto$2.locale = locale;
      proto$2.localeData = localeData;
      proto$2.toIsoString = deprecate(
        "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",
        toISOString$1
      );
      proto$2.lang = lang;
      addFormatToken("X", 0, 0, "unix");
      addFormatToken("x", 0, 0, "valueOf");
      addRegexToken("x", matchSigned);
      addRegexToken("X", matchTimestamp);
      addParseToken("X", function(input, array, config) {
        config._d = new Date(parseFloat(input) * 1e3);
      });
      addParseToken("x", function(input, array, config) {
        config._d = new Date(toInt(input));
      });
      hooks.version = "2.29.4";
      setHookCallback(createLocal);
      hooks.fn = proto;
      hooks.min = min2;
      hooks.max = max2;
      hooks.now = now3;
      hooks.utc = createUTC;
      hooks.unix = createUnix;
      hooks.months = listMonths;
      hooks.isDate = isDate2;
      hooks.locale = getSetGlobalLocale;
      hooks.invalid = createInvalid;
      hooks.duration = createDuration;
      hooks.isMoment = isMoment;
      hooks.weekdays = listWeekdays;
      hooks.parseZone = createInZone;
      hooks.localeData = getLocale2;
      hooks.isDuration = isDuration;
      hooks.monthsShort = listMonthsShort;
      hooks.weekdaysMin = listWeekdaysMin;
      hooks.defineLocale = defineLocale;
      hooks.updateLocale = updateLocale;
      hooks.locales = listLocales;
      hooks.weekdaysShort = listWeekdaysShort;
      hooks.normalizeUnits = normalizeUnits;
      hooks.relativeTimeRounding = getSetRelativeTimeRounding;
      hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
      hooks.calendarFormat = getCalendarFormat;
      hooks.prototype = proto;
      hooks.HTML5_FMT = {
        DATETIME_LOCAL: "YYYY-MM-DDTHH:mm",
        // <input type="datetime-local" />
        DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss",
        // <input type="datetime-local" step="1" />
        DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS",
        // <input type="datetime-local" step="0.001" />
        DATE: "YYYY-MM-DD",
        // <input type="date" />
        TIME: "HH:mm",
        // <input type="time" />
        TIME_SECONDS: "HH:mm:ss",
        // <input type="time" step="1" />
        TIME_MS: "HH:mm:ss.SSS",
        // <input type="time" step="0.001" />
        WEEK: "GGGG-[W]WW",
        // <input type="week" />
        MONTH: "YYYY-MM"
        // <input type="month" />
      };
      return hooks;
    });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/V2ChatStreamRequestCitationMode.js
var require_V2ChatStreamRequestCitationMode = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/V2ChatStreamRequestCitationMode.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatStreamRequestCitationMode = void 0;
    exports.V2ChatStreamRequestCitationMode = {
      Fast: "FAST",
      Accurate: "ACCURATE",
      Off: "OFF"
    };
  }
});

// node_modules/cohere-ai/api/resources/v2/types/V2ChatRequestCitationMode.js
var require_V2ChatRequestCitationMode = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/V2ChatRequestCitationMode.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatRequestCitationMode = void 0;
    exports.V2ChatRequestCitationMode = {
      Fast: "FAST",
      Accurate: "ACCURATE",
      Off: "OFF"
    };
  }
});

// node_modules/cohere-ai/api/resources/v2/types/TextContent.js
var require_TextContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/TextContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Content.js
var require_Content = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Content.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/UserMessageContent.js
var require_UserMessageContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/UserMessageContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/UserMessage.js
var require_UserMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/UserMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolCall2Function.js
var require_ToolCall2Function = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolCall2Function.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolCall2.js
var require_ToolCall2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolCall2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolSource.js
var require_ToolSource = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolSource.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/DocumentSource.js
var require_DocumentSource = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/DocumentSource.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Source.js
var require_Source = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Source.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Citation.js
var require_Citation = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Citation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/AssistantMessageContentItem.js
var require_AssistantMessageContentItem = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/AssistantMessageContentItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/AssistantMessageContent.js
var require_AssistantMessageContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/AssistantMessageContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/AssistantMessage.js
var require_AssistantMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/AssistantMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/SystemMessageContentItem.js
var require_SystemMessageContentItem = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/SystemMessageContentItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/SystemMessageContent.js
var require_SystemMessageContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/SystemMessageContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/SystemMessage.js
var require_SystemMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/SystemMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolContent.js
var require_ToolContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolMessage2ToolContentItem.js
var require_ToolMessage2ToolContentItem = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolMessage2ToolContentItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ToolMessage2.js
var require_ToolMessage2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ToolMessage2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessage2.js
var require_ChatMessage2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessage2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessages.js
var require_ChatMessages = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessages.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Tool2Function.js
var require_Tool2Function = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Tool2Function.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Tool2.js
var require_Tool2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Tool2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatFinishReason.js
var require_ChatFinishReason = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatFinishReason.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatFinishReason = void 0;
    exports.ChatFinishReason = {
      Complete: "complete",
      StopSequence: "stop_sequence",
      MaxTokens: "max_tokens",
      ToolCall: "tool_call",
      Error: "error",
      ContentBlocked: "content_blocked",
      ErrorLimit: "error_limit"
    };
  }
});

// node_modules/cohere-ai/api/resources/v2/types/AssistantMessageResponseContentItem.js
var require_AssistantMessageResponseContentItem = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/AssistantMessageResponseContentItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/AssistantMessageResponse.js
var require_AssistantMessageResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/AssistantMessageResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/UsageBilledUnits.js
var require_UsageBilledUnits = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/UsageBilledUnits.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/UsageTokens.js
var require_UsageTokens = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/UsageTokens.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/Usage.js
var require_Usage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/Usage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/NonStreamedChatResponse2.js
var require_NonStreamedChatResponse2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/NonStreamedChatResponse2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatStreamEventType.js
var require_ChatStreamEventType = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatStreamEventType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEventDeltaMessage.js
var require_ChatMessageStartEventDeltaMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEventDeltaMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEventDelta.js
var require_ChatMessageStartEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEvent.js
var require_ChatMessageStartEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessageStartEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDeltaMessageContent.js
var require_ChatContentStartEventDeltaMessageContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDeltaMessageContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDeltaMessage.js
var require_ChatContentStartEventDeltaMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDeltaMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDelta.js
var require_ChatContentStartEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEvent.js
var require_ChatContentStartEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentStartEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDeltaMessageContent.js
var require_ChatContentDeltaEventDeltaMessageContent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDeltaMessageContent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDeltaMessage.js
var require_ChatContentDeltaEventDeltaMessage = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDeltaMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDelta.js
var require_ChatContentDeltaEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEvent.js
var require_ChatContentDeltaEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentDeltaEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatContentEndEvent.js
var require_ChatContentEndEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatContentEndEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolPlanDeltaEventDelta.js
var require_ChatToolPlanDeltaEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolPlanDeltaEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolPlanDeltaEvent.js
var require_ChatToolPlanDeltaEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolPlanDeltaEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDeltaToolCallFunction.js
var require_ChatToolCallStartEventDeltaToolCallFunction = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDeltaToolCallFunction.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDeltaToolCall.js
var require_ChatToolCallStartEventDeltaToolCall = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDeltaToolCall.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDelta.js
var require_ChatToolCallStartEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEvent.js
var require_ChatToolCallStartEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallStartEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDeltaToolCallFunction.js
var require_ChatToolCallDeltaEventDeltaToolCallFunction = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDeltaToolCallFunction.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDeltaToolCall.js
var require_ChatToolCallDeltaEventDeltaToolCall = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDeltaToolCall.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDelta.js
var require_ChatToolCallDeltaEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEvent.js
var require_ChatToolCallDeltaEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallDeltaEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatToolCallEndEvent.js
var require_ChatToolCallEndEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatToolCallEndEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessageEndEventDelta.js
var require_ChatMessageEndEventDelta = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessageEndEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/ChatMessageEndEvent.js
var require_ChatMessageEndEvent = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/ChatMessageEndEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/StreamedChatResponse2.js
var require_StreamedChatResponse2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/StreamedChatResponse2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/types/index.js
var require_types = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_V2ChatStreamRequestCitationMode(), exports);
    __exportStar5(require_V2ChatRequestCitationMode(), exports);
    __exportStar5(require_TextContent(), exports);
    __exportStar5(require_Content(), exports);
    __exportStar5(require_UserMessageContent(), exports);
    __exportStar5(require_UserMessage(), exports);
    __exportStar5(require_ToolCall2Function(), exports);
    __exportStar5(require_ToolCall2(), exports);
    __exportStar5(require_ToolSource(), exports);
    __exportStar5(require_DocumentSource(), exports);
    __exportStar5(require_Source(), exports);
    __exportStar5(require_Citation(), exports);
    __exportStar5(require_AssistantMessageContentItem(), exports);
    __exportStar5(require_AssistantMessageContent(), exports);
    __exportStar5(require_AssistantMessage(), exports);
    __exportStar5(require_SystemMessageContentItem(), exports);
    __exportStar5(require_SystemMessageContent(), exports);
    __exportStar5(require_SystemMessage(), exports);
    __exportStar5(require_ToolContent(), exports);
    __exportStar5(require_ToolMessage2ToolContentItem(), exports);
    __exportStar5(require_ToolMessage2(), exports);
    __exportStar5(require_ChatMessage2(), exports);
    __exportStar5(require_ChatMessages(), exports);
    __exportStar5(require_Tool2Function(), exports);
    __exportStar5(require_Tool2(), exports);
    __exportStar5(require_ChatFinishReason(), exports);
    __exportStar5(require_AssistantMessageResponseContentItem(), exports);
    __exportStar5(require_AssistantMessageResponse(), exports);
    __exportStar5(require_UsageBilledUnits(), exports);
    __exportStar5(require_UsageTokens(), exports);
    __exportStar5(require_Usage(), exports);
    __exportStar5(require_NonStreamedChatResponse2(), exports);
    __exportStar5(require_ChatStreamEventType(), exports);
    __exportStar5(require_ChatMessageStartEventDeltaMessage(), exports);
    __exportStar5(require_ChatMessageStartEventDelta(), exports);
    __exportStar5(require_ChatMessageStartEvent(), exports);
    __exportStar5(require_ChatContentStartEventDeltaMessageContent(), exports);
    __exportStar5(require_ChatContentStartEventDeltaMessage(), exports);
    __exportStar5(require_ChatContentStartEventDelta(), exports);
    __exportStar5(require_ChatContentStartEvent(), exports);
    __exportStar5(require_ChatContentDeltaEventDeltaMessageContent(), exports);
    __exportStar5(require_ChatContentDeltaEventDeltaMessage(), exports);
    __exportStar5(require_ChatContentDeltaEventDelta(), exports);
    __exportStar5(require_ChatContentDeltaEvent(), exports);
    __exportStar5(require_ChatContentEndEvent(), exports);
    __exportStar5(require_ChatToolPlanDeltaEventDelta(), exports);
    __exportStar5(require_ChatToolPlanDeltaEvent(), exports);
    __exportStar5(require_ChatToolCallStartEventDeltaToolCallFunction(), exports);
    __exportStar5(require_ChatToolCallStartEventDeltaToolCall(), exports);
    __exportStar5(require_ChatToolCallStartEventDelta(), exports);
    __exportStar5(require_ChatToolCallStartEvent(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDeltaToolCallFunction(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDeltaToolCall(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDelta(), exports);
    __exportStar5(require_ChatToolCallDeltaEvent(), exports);
    __exportStar5(require_ChatToolCallEndEvent(), exports);
    __exportStar5(require_ChatMessageEndEventDelta(), exports);
    __exportStar5(require_ChatMessageEndEvent(), exports);
    __exportStar5(require_StreamedChatResponse2(), exports);
  }
});

// node_modules/cohere-ai/api/resources/v2/client/requests/index.js
var require_requests = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/v2/client/index.js
var require_client2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests(), exports);
  }
});

// node_modules/cohere-ai/api/resources/v2/index.js
var require_v2 = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types(), exports);
    __exportStar5(require_client2(), exports);
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/types/CreateEmbedJobRequestTruncate.js
var require_CreateEmbedJobRequestTruncate = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/types/CreateEmbedJobRequestTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateEmbedJobRequestTruncate = void 0;
    exports.CreateEmbedJobRequestTruncate = {
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/types/index.js
var require_types2 = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_CreateEmbedJobRequestTruncate(), exports);
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/client/requests/index.js
var require_requests2 = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/client/index.js
var require_client3 = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests2(), exports);
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/index.js
var require_embedJobs = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types2(), exports);
    __exportStar5(require_client3(), exports);
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/DatasetsListResponse.js
var require_DatasetsListResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/DatasetsListResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.js
var require_DatasetsCreateResponseDatasetPartsItem = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/DatasetsCreateResponse.js
var require_DatasetsCreateResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/DatasetsCreateResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/DatasetsGetUsageResponse.js
var require_DatasetsGetUsageResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/DatasetsGetUsageResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/DatasetsGetResponse.js
var require_DatasetsGetResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/DatasetsGetResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/types/index.js
var require_types3 = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_DatasetsListResponse(), exports);
    __exportStar5(require_DatasetsCreateResponseDatasetPartsItem(), exports);
    __exportStar5(require_DatasetsCreateResponse(), exports);
    __exportStar5(require_DatasetsGetUsageResponse(), exports);
    __exportStar5(require_DatasetsGetResponse(), exports);
  }
});

// node_modules/cohere-ai/api/resources/datasets/client/requests/index.js
var require_requests3 = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/datasets/client/index.js
var require_client4 = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests3(), exports);
  }
});

// node_modules/cohere-ai/api/resources/datasets/index.js
var require_datasets = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types3(), exports);
    __exportStar5(require_client4(), exports);
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/BaseType.js
var require_BaseType = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/BaseType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseType = void 0;
    exports.BaseType = {
      BaseTypeUnspecified: "BASE_TYPE_UNSPECIFIED",
      BaseTypeGenerative: "BASE_TYPE_GENERATIVE",
      BaseTypeClassification: "BASE_TYPE_CLASSIFICATION",
      BaseTypeRerank: "BASE_TYPE_RERANK",
      BaseTypeChat: "BASE_TYPE_CHAT"
    };
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Strategy.js
var require_Strategy = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Strategy.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Strategy = void 0;
    exports.Strategy = {
      StrategyUnspecified: "STRATEGY_UNSPECIFIED",
      StrategyVanilla: "STRATEGY_VANILLA",
      StrategyTfew: "STRATEGY_TFEW"
    };
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/BaseModel.js
var require_BaseModel = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/BaseModel.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Hyperparameters.js
var require_Hyperparameters = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Hyperparameters.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/WandbConfig.js
var require_WandbConfig = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/WandbConfig.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Settings.js
var require_Settings = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Settings.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Status.js
var require_Status = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Status.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Status = void 0;
    exports.Status = {
      StatusUnspecified: "STATUS_UNSPECIFIED",
      StatusFinetuning: "STATUS_FINETUNING",
      StatusDeployingApi: "STATUS_DEPLOYING_API",
      StatusReady: "STATUS_READY",
      StatusFailed: "STATUS_FAILED",
      StatusDeleted: "STATUS_DELETED",
      StatusTemporarilyOffline: "STATUS_TEMPORARILY_OFFLINE",
      StatusPaused: "STATUS_PAUSED",
      StatusQueued: "STATUS_QUEUED"
    };
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/FinetunedModel.js
var require_FinetunedModel = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/FinetunedModel.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListFinetunedModelsResponse.js
var require_ListFinetunedModelsResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListFinetunedModelsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/CreateFinetunedModelResponse.js
var require_CreateFinetunedModelResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/CreateFinetunedModelResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/GetFinetunedModelResponse.js
var require_GetFinetunedModelResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/GetFinetunedModelResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/DeleteFinetunedModelResponse.js
var require_DeleteFinetunedModelResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/DeleteFinetunedModelResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/UpdateFinetunedModelResponse.js
var require_UpdateFinetunedModelResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/UpdateFinetunedModelResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Event.js
var require_Event = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/Event.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListEventsResponse.js
var require_ListEventsResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListEventsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/TrainingStepMetrics.js
var require_TrainingStepMetrics = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/TrainingStepMetrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListTrainingStepMetricsResponse.js
var require_ListTrainingStepMetricsResponse = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/ListTrainingStepMetricsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/index.js
var require_types4 = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_BaseType(), exports);
    __exportStar5(require_Strategy(), exports);
    __exportStar5(require_BaseModel(), exports);
    __exportStar5(require_Hyperparameters(), exports);
    __exportStar5(require_WandbConfig(), exports);
    __exportStar5(require_Settings(), exports);
    __exportStar5(require_Status(), exports);
    __exportStar5(require_FinetunedModel(), exports);
    __exportStar5(require_ListFinetunedModelsResponse(), exports);
    __exportStar5(require_CreateFinetunedModelResponse(), exports);
    __exportStar5(require_GetFinetunedModelResponse(), exports);
    __exportStar5(require_DeleteFinetunedModelResponse(), exports);
    __exportStar5(require_UpdateFinetunedModelResponse(), exports);
    __exportStar5(require_Event(), exports);
    __exportStar5(require_ListEventsResponse(), exports);
    __exportStar5(require_TrainingStepMetrics(), exports);
    __exportStar5(require_ListTrainingStepMetricsResponse(), exports);
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/index.js
var require_finetuning = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/finetuning/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types4(), exports);
  }
});

// node_modules/cohere-ai/api/resources/finetuning/resources/index.js
var require_resources = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/resources/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.finetuning = void 0;
    exports.finetuning = __importStar5(require_finetuning());
    __exportStar5(require_types4(), exports);
  }
});

// node_modules/cohere-ai/api/resources/finetuning/client/requests/index.js
var require_requests4 = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/finetuning/client/index.js
var require_client5 = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests4(), exports);
  }
});

// node_modules/cohere-ai/api/resources/finetuning/index.js
var require_finetuning2 = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_resources(), exports);
    __exportStar5(require_client5(), exports);
  }
});

// node_modules/cohere-ai/api/resources/connectors/client/requests/index.js
var require_requests5 = __commonJS({
  "node_modules/cohere-ai/api/resources/connectors/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/connectors/client/index.js
var require_client6 = __commonJS({
  "node_modules/cohere-ai/api/resources/connectors/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests5(), exports);
  }
});

// node_modules/cohere-ai/api/resources/connectors/index.js
var require_connectors = __commonJS({
  "node_modules/cohere-ai/api/resources/connectors/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_client6(), exports);
  }
});

// node_modules/cohere-ai/api/resources/models/client/requests/index.js
var require_requests6 = __commonJS({
  "node_modules/cohere-ai/api/resources/models/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/resources/models/client/index.js
var require_client7 = __commonJS({
  "node_modules/cohere-ai/api/resources/models/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests6(), exports);
  }
});

// node_modules/cohere-ai/api/resources/models/index.js
var require_models = __commonJS({
  "node_modules/cohere-ai/api/resources/models/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_client7(), exports);
  }
});

// node_modules/cohere-ai/api/resources/index.js
var require_resources2 = __commonJS({
  "node_modules/cohere-ai/api/resources/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.models = exports.connectors = exports.finetuning = exports.datasets = exports.embedJobs = exports.v2 = void 0;
    exports.v2 = __importStar5(require_v2());
    __exportStar5(require_types(), exports);
    exports.embedJobs = __importStar5(require_embedJobs());
    __exportStar5(require_types2(), exports);
    exports.datasets = __importStar5(require_datasets());
    __exportStar5(require_types3(), exports);
    exports.finetuning = __importStar5(require_finetuning2());
    exports.connectors = __importStar5(require_connectors());
    exports.models = __importStar5(require_models());
    __exportStar5(require_requests(), exports);
    __exportStar5(require_requests2(), exports);
    __exportStar5(require_requests3(), exports);
    __exportStar5(require_requests5(), exports);
    __exportStar5(require_requests6(), exports);
    __exportStar5(require_requests4(), exports);
  }
});

// node_modules/cohere-ai/api/types/ChatStreamRequestPromptTruncation.js
var require_ChatStreamRequestPromptTruncation = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamRequestPromptTruncation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestPromptTruncation = void 0;
    exports.ChatStreamRequestPromptTruncation = {
      Off: "OFF",
      Auto: "AUTO",
      AutoPreserveOrder: "AUTO_PRESERVE_ORDER"
    };
  }
});

// node_modules/cohere-ai/api/types/ChatStreamRequestCitationQuality.js
var require_ChatStreamRequestCitationQuality = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamRequestCitationQuality.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestCitationQuality = void 0;
    exports.ChatStreamRequestCitationQuality = {
      Fast: "fast",
      Accurate: "accurate",
      Off: "off"
    };
  }
});

// node_modules/cohere-ai/api/types/ChatStreamRequestConnectorsSearchOptions.js
var require_ChatStreamRequestConnectorsSearchOptions = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamRequestConnectorsSearchOptions.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatStreamRequestSafetyMode.js
var require_ChatStreamRequestSafetyMode = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamRequestSafetyMode.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestSafetyMode = void 0;
    exports.ChatStreamRequestSafetyMode = {
      Contextual: "CONTEXTUAL",
      Strict: "STRICT",
      None: "NONE"
    };
  }
});

// node_modules/cohere-ai/api/types/UnprocessableEntityErrorBody.js
var require_UnprocessableEntityErrorBody = __commonJS({
  "node_modules/cohere-ai/api/types/UnprocessableEntityErrorBody.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/TooManyRequestsErrorBody.js
var require_TooManyRequestsErrorBody = __commonJS({
  "node_modules/cohere-ai/api/types/TooManyRequestsErrorBody.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClientClosedRequestErrorBody.js
var require_ClientClosedRequestErrorBody = __commonJS({
  "node_modules/cohere-ai/api/types/ClientClosedRequestErrorBody.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/NotImplementedErrorBody.js
var require_NotImplementedErrorBody = __commonJS({
  "node_modules/cohere-ai/api/types/NotImplementedErrorBody.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GatewayTimeoutErrorBody.js
var require_GatewayTimeoutErrorBody = __commonJS({
  "node_modules/cohere-ai/api/types/GatewayTimeoutErrorBody.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatRequestPromptTruncation.js
var require_ChatRequestPromptTruncation = __commonJS({
  "node_modules/cohere-ai/api/types/ChatRequestPromptTruncation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestPromptTruncation = void 0;
    exports.ChatRequestPromptTruncation = {
      Off: "OFF",
      Auto: "AUTO",
      AutoPreserveOrder: "AUTO_PRESERVE_ORDER"
    };
  }
});

// node_modules/cohere-ai/api/types/ChatRequestCitationQuality.js
var require_ChatRequestCitationQuality = __commonJS({
  "node_modules/cohere-ai/api/types/ChatRequestCitationQuality.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestCitationQuality = void 0;
    exports.ChatRequestCitationQuality = {
      Fast: "fast",
      Accurate: "accurate",
      Off: "off"
    };
  }
});

// node_modules/cohere-ai/api/types/ChatRequestConnectorsSearchOptions.js
var require_ChatRequestConnectorsSearchOptions = __commonJS({
  "node_modules/cohere-ai/api/types/ChatRequestConnectorsSearchOptions.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatRequestSafetyMode.js
var require_ChatRequestSafetyMode = __commonJS({
  "node_modules/cohere-ai/api/types/ChatRequestSafetyMode.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestSafetyMode = void 0;
    exports.ChatRequestSafetyMode = {
      Contextual: "CONTEXTUAL",
      Strict: "STRICT",
      None: "NONE"
    };
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamRequestTruncate.js
var require_GenerateStreamRequestTruncate = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamRequestTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamRequestTruncate = void 0;
    exports.GenerateStreamRequestTruncate = {
      None: "NONE",
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamRequestReturnLikelihoods.js
var require_GenerateStreamRequestReturnLikelihoods = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamRequestReturnLikelihoods.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamRequestReturnLikelihoods = void 0;
    exports.GenerateStreamRequestReturnLikelihoods = {
      Generation: "GENERATION",
      All: "ALL",
      None: "NONE"
    };
  }
});

// node_modules/cohere-ai/api/types/GenerateRequestTruncate.js
var require_GenerateRequestTruncate = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateRequestTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateRequestTruncate = void 0;
    exports.GenerateRequestTruncate = {
      None: "NONE",
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/types/GenerateRequestReturnLikelihoods.js
var require_GenerateRequestReturnLikelihoods = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateRequestReturnLikelihoods.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateRequestReturnLikelihoods = void 0;
    exports.GenerateRequestReturnLikelihoods = {
      Generation: "GENERATION",
      All: "ALL",
      None: "NONE"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbedRequestTruncate.js
var require_EmbedRequestTruncate = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedRequestTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedRequestTruncate = void 0;
    exports.EmbedRequestTruncate = {
      None: "NONE",
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbedResponse.js
var require_EmbedResponse = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankRequestDocumentsItem.js
var require_RerankRequestDocumentsItem = __commonJS({
  "node_modules/cohere-ai/api/types/RerankRequestDocumentsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankResponseResultsItemDocument.js
var require_RerankResponseResultsItemDocument = __commonJS({
  "node_modules/cohere-ai/api/types/RerankResponseResultsItemDocument.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankResponseResultsItem.js
var require_RerankResponseResultsItem = __commonJS({
  "node_modules/cohere-ai/api/types/RerankResponseResultsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankResponse.js
var require_RerankResponse = __commonJS({
  "node_modules/cohere-ai/api/types/RerankResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClassifyRequestTruncate.js
var require_ClassifyRequestTruncate = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyRequestTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyRequestTruncate = void 0;
    exports.ClassifyRequestTruncate = {
      None: "NONE",
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItemLabelsValue.js
var require_ClassifyResponseClassificationsItemLabelsValue = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItemLabelsValue.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItemClassificationType.js
var require_ClassifyResponseClassificationsItemClassificationType = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItemClassificationType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyResponseClassificationsItemClassificationType = void 0;
    exports.ClassifyResponseClassificationsItemClassificationType = {
      SingleLabel: "single-label",
      MultiLabel: "multi-label"
    };
  }
});

// node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItem.js
var require_ClassifyResponseClassificationsItem = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyResponseClassificationsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClassifyResponse.js
var require_ClassifyResponse = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/SummarizeRequestLength.js
var require_SummarizeRequestLength = __commonJS({
  "node_modules/cohere-ai/api/types/SummarizeRequestLength.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestLength = void 0;
    exports.SummarizeRequestLength = {
      Short: "short",
      Medium: "medium",
      Long: "long"
    };
  }
});

// node_modules/cohere-ai/api/types/SummarizeRequestFormat.js
var require_SummarizeRequestFormat = __commonJS({
  "node_modules/cohere-ai/api/types/SummarizeRequestFormat.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestFormat = void 0;
    exports.SummarizeRequestFormat = {
      Paragraph: "paragraph",
      Bullets: "bullets"
    };
  }
});

// node_modules/cohere-ai/api/types/SummarizeRequestExtractiveness.js
var require_SummarizeRequestExtractiveness = __commonJS({
  "node_modules/cohere-ai/api/types/SummarizeRequestExtractiveness.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestExtractiveness = void 0;
    exports.SummarizeRequestExtractiveness = {
      Low: "low",
      Medium: "medium",
      High: "high"
    };
  }
});

// node_modules/cohere-ai/api/types/SummarizeResponse.js
var require_SummarizeResponse = __commonJS({
  "node_modules/cohere-ai/api/types/SummarizeResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/TokenizeResponse.js
var require_TokenizeResponse = __commonJS({
  "node_modules/cohere-ai/api/types/TokenizeResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/DetokenizeResponse.js
var require_DetokenizeResponse = __commonJS({
  "node_modules/cohere-ai/api/types/DetokenizeResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CheckApiKeyResponse.js
var require_CheckApiKeyResponse = __commonJS({
  "node_modules/cohere-ai/api/types/CheckApiKeyResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ToolCall.js
var require_ToolCall = __commonJS({
  "node_modules/cohere-ai/api/types/ToolCall.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatMessage.js
var require_ChatMessage = __commonJS({
  "node_modules/cohere-ai/api/types/ChatMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ToolResult.js
var require_ToolResult = __commonJS({
  "node_modules/cohere-ai/api/types/ToolResult.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ToolMessage.js
var require_ToolMessage = __commonJS({
  "node_modules/cohere-ai/api/types/ToolMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/Message.js
var require_Message = __commonJS({
  "node_modules/cohere-ai/api/types/Message.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatConnector.js
var require_ChatConnector = __commonJS({
  "node_modules/cohere-ai/api/types/ChatConnector.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatDocument.js
var require_ChatDocument = __commonJS({
  "node_modules/cohere-ai/api/types/ChatDocument.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ToolParameterDefinitionsValue.js
var require_ToolParameterDefinitionsValue = __commonJS({
  "node_modules/cohere-ai/api/types/ToolParameterDefinitionsValue.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/Tool.js
var require_Tool = __commonJS({
  "node_modules/cohere-ai/api/types/Tool.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/TextResponseFormat.js
var require_TextResponseFormat = __commonJS({
  "node_modules/cohere-ai/api/types/TextResponseFormat.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/JsonResponseFormat.js
var require_JsonResponseFormat = __commonJS({
  "node_modules/cohere-ai/api/types/JsonResponseFormat.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ResponseFormat.js
var require_ResponseFormat = __commonJS({
  "node_modules/cohere-ai/api/types/ResponseFormat.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatCitation.js
var require_ChatCitation = __commonJS({
  "node_modules/cohere-ai/api/types/ChatCitation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatSearchQuery.js
var require_ChatSearchQuery = __commonJS({
  "node_modules/cohere-ai/api/types/ChatSearchQuery.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatSearchResultConnector.js
var require_ChatSearchResultConnector = __commonJS({
  "node_modules/cohere-ai/api/types/ChatSearchResultConnector.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatSearchResult.js
var require_ChatSearchResult = __commonJS({
  "node_modules/cohere-ai/api/types/ChatSearchResult.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/FinishReason.js
var require_FinishReason = __commonJS({
  "node_modules/cohere-ai/api/types/FinishReason.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinishReason = void 0;
    exports.FinishReason = {
      Complete: "COMPLETE",
      StopSequence: "STOP_SEQUENCE",
      Error: "ERROR",
      ErrorToxic: "ERROR_TOXIC",
      ErrorLimit: "ERROR_LIMIT",
      UserCancel: "USER_CANCEL",
      MaxTokens: "MAX_TOKENS"
    };
  }
});

// node_modules/cohere-ai/api/types/ApiMetaApiVersion.js
var require_ApiMetaApiVersion = __commonJS({
  "node_modules/cohere-ai/api/types/ApiMetaApiVersion.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ApiMetaBilledUnits.js
var require_ApiMetaBilledUnits = __commonJS({
  "node_modules/cohere-ai/api/types/ApiMetaBilledUnits.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ApiMetaTokens.js
var require_ApiMetaTokens = __commonJS({
  "node_modules/cohere-ai/api/types/ApiMetaTokens.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ApiMeta.js
var require_ApiMeta = __commonJS({
  "node_modules/cohere-ai/api/types/ApiMeta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/NonStreamedChatResponse.js
var require_NonStreamedChatResponse = __commonJS({
  "node_modules/cohere-ai/api/types/NonStreamedChatResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatStreamEvent.js
var require_ChatStreamEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatStreamStartEvent.js
var require_ChatStreamStartEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamStartEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatSearchQueriesGenerationEvent.js
var require_ChatSearchQueriesGenerationEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatSearchQueriesGenerationEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatSearchResultsEvent.js
var require_ChatSearchResultsEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatSearchResultsEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatTextGenerationEvent.js
var require_ChatTextGenerationEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatTextGenerationEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatCitationGenerationEvent.js
var require_ChatCitationGenerationEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatCitationGenerationEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatToolCallsGenerationEvent.js
var require_ChatToolCallsGenerationEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatToolCallsGenerationEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatStreamEndEventFinishReason.js
var require_ChatStreamEndEventFinishReason = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamEndEventFinishReason.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamEndEventFinishReason = void 0;
    exports.ChatStreamEndEventFinishReason = {
      Complete: "COMPLETE",
      ErrorLimit: "ERROR_LIMIT",
      MaxTokens: "MAX_TOKENS",
      Error: "ERROR",
      ErrorToxic: "ERROR_TOXIC"
    };
  }
});

// node_modules/cohere-ai/api/types/ChatStreamEndEvent.js
var require_ChatStreamEndEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatStreamEndEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ToolCallDelta.js
var require_ToolCallDelta = __commonJS({
  "node_modules/cohere-ai/api/types/ToolCallDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatToolCallsChunkEvent.js
var require_ChatToolCallsChunkEvent = __commonJS({
  "node_modules/cohere-ai/api/types/ChatToolCallsChunkEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/StreamedChatResponse.js
var require_StreamedChatResponse = __commonJS({
  "node_modules/cohere-ai/api/types/StreamedChatResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/JsonResponseFormat2.js
var require_JsonResponseFormat2 = __commonJS({
  "node_modules/cohere-ai/api/types/JsonResponseFormat2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ResponseFormat2.js
var require_ResponseFormat2 = __commonJS({
  "node_modules/cohere-ai/api/types/ResponseFormat2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CitationStartEventDeltaMessage.js
var require_CitationStartEventDeltaMessage = __commonJS({
  "node_modules/cohere-ai/api/types/CitationStartEventDeltaMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CitationStartEventDelta.js
var require_CitationStartEventDelta = __commonJS({
  "node_modules/cohere-ai/api/types/CitationStartEventDelta.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CitationStartEvent.js
var require_CitationStartEvent = __commonJS({
  "node_modules/cohere-ai/api/types/CitationStartEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CitationEndEvent.js
var require_CitationEndEvent = __commonJS({
  "node_modules/cohere-ai/api/types/CitationEndEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/SingleGenerationTokenLikelihoodsItem.js
var require_SingleGenerationTokenLikelihoodsItem = __commonJS({
  "node_modules/cohere-ai/api/types/SingleGenerationTokenLikelihoodsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/SingleGeneration.js
var require_SingleGeneration = __commonJS({
  "node_modules/cohere-ai/api/types/SingleGeneration.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/Generation.js
var require_Generation = __commonJS({
  "node_modules/cohere-ai/api/types/Generation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamEvent.js
var require_GenerateStreamEvent = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamEvent.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamText.js
var require_GenerateStreamText = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamText.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/SingleGenerationInStream.js
var require_SingleGenerationInStream = __commonJS({
  "node_modules/cohere-ai/api/types/SingleGenerationInStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamEndResponse.js
var require_GenerateStreamEndResponse = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamEndResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamEnd.js
var require_GenerateStreamEnd = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamEnd.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamError.js
var require_GenerateStreamError = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GenerateStreamedResponse.js
var require_GenerateStreamedResponse = __commonJS({
  "node_modules/cohere-ai/api/types/GenerateStreamedResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/EmbedInputType.js
var require_EmbedInputType = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedInputType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedInputType = void 0;
    exports.EmbedInputType = {
      SearchDocument: "search_document",
      SearchQuery: "search_query",
      Classification: "classification",
      Clustering: "clustering"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbeddingType.js
var require_EmbeddingType = __commonJS({
  "node_modules/cohere-ai/api/types/EmbeddingType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingType = void 0;
    exports.EmbeddingType = {
      Float: "float",
      Int8: "int8",
      Uint8: "uint8",
      Binary: "binary",
      Ubinary: "ubinary"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbedFloatsResponse.js
var require_EmbedFloatsResponse = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedFloatsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/EmbedByTypeResponseEmbeddings.js
var require_EmbedByTypeResponseEmbeddings = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedByTypeResponseEmbeddings.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/EmbedByTypeResponse.js
var require_EmbedByTypeResponse = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedByTypeResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/EmbedJobStatus.js
var require_EmbedJobStatus = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedJobStatus.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJobStatus = void 0;
    exports.EmbedJobStatus = {
      Processing: "processing",
      Complete: "complete",
      Cancelling: "cancelling",
      Cancelled: "cancelled",
      Failed: "failed"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbedJobTruncate.js
var require_EmbedJobTruncate = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedJobTruncate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJobTruncate = void 0;
    exports.EmbedJobTruncate = {
      Start: "START",
      End: "END"
    };
  }
});

// node_modules/cohere-ai/api/types/EmbedJob.js
var require_EmbedJob = __commonJS({
  "node_modules/cohere-ai/api/types/EmbedJob.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ListEmbedJobResponse.js
var require_ListEmbedJobResponse = __commonJS({
  "node_modules/cohere-ai/api/types/ListEmbedJobResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CreateEmbedJobResponse.js
var require_CreateEmbedJobResponse = __commonJS({
  "node_modules/cohere-ai/api/types/CreateEmbedJobResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankDocument.js
var require_RerankDocument = __commonJS({
  "node_modules/cohere-ai/api/types/RerankDocument.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClassifyExample.js
var require_ClassifyExample = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyExample.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/DatasetValidationStatus.js
var require_DatasetValidationStatus = __commonJS({
  "node_modules/cohere-ai/api/types/DatasetValidationStatus.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetValidationStatus = void 0;
    exports.DatasetValidationStatus = {
      Unknown: "unknown",
      Queued: "queued",
      Processing: "processing",
      Failed: "failed",
      Validated: "validated",
      Skipped: "skipped"
    };
  }
});

// node_modules/cohere-ai/api/types/DatasetType.js
var require_DatasetType = __commonJS({
  "node_modules/cohere-ai/api/types/DatasetType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetType = void 0;
    exports.DatasetType = {
      EmbedInput: "embed-input",
      EmbedResult: "embed-result",
      ClusterResult: "cluster-result",
      ClusterOutliers: "cluster-outliers",
      RerankerFinetuneInput: "reranker-finetune-input",
      SingleLabelClassificationFinetuneInput: "single-label-classification-finetune-input",
      ChatFinetuneInput: "chat-finetune-input",
      MultiLabelClassificationFinetuneInput: "multi-label-classification-finetune-input"
    };
  }
});

// node_modules/cohere-ai/api/types/DatasetPart.js
var require_DatasetPart = __commonJS({
  "node_modules/cohere-ai/api/types/DatasetPart.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ParseInfo.js
var require_ParseInfo = __commonJS({
  "node_modules/cohere-ai/api/types/ParseInfo.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/RerankerDataMetrics.js
var require_RerankerDataMetrics = __commonJS({
  "node_modules/cohere-ai/api/types/RerankerDataMetrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ChatDataMetrics.js
var require_ChatDataMetrics = __commonJS({
  "node_modules/cohere-ai/api/types/ChatDataMetrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/LabelMetric.js
var require_LabelMetric = __commonJS({
  "node_modules/cohere-ai/api/types/LabelMetric.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ClassifyDataMetrics.js
var require_ClassifyDataMetrics = __commonJS({
  "node_modules/cohere-ai/api/types/ClassifyDataMetrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/FinetuneDatasetMetrics.js
var require_FinetuneDatasetMetrics = __commonJS({
  "node_modules/cohere-ai/api/types/FinetuneDatasetMetrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/MetricsEmbedDataFieldsItem.js
var require_MetricsEmbedDataFieldsItem = __commonJS({
  "node_modules/cohere-ai/api/types/MetricsEmbedDataFieldsItem.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/MetricsEmbedData.js
var require_MetricsEmbedData = __commonJS({
  "node_modules/cohere-ai/api/types/MetricsEmbedData.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/Metrics.js
var require_Metrics = __commonJS({
  "node_modules/cohere-ai/api/types/Metrics.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/Dataset.js
var require_Dataset = __commonJS({
  "node_modules/cohere-ai/api/types/Dataset.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ConnectorOAuth.js
var require_ConnectorOAuth = __commonJS({
  "node_modules/cohere-ai/api/types/ConnectorOAuth.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ConnectorAuthStatus.js
var require_ConnectorAuthStatus = __commonJS({
  "node_modules/cohere-ai/api/types/ConnectorAuthStatus.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConnectorAuthStatus = void 0;
    exports.ConnectorAuthStatus = {
      Valid: "valid",
      Expired: "expired"
    };
  }
});

// node_modules/cohere-ai/api/types/Connector.js
var require_Connector = __commonJS({
  "node_modules/cohere-ai/api/types/Connector.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ListConnectorsResponse.js
var require_ListConnectorsResponse = __commonJS({
  "node_modules/cohere-ai/api/types/ListConnectorsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CreateConnectorOAuth.js
var require_CreateConnectorOAuth = __commonJS({
  "node_modules/cohere-ai/api/types/CreateConnectorOAuth.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/AuthTokenType.js
var require_AuthTokenType = __commonJS({
  "node_modules/cohere-ai/api/types/AuthTokenType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AuthTokenType = void 0;
    exports.AuthTokenType = {
      Bearer: "bearer",
      Basic: "basic",
      Noscheme: "noscheme"
    };
  }
});

// node_modules/cohere-ai/api/types/CreateConnectorServiceAuth.js
var require_CreateConnectorServiceAuth = __commonJS({
  "node_modules/cohere-ai/api/types/CreateConnectorServiceAuth.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CreateConnectorResponse.js
var require_CreateConnectorResponse = __commonJS({
  "node_modules/cohere-ai/api/types/CreateConnectorResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/GetConnectorResponse.js
var require_GetConnectorResponse = __commonJS({
  "node_modules/cohere-ai/api/types/GetConnectorResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/DeleteConnectorResponse.js
var require_DeleteConnectorResponse = __commonJS({
  "node_modules/cohere-ai/api/types/DeleteConnectorResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/UpdateConnectorResponse.js
var require_UpdateConnectorResponse = __commonJS({
  "node_modules/cohere-ai/api/types/UpdateConnectorResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/OAuthAuthorizeResponse.js
var require_OAuthAuthorizeResponse = __commonJS({
  "node_modules/cohere-ai/api/types/OAuthAuthorizeResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/CompatibleEndpoint.js
var require_CompatibleEndpoint = __commonJS({
  "node_modules/cohere-ai/api/types/CompatibleEndpoint.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompatibleEndpoint = void 0;
    exports.CompatibleEndpoint = {
      Chat: "chat",
      Embed: "embed",
      Classify: "classify",
      Summarize: "summarize",
      Rerank: "rerank",
      Rate: "rate",
      Generate: "generate"
    };
  }
});

// node_modules/cohere-ai/api/types/GetModelResponse.js
var require_GetModelResponse = __commonJS({
  "node_modules/cohere-ai/api/types/GetModelResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/ListModelsResponse.js
var require_ListModelsResponse = __commonJS({
  "node_modules/cohere-ai/api/types/ListModelsResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/types/index.js
var require_types5 = __commonJS({
  "node_modules/cohere-ai/api/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_ChatStreamRequestPromptTruncation(), exports);
    __exportStar5(require_ChatStreamRequestCitationQuality(), exports);
    __exportStar5(require_ChatStreamRequestConnectorsSearchOptions(), exports);
    __exportStar5(require_ChatStreamRequestSafetyMode(), exports);
    __exportStar5(require_UnprocessableEntityErrorBody(), exports);
    __exportStar5(require_TooManyRequestsErrorBody(), exports);
    __exportStar5(require_ClientClosedRequestErrorBody(), exports);
    __exportStar5(require_NotImplementedErrorBody(), exports);
    __exportStar5(require_GatewayTimeoutErrorBody(), exports);
    __exportStar5(require_ChatRequestPromptTruncation(), exports);
    __exportStar5(require_ChatRequestCitationQuality(), exports);
    __exportStar5(require_ChatRequestConnectorsSearchOptions(), exports);
    __exportStar5(require_ChatRequestSafetyMode(), exports);
    __exportStar5(require_GenerateStreamRequestTruncate(), exports);
    __exportStar5(require_GenerateStreamRequestReturnLikelihoods(), exports);
    __exportStar5(require_GenerateRequestTruncate(), exports);
    __exportStar5(require_GenerateRequestReturnLikelihoods(), exports);
    __exportStar5(require_EmbedRequestTruncate(), exports);
    __exportStar5(require_EmbedResponse(), exports);
    __exportStar5(require_RerankRequestDocumentsItem(), exports);
    __exportStar5(require_RerankResponseResultsItemDocument(), exports);
    __exportStar5(require_RerankResponseResultsItem(), exports);
    __exportStar5(require_RerankResponse(), exports);
    __exportStar5(require_ClassifyRequestTruncate(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItemLabelsValue(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItemClassificationType(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItem(), exports);
    __exportStar5(require_ClassifyResponse(), exports);
    __exportStar5(require_SummarizeRequestLength(), exports);
    __exportStar5(require_SummarizeRequestFormat(), exports);
    __exportStar5(require_SummarizeRequestExtractiveness(), exports);
    __exportStar5(require_SummarizeResponse(), exports);
    __exportStar5(require_TokenizeResponse(), exports);
    __exportStar5(require_DetokenizeResponse(), exports);
    __exportStar5(require_CheckApiKeyResponse(), exports);
    __exportStar5(require_ToolCall(), exports);
    __exportStar5(require_ChatMessage(), exports);
    __exportStar5(require_ToolResult(), exports);
    __exportStar5(require_ToolMessage(), exports);
    __exportStar5(require_Message(), exports);
    __exportStar5(require_ChatConnector(), exports);
    __exportStar5(require_ChatDocument(), exports);
    __exportStar5(require_ToolParameterDefinitionsValue(), exports);
    __exportStar5(require_Tool(), exports);
    __exportStar5(require_TextResponseFormat(), exports);
    __exportStar5(require_JsonResponseFormat(), exports);
    __exportStar5(require_ResponseFormat(), exports);
    __exportStar5(require_ChatCitation(), exports);
    __exportStar5(require_ChatSearchQuery(), exports);
    __exportStar5(require_ChatSearchResultConnector(), exports);
    __exportStar5(require_ChatSearchResult(), exports);
    __exportStar5(require_FinishReason(), exports);
    __exportStar5(require_ApiMetaApiVersion(), exports);
    __exportStar5(require_ApiMetaBilledUnits(), exports);
    __exportStar5(require_ApiMetaTokens(), exports);
    __exportStar5(require_ApiMeta(), exports);
    __exportStar5(require_NonStreamedChatResponse(), exports);
    __exportStar5(require_ChatStreamEvent(), exports);
    __exportStar5(require_ChatStreamStartEvent(), exports);
    __exportStar5(require_ChatSearchQueriesGenerationEvent(), exports);
    __exportStar5(require_ChatSearchResultsEvent(), exports);
    __exportStar5(require_ChatTextGenerationEvent(), exports);
    __exportStar5(require_ChatCitationGenerationEvent(), exports);
    __exportStar5(require_ChatToolCallsGenerationEvent(), exports);
    __exportStar5(require_ChatStreamEndEventFinishReason(), exports);
    __exportStar5(require_ChatStreamEndEvent(), exports);
    __exportStar5(require_ToolCallDelta(), exports);
    __exportStar5(require_ChatToolCallsChunkEvent(), exports);
    __exportStar5(require_StreamedChatResponse(), exports);
    __exportStar5(require_JsonResponseFormat2(), exports);
    __exportStar5(require_ResponseFormat2(), exports);
    __exportStar5(require_CitationStartEventDeltaMessage(), exports);
    __exportStar5(require_CitationStartEventDelta(), exports);
    __exportStar5(require_CitationStartEvent(), exports);
    __exportStar5(require_CitationEndEvent(), exports);
    __exportStar5(require_SingleGenerationTokenLikelihoodsItem(), exports);
    __exportStar5(require_SingleGeneration(), exports);
    __exportStar5(require_Generation(), exports);
    __exportStar5(require_GenerateStreamEvent(), exports);
    __exportStar5(require_GenerateStreamText(), exports);
    __exportStar5(require_SingleGenerationInStream(), exports);
    __exportStar5(require_GenerateStreamEndResponse(), exports);
    __exportStar5(require_GenerateStreamEnd(), exports);
    __exportStar5(require_GenerateStreamError(), exports);
    __exportStar5(require_GenerateStreamedResponse(), exports);
    __exportStar5(require_EmbedInputType(), exports);
    __exportStar5(require_EmbeddingType(), exports);
    __exportStar5(require_EmbedFloatsResponse(), exports);
    __exportStar5(require_EmbedByTypeResponseEmbeddings(), exports);
    __exportStar5(require_EmbedByTypeResponse(), exports);
    __exportStar5(require_EmbedJobStatus(), exports);
    __exportStar5(require_EmbedJobTruncate(), exports);
    __exportStar5(require_EmbedJob(), exports);
    __exportStar5(require_ListEmbedJobResponse(), exports);
    __exportStar5(require_CreateEmbedJobResponse(), exports);
    __exportStar5(require_RerankDocument(), exports);
    __exportStar5(require_ClassifyExample(), exports);
    __exportStar5(require_DatasetValidationStatus(), exports);
    __exportStar5(require_DatasetType(), exports);
    __exportStar5(require_DatasetPart(), exports);
    __exportStar5(require_ParseInfo(), exports);
    __exportStar5(require_RerankerDataMetrics(), exports);
    __exportStar5(require_ChatDataMetrics(), exports);
    __exportStar5(require_LabelMetric(), exports);
    __exportStar5(require_ClassifyDataMetrics(), exports);
    __exportStar5(require_FinetuneDatasetMetrics(), exports);
    __exportStar5(require_MetricsEmbedDataFieldsItem(), exports);
    __exportStar5(require_MetricsEmbedData(), exports);
    __exportStar5(require_Metrics(), exports);
    __exportStar5(require_Dataset(), exports);
    __exportStar5(require_ConnectorOAuth(), exports);
    __exportStar5(require_ConnectorAuthStatus(), exports);
    __exportStar5(require_Connector(), exports);
    __exportStar5(require_ListConnectorsResponse(), exports);
    __exportStar5(require_CreateConnectorOAuth(), exports);
    __exportStar5(require_AuthTokenType(), exports);
    __exportStar5(require_CreateConnectorServiceAuth(), exports);
    __exportStar5(require_CreateConnectorResponse(), exports);
    __exportStar5(require_GetConnectorResponse(), exports);
    __exportStar5(require_DeleteConnectorResponse(), exports);
    __exportStar5(require_UpdateConnectorResponse(), exports);
    __exportStar5(require_OAuthAuthorizeResponse(), exports);
    __exportStar5(require_CompatibleEndpoint(), exports);
    __exportStar5(require_GetModelResponse(), exports);
    __exportStar5(require_ListModelsResponse(), exports);
  }
});

// node_modules/cohere-ai/errors/CohereError.js
var require_CohereError = __commonJS({
  "node_modules/cohere-ai/errors/CohereError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereError = void 0;
    var CohereError = class extends Error {
      constructor({ message, statusCode, body }) {
        super(buildMessage({ message, statusCode, body }));
        Object.setPrototypeOf(this, CohereError.prototype);
        if (statusCode != null) {
          this.statusCode = statusCode;
        }
        if (body !== void 0) {
          this.body = body;
        }
      }
    };
    exports.CohereError = CohereError;
    function buildMessage({ message, statusCode, body }) {
      let lines = [];
      if (message != null) {
        lines.push(message);
      }
      if (statusCode != null) {
        lines.push(`Status code: ${statusCode.toString()}`);
      }
      if (body != null) {
        lines.push(`Body: ${JSON.stringify(body, void 0, 2)}`);
      }
      return lines.join("\n");
    }
  }
});

// node_modules/cohere-ai/errors/CohereTimeoutError.js
var require_CohereTimeoutError = __commonJS({
  "node_modules/cohere-ai/errors/CohereTimeoutError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereTimeoutError = void 0;
    var CohereTimeoutError = class extends Error {
      constructor() {
        super("Timeout");
        Object.setPrototypeOf(this, CohereTimeoutError.prototype);
      }
    };
    exports.CohereTimeoutError = CohereTimeoutError;
  }
});

// node_modules/cohere-ai/errors/index.js
var require_errors = __commonJS({
  "node_modules/cohere-ai/errors/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereTimeoutError = exports.CohereError = void 0;
    var CohereError_1 = require_CohereError();
    Object.defineProperty(exports, "CohereError", { enumerable: true, get: function() {
      return CohereError_1.CohereError;
    } });
    var CohereTimeoutError_1 = require_CohereTimeoutError();
    Object.defineProperty(exports, "CohereTimeoutError", { enumerable: true, get: function() {
      return CohereTimeoutError_1.CohereTimeoutError;
    } });
  }
});

// node_modules/cohere-ai/api/errors/BadRequestError.js
var require_BadRequestError = __commonJS({
  "node_modules/cohere-ai/api/errors/BadRequestError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BadRequestError = void 0;
    var errors2 = __importStar5(require_errors());
    var BadRequestError6 = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "BadRequestError",
          statusCode: 400,
          body
        });
        Object.setPrototypeOf(this, BadRequestError6.prototype);
      }
    };
    exports.BadRequestError = BadRequestError6;
  }
});

// node_modules/cohere-ai/api/errors/UnauthorizedError.js
var require_UnauthorizedError = __commonJS({
  "node_modules/cohere-ai/api/errors/UnauthorizedError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnauthorizedError = void 0;
    var errors2 = __importStar5(require_errors());
    var UnauthorizedError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "UnauthorizedError",
          statusCode: 401,
          body
        });
        Object.setPrototypeOf(this, UnauthorizedError.prototype);
      }
    };
    exports.UnauthorizedError = UnauthorizedError;
  }
});

// node_modules/cohere-ai/api/errors/ForbiddenError.js
var require_ForbiddenError = __commonJS({
  "node_modules/cohere-ai/api/errors/ForbiddenError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ForbiddenError = void 0;
    var errors2 = __importStar5(require_errors());
    var ForbiddenError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "ForbiddenError",
          statusCode: 403,
          body
        });
        Object.setPrototypeOf(this, ForbiddenError.prototype);
      }
    };
    exports.ForbiddenError = ForbiddenError;
  }
});

// node_modules/cohere-ai/api/errors/NotFoundError.js
var require_NotFoundError = __commonJS({
  "node_modules/cohere-ai/api/errors/NotFoundError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NotFoundError = void 0;
    var errors2 = __importStar5(require_errors());
    var NotFoundError6 = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "NotFoundError",
          statusCode: 404,
          body
        });
        Object.setPrototypeOf(this, NotFoundError6.prototype);
      }
    };
    exports.NotFoundError = NotFoundError6;
  }
});

// node_modules/cohere-ai/api/errors/UnprocessableEntityError.js
var require_UnprocessableEntityError = __commonJS({
  "node_modules/cohere-ai/api/errors/UnprocessableEntityError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnprocessableEntityError = void 0;
    var errors2 = __importStar5(require_errors());
    var UnprocessableEntityError6 = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "UnprocessableEntityError",
          statusCode: 422,
          body
        });
        Object.setPrototypeOf(this, UnprocessableEntityError6.prototype);
      }
    };
    exports.UnprocessableEntityError = UnprocessableEntityError6;
  }
});

// node_modules/cohere-ai/api/errors/TooManyRequestsError.js
var require_TooManyRequestsError = __commonJS({
  "node_modules/cohere-ai/api/errors/TooManyRequestsError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TooManyRequestsError = void 0;
    var errors2 = __importStar5(require_errors());
    var TooManyRequestsError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "TooManyRequestsError",
          statusCode: 429,
          body
        });
        Object.setPrototypeOf(this, TooManyRequestsError.prototype);
      }
    };
    exports.TooManyRequestsError = TooManyRequestsError;
  }
});

// node_modules/cohere-ai/api/errors/ClientClosedRequestError.js
var require_ClientClosedRequestError = __commonJS({
  "node_modules/cohere-ai/api/errors/ClientClosedRequestError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClientClosedRequestError = void 0;
    var errors2 = __importStar5(require_errors());
    var ClientClosedRequestError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "ClientClosedRequestError",
          statusCode: 499,
          body
        });
        Object.setPrototypeOf(this, ClientClosedRequestError.prototype);
      }
    };
    exports.ClientClosedRequestError = ClientClosedRequestError;
  }
});

// node_modules/cohere-ai/api/errors/InternalServerError.js
var require_InternalServerError = __commonJS({
  "node_modules/cohere-ai/api/errors/InternalServerError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InternalServerError = void 0;
    var errors2 = __importStar5(require_errors());
    var InternalServerError6 = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "InternalServerError",
          statusCode: 500,
          body
        });
        Object.setPrototypeOf(this, InternalServerError6.prototype);
      }
    };
    exports.InternalServerError = InternalServerError6;
  }
});

// node_modules/cohere-ai/api/errors/NotImplementedError.js
var require_NotImplementedError = __commonJS({
  "node_modules/cohere-ai/api/errors/NotImplementedError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NotImplementedError = void 0;
    var errors2 = __importStar5(require_errors());
    var NotImplementedError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "NotImplementedError",
          statusCode: 501,
          body
        });
        Object.setPrototypeOf(this, NotImplementedError.prototype);
      }
    };
    exports.NotImplementedError = NotImplementedError;
  }
});

// node_modules/cohere-ai/api/errors/ServiceUnavailableError.js
var require_ServiceUnavailableError = __commonJS({
  "node_modules/cohere-ai/api/errors/ServiceUnavailableError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ServiceUnavailableError = void 0;
    var errors2 = __importStar5(require_errors());
    var ServiceUnavailableError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "ServiceUnavailableError",
          statusCode: 503,
          body
        });
        Object.setPrototypeOf(this, ServiceUnavailableError.prototype);
      }
    };
    exports.ServiceUnavailableError = ServiceUnavailableError;
  }
});

// node_modules/cohere-ai/api/errors/GatewayTimeoutError.js
var require_GatewayTimeoutError = __commonJS({
  "node_modules/cohere-ai/api/errors/GatewayTimeoutError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GatewayTimeoutError = void 0;
    var errors2 = __importStar5(require_errors());
    var GatewayTimeoutError = class extends errors2.CohereError {
      constructor(body) {
        super({
          message: "GatewayTimeoutError",
          statusCode: 504,
          body
        });
        Object.setPrototypeOf(this, GatewayTimeoutError.prototype);
      }
    };
    exports.GatewayTimeoutError = GatewayTimeoutError;
  }
});

// node_modules/cohere-ai/api/errors/index.js
var require_errors2 = __commonJS({
  "node_modules/cohere-ai/api/errors/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_BadRequestError(), exports);
    __exportStar5(require_UnauthorizedError(), exports);
    __exportStar5(require_ForbiddenError(), exports);
    __exportStar5(require_NotFoundError(), exports);
    __exportStar5(require_UnprocessableEntityError(), exports);
    __exportStar5(require_TooManyRequestsError(), exports);
    __exportStar5(require_ClientClosedRequestError(), exports);
    __exportStar5(require_InternalServerError(), exports);
    __exportStar5(require_NotImplementedError(), exports);
    __exportStar5(require_ServiceUnavailableError(), exports);
    __exportStar5(require_GatewayTimeoutError(), exports);
  }
});

// node_modules/cohere-ai/api/client/requests/index.js
var require_requests7 = __commonJS({
  "node_modules/cohere-ai/api/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/cohere-ai/api/client/index.js
var require_client8 = __commonJS({
  "node_modules/cohere-ai/api/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests7(), exports);
  }
});

// node_modules/cohere-ai/api/index.js
var require_api = __commonJS({
  "node_modules/cohere-ai/api/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_resources2(), exports);
    __exportStar5(require_types5(), exports);
    __exportStar5(require_errors2(), exports);
    __exportStar5(require_client8(), exports);
  }
});

// node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports = {};
__export(tslib_es6_exports, {
  __addDisposableResource: () => __addDisposableResource,
  __assign: () => __assign,
  __asyncDelegator: () => __asyncDelegator,
  __asyncGenerator: () => __asyncGenerator,
  __asyncValues: () => __asyncValues,
  __await: () => __await,
  __awaiter: () => __awaiter,
  __classPrivateFieldGet: () => __classPrivateFieldGet2,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet2,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values2,
  default: () => tslib_es6_default
});
function __extends(d3, b3) {
  if (typeof b3 !== "function" && b3 !== null)
    throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
  extendStatics(d3, b3);
  function __() {
    this.constructor = d3;
  }
  d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
}
function __rest(s4, e3) {
  var t3 = {};
  for (var p3 in s4)
    if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
      t3[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
      if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
        t3[p3[i3]] = s4[p3[i3]];
    }
  return t3;
}
function __decorate(decorators, target, key, desc) {
  var c4 = arguments.length, r4 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r4 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d3 = decorators[i3])
        r4 = (c4 < 3 ? d3(r4) : c4 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  return c4 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f3) {
    if (f3 !== void 0 && typeof f3 !== "function")
      throw new TypeError("Function expected");
    return f3;
  }
  var kind4 = contextIn.kind, key = kind4 === "getter" ? "get" : kind4 === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i3 = decorators.length - 1; i3 >= 0; i3--) {
    var context = {};
    for (var p3 in contextIn)
      context[p3] = p3 === "access" ? {} : contextIn[p3];
    for (var p3 in contextIn.access)
      context.access[p3] = contextIn.access[p3];
    context.addInitializer = function(f3) {
      if (done)
        throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f3 || null));
    };
    var result = (0, decorators[i3])(kind4 === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind4 === "accessor") {
      if (result === void 0)
        continue;
      if (result === null || typeof result !== "object")
        throw new TypeError("Object expected");
      if (_2 = accept(result.get))
        descriptor.get = _2;
      if (_2 = accept(result.set))
        descriptor.set = _2;
      if (_2 = accept(result.init))
        initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind4 === "field")
        initializers.unshift(_2);
      else
        descriptor[key] = _2;
    }
  }
  if (target)
    Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i3 = 0; i3 < initializers.length; i3++) {
    value = useValue ? initializers[i3].call(thisArg, value) : initializers[i3].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName(f3, name, prefix) {
  if (typeof name === "symbol")
    name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f3, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e3) {
        reject(e3);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e3) {
        reject(e3);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t3[0] & 1)
      throw t3[1];
    return t3[1];
  }, trys: [], ops: [] }, f3, y2, t3, g4 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g4.next = verb(0), g4["throw"] = verb(1), g4["return"] = verb(2), typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
    return this;
  }), g4;
  function verb(n4) {
    return function(v5) {
      return step([n4, v5]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
      try {
        if (f3 = 1, y2 && (t3 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t3 = y2["return"]) && t3.call(y2), 0) : y2.next) && !(t3 = t3.call(y2, op[1])).done)
          return t3;
        if (y2 = 0, t3)
          op = [op[0] & 2, t3.value];
        switch (op[0]) {
          case 0:
          case 1:
            t3 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y2 = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t3 = _2.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t3[1]) {
              _2.label = t3[1];
              t3 = op;
              break;
            }
            if (t3 && _2.label < t3[2]) {
              _2.label = t3[2];
              _2.ops.push(op);
              break;
            }
            if (t3[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e3) {
        op = [6, e3];
        y2 = 0;
      } finally {
        f3 = t3 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar(m3, o3) {
  for (var p3 in m3)
    if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3))
      __createBinding(o3, m3, p3);
}
function __values2(o3) {
  var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o3[s4], i3 = 0;
  if (m3)
    return m3.call(o3);
  if (o3 && typeof o3.length === "number")
    return {
      next: function() {
        if (o3 && i3 >= o3.length)
          o3 = void 0;
        return { value: o3 && o3[i3++], done: !o3 };
      }
    };
  throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o3, n4) {
  var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
  if (!m3)
    return o3;
  var i3 = m3.call(o3), r4, ar = [], e3;
  try {
    while ((n4 === void 0 || n4-- > 0) && !(r4 = i3.next()).done)
      ar.push(r4.value);
  } catch (error) {
    e3 = { error };
  } finally {
    try {
      if (r4 && !r4.done && (m3 = i3["return"]))
        m3.call(i3);
    } finally {
      if (e3)
        throw e3.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i3 = 0; i3 < arguments.length; i3++)
    ar = ar.concat(__read(arguments[i3]));
  return ar;
}
function __spreadArrays() {
  for (var s4 = 0, i3 = 0, il = arguments.length; i3 < il; i3++)
    s4 += arguments[i3].length;
  for (var r4 = Array(s4), k3 = 0, i3 = 0; i3 < il; i3++)
    for (var a3 = arguments[i3], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
      r4[k3] = a3[j3];
  return r4;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i3 = 0, l4 = from.length, ar; i3 < l4; i3++) {
      if (ar || !(i3 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i3);
        ar[i3] = from[i3];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v5) {
  return this instanceof __await ? (this.v = v5, this) : new __await(v5);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
  return i3 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function awaitReturn(f3) {
    return function(v5) {
      return Promise.resolve(v5).then(f3, reject);
    };
  }
  function verb(n4, f3) {
    if (g4[n4]) {
      i3[n4] = function(v5) {
        return new Promise(function(a3, b3) {
          q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
        });
      };
      if (f3)
        i3[n4] = f3(i3[n4]);
    }
  }
  function resume(n4, v5) {
    try {
      step(g4[n4](v5));
    } catch (e3) {
      settle(q3[0][3], e3);
    }
  }
  function step(r4) {
    r4.value instanceof __await ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v5) {
    if (f3(v5), q3.shift(), q3.length)
      resume(q3[0][0], q3[0][1]);
  }
}
function __asyncDelegator(o3) {
  var i3, p3;
  return i3 = {}, verb("next"), verb("throw", function(e3) {
    throw e3;
  }), verb("return"), i3[Symbol.iterator] = function() {
    return this;
  }, i3;
  function verb(n4, f3) {
    i3[n4] = o3[n4] ? function(v5) {
      return (p3 = !p3) ? { value: __await(o3[n4](v5)), done: false } : f3 ? f3(v5) : v5;
    } : f3;
  }
}
function __asyncValues(o3) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i3;
  return m3 ? m3.call(o3) : (o3 = typeof __values2 === "function" ? __values2(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3);
  function verb(n4) {
    i3[n4] = o3[n4] && function(v5) {
      return new Promise(function(resolve, reject) {
        v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
      });
    };
  }
  function settle(resolve, reject, d3, v5) {
    Promise.resolve(v5).then(function(v6) {
      resolve({ value: v6, done: d3 });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k3 in mod)
      if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
        __createBinding(result, mod, k3);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet2(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet2(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function")
    throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function")
      throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose)
        throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose)
        throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async)
        inner = dispose;
    }
    if (typeof dispose !== "function")
      throw new TypeError("Object not disposable.");
    if (inner)
      dispose = function() {
        try {
          inner.call(this);
        } catch (e3) {
          return Promise.reject(e3);
        }
      };
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env) {
  function fail(e3) {
    env.error = env.hasError ? new _SuppressedError(e3, env.error, "An error was suppressed during disposal.") : e3;
    env.hasError = true;
  }
  var r4, s4 = 0;
  function next() {
    while (r4 = env.stack.pop()) {
      try {
        if (!r4.async && s4 === 1)
          return s4 = 0, env.stack.push(r4), Promise.resolve().then(next);
        if (r4.dispose) {
          var result = r4.dispose.call(r4.value);
          if (r4.async)
            return s4 |= 2, Promise.resolve(result).then(next, function(e3) {
              fail(e3);
              return next();
            });
        } else
          s4 |= 1;
      } catch (e3) {
        fail(e3);
      }
    }
    if (s4 === 1)
      return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError)
      throw env.error;
  }
  return next();
}
var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics = function(d3, b3) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
        d4.__proto__ = b4;
      } || function(d4, b4) {
        for (var p3 in b4)
          if (Object.prototype.hasOwnProperty.call(b4, p3))
            d4[p3] = b4[p3];
      };
      return extendStatics(d3, b3);
    };
    __assign = function() {
      __assign = Object.assign || function __assign6(t3) {
        for (var s4, i3 = 1, n4 = arguments.length; i3 < n4; i3++) {
          s4 = arguments[i3];
          for (var p3 in s4)
            if (Object.prototype.hasOwnProperty.call(s4, p3))
              t3[p3] = s4[p3];
        }
        return t3;
      };
      return __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    };
    __setModuleDefault = Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    };
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e3 = new Error(message);
      return e3.name = "SuppressedError", e3.error = error, e3.suppressed = suppressed, e3;
    };
    tslib_es6_default = {
      __extends,
      __assign,
      __rest,
      __decorate,
      __param,
      __metadata,
      __awaiter,
      __generator,
      __createBinding,
      __exportStar,
      __values: __values2,
      __read,
      __spread,
      __spreadArrays,
      __spreadArray,
      __await,
      __asyncGenerator,
      __asyncDelegator,
      __asyncValues,
      __makeTemplateObject,
      __importStar,
      __importDefault,
      __classPrivateFieldGet: __classPrivateFieldGet2,
      __classPrivateFieldSet: __classPrivateFieldSet2,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources
    };
  }
});

// node_modules/@aws-crypto/sha256-js/build/main/constants.js
var require_constants2 = __commonJS({
  "node_modules/@aws-crypto/sha256-js/build/main/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MAX_HASHABLE_LENGTH = exports.INIT = exports.KEY = exports.DIGEST_LENGTH = exports.BLOCK_SIZE = void 0;
    exports.BLOCK_SIZE = 64;
    exports.DIGEST_LENGTH = 32;
    exports.KEY = new Uint32Array([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    exports.INIT = [
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ];
    exports.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;
  }
});

// node_modules/@aws-crypto/sha256-js/build/main/RawSha256.js
var require_RawSha256 = __commonJS({
  "node_modules/@aws-crypto/sha256-js/build/main/RawSha256.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RawSha256 = void 0;
    var constants_1 = require_constants2();
    var RawSha256 = (
      /** @class */
      function() {
        function RawSha2562() {
          this.state = Int32Array.from(constants_1.INIT);
          this.temp = new Int32Array(64);
          this.buffer = new Uint8Array(64);
          this.bufferLength = 0;
          this.bytesHashed = 0;
          this.finished = false;
        }
        RawSha2562.prototype.update = function(data) {
          if (this.finished) {
            throw new Error("Attempted to update an already finished hash.");
          }
          var position = 0;
          var byteLength = data.byteLength;
          this.bytesHashed += byteLength;
          if (this.bytesHashed * 8 > constants_1.MAX_HASHABLE_LENGTH) {
            throw new Error("Cannot hash more than 2^53 - 1 bits");
          }
          while (byteLength > 0) {
            this.buffer[this.bufferLength++] = data[position++];
            byteLength--;
            if (this.bufferLength === constants_1.BLOCK_SIZE) {
              this.hashBuffer();
              this.bufferLength = 0;
            }
          }
        };
        RawSha2562.prototype.digest = function() {
          if (!this.finished) {
            var bitsHashed = this.bytesHashed * 8;
            var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
            var undecoratedLength = this.bufferLength;
            bufferView.setUint8(this.bufferLength++, 128);
            if (undecoratedLength % constants_1.BLOCK_SIZE >= constants_1.BLOCK_SIZE - 8) {
              for (var i3 = this.bufferLength; i3 < constants_1.BLOCK_SIZE; i3++) {
                bufferView.setUint8(i3, 0);
              }
              this.hashBuffer();
              this.bufferLength = 0;
            }
            for (var i3 = this.bufferLength; i3 < constants_1.BLOCK_SIZE - 8; i3++) {
              bufferView.setUint8(i3, 0);
            }
            bufferView.setUint32(constants_1.BLOCK_SIZE - 8, Math.floor(bitsHashed / 4294967296), true);
            bufferView.setUint32(constants_1.BLOCK_SIZE - 4, bitsHashed);
            this.hashBuffer();
            this.finished = true;
          }
          var out = new Uint8Array(constants_1.DIGEST_LENGTH);
          for (var i3 = 0; i3 < 8; i3++) {
            out[i3 * 4] = this.state[i3] >>> 24 & 255;
            out[i3 * 4 + 1] = this.state[i3] >>> 16 & 255;
            out[i3 * 4 + 2] = this.state[i3] >>> 8 & 255;
            out[i3 * 4 + 3] = this.state[i3] >>> 0 & 255;
          }
          return out;
        };
        RawSha2562.prototype.hashBuffer = function() {
          var _a5 = this, buffer = _a5.buffer, state = _a5.state;
          var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];
          for (var i3 = 0; i3 < constants_1.BLOCK_SIZE; i3++) {
            if (i3 < 16) {
              this.temp[i3] = (buffer[i3 * 4] & 255) << 24 | (buffer[i3 * 4 + 1] & 255) << 16 | (buffer[i3 * 4 + 2] & 255) << 8 | buffer[i3 * 4 + 3] & 255;
            } else {
              var u3 = this.temp[i3 - 2];
              var t1_1 = (u3 >>> 17 | u3 << 15) ^ (u3 >>> 19 | u3 << 13) ^ u3 >>> 10;
              u3 = this.temp[i3 - 15];
              var t2_1 = (u3 >>> 7 | u3 << 25) ^ (u3 >>> 18 | u3 << 14) ^ u3 >>> 3;
              this.temp[i3] = (t1_1 + this.temp[i3 - 7] | 0) + (t2_1 + this.temp[i3 - 16] | 0);
            }
            var t1 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (constants_1.KEY[i3] + this.temp[i3] | 0) | 0) | 0;
            var t22 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0;
            state7 = state6;
            state6 = state5;
            state5 = state4;
            state4 = state3 + t1 | 0;
            state3 = state2;
            state2 = state1;
            state1 = state0;
            state0 = t1 + t22 | 0;
          }
          state[0] += state0;
          state[1] += state1;
          state[2] += state2;
          state[3] += state3;
          state[4] += state4;
          state[5] += state5;
          state[6] += state6;
          state[7] += state7;
        };
        return RawSha2562;
      }()
    );
    exports.RawSha256 = RawSha256;
  }
});

// node_modules/@smithy/is-array-buffer/dist-cjs/index.js
var require_dist_cjs = __commonJS({
  "node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports, module2) {
    var __defProp4 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp4(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp4(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp4({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      isArrayBuffer: () => isArrayBuffer2
    });
    module2.exports = __toCommonJS2(src_exports);
    var isArrayBuffer2 = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
  }
});

// node_modules/base64-js/index.js
var require_base64_js = __commonJS({
  "node_modules/base64-js/index.js"(exports) {
    "use strict";
    exports.byteLength = byteLength;
    exports.toByteArray = toByteArray;
    exports.fromByteArray = fromByteArray;
    var lookup2 = [];
    var revLookup = [];
    var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i3 = 0, len = code.length; i3 < len; ++i3) {
      lookup2[i3] = code[i3];
      revLookup[code.charCodeAt(i3)] = i3;
    }
    var i3;
    var len;
    revLookup["-".charCodeAt(0)] = 62;
    revLookup["_".charCodeAt(0)] = 63;
    function getLens(b64) {
      var len2 = b64.length;
      if (len2 % 4 > 0) {
        throw new Error("Invalid string. Length must be a multiple of 4");
      }
      var validLen = b64.indexOf("=");
      if (validLen === -1)
        validLen = len2;
      var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
      return [validLen, placeHoldersLen];
    }
    function byteLength(b64) {
      var lens = getLens(b64);
      var validLen = lens[0];
      var placeHoldersLen = lens[1];
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    function _byteLength(b64, validLen, placeHoldersLen) {
      return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
    }
    function toByteArray(b64) {
      var tmp;
      var lens = getLens(b64);
      var validLen = lens[0];
      var placeHoldersLen = lens[1];
      var arr2 = new Arr(_byteLength(b64, validLen, placeHoldersLen));
      var curByte = 0;
      var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
      var i4;
      for (i4 = 0; i4 < len2; i4 += 4) {
        tmp = revLookup[b64.charCodeAt(i4)] << 18 | revLookup[b64.charCodeAt(i4 + 1)] << 12 | revLookup[b64.charCodeAt(i4 + 2)] << 6 | revLookup[b64.charCodeAt(i4 + 3)];
        arr2[curByte++] = tmp >> 16 & 255;
        arr2[curByte++] = tmp >> 8 & 255;
        arr2[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 2) {
        tmp = revLookup[b64.charCodeAt(i4)] << 2 | revLookup[b64.charCodeAt(i4 + 1)] >> 4;
        arr2[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 1) {
        tmp = revLookup[b64.charCodeAt(i4)] << 10 | revLookup[b64.charCodeAt(i4 + 1)] << 4 | revLookup[b64.charCodeAt(i4 + 2)] >> 2;
        arr2[curByte++] = tmp >> 8 & 255;
        arr2[curByte++] = tmp & 255;
      }
      return arr2;
    }
    function tripletToBase64(num) {
      return lookup2[num >> 18 & 63] + lookup2[num >> 12 & 63] + lookup2[num >> 6 & 63] + lookup2[num & 63];
    }
    function encodeChunk(uint8, start, end) {
      var tmp;
      var output = [];
      for (var i4 = start; i4 < end; i4 += 3) {
        tmp = (uint8[i4] << 16 & 16711680) + (uint8[i4 + 1] << 8 & 65280) + (uint8[i4 + 2] & 255);
        output.push(tripletToBase64(tmp));
      }
      return output.join("");
    }
    function fromByteArray(uint8) {
      var tmp;
      var len2 = uint8.length;
      var extraBytes = len2 % 3;
      var parts = [];
      var maxChunkLength = 16383;
      for (var i4 = 0, len22 = len2 - extraBytes; i4 < len22; i4 += maxChunkLength) {
        parts.push(encodeChunk(uint8, i4, i4 + maxChunkLength > len22 ? len22 : i4 + maxChunkLength));
      }
      if (extraBytes === 1) {
        tmp = uint8[len2 - 1];
        parts.push(
          lookup2[tmp >> 2] + lookup2[tmp << 4 & 63] + "=="
        );
      } else if (extraBytes === 2) {
        tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
        parts.push(
          lookup2[tmp >> 10] + lookup2[tmp >> 4 & 63] + lookup2[tmp << 2 & 63] + "="
        );
      }
      return parts.join("");
    }
  }
});

// node_modules/ieee754/index.js
var require_ieee754 = __commonJS({
  "node_modules/ieee754/index.js"(exports) {
    exports.read = function(buffer, offset5, isLE, mLen, nBytes) {
      var e3, m3;
      var eLen = nBytes * 8 - mLen - 1;
      var eMax = (1 << eLen) - 1;
      var eBias = eMax >> 1;
      var nBits = -7;
      var i3 = isLE ? nBytes - 1 : 0;
      var d3 = isLE ? -1 : 1;
      var s4 = buffer[offset5 + i3];
      i3 += d3;
      e3 = s4 & (1 << -nBits) - 1;
      s4 >>= -nBits;
      nBits += eLen;
      for (; nBits > 0; e3 = e3 * 256 + buffer[offset5 + i3], i3 += d3, nBits -= 8) {
      }
      m3 = e3 & (1 << -nBits) - 1;
      e3 >>= -nBits;
      nBits += mLen;
      for (; nBits > 0; m3 = m3 * 256 + buffer[offset5 + i3], i3 += d3, nBits -= 8) {
      }
      if (e3 === 0) {
        e3 = 1 - eBias;
      } else if (e3 === eMax) {
        return m3 ? NaN : (s4 ? -1 : 1) * Infinity;
      } else {
        m3 = m3 + Math.pow(2, mLen);
        e3 = e3 - eBias;
      }
      return (s4 ? -1 : 1) * m3 * Math.pow(2, e3 - mLen);
    };
    exports.write = function(buffer, value, offset5, isLE, mLen, nBytes) {
      var e3, m3, c4;
      var eLen = nBytes * 8 - mLen - 1;
      var eMax = (1 << eLen) - 1;
      var eBias = eMax >> 1;
      var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
      var i3 = isLE ? 0 : nBytes - 1;
      var d3 = isLE ? 1 : -1;
      var s4 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
      value = Math.abs(value);
      if (isNaN(value) || value === Infinity) {
        m3 = isNaN(value) ? 1 : 0;
        e3 = eMax;
      } else {
        e3 = Math.floor(Math.log(value) / Math.LN2);
        if (value * (c4 = Math.pow(2, -e3)) < 1) {
          e3--;
          c4 *= 2;
        }
        if (e3 + eBias >= 1) {
          value += rt / c4;
        } else {
          value += rt * Math.pow(2, 1 - eBias);
        }
        if (value * c4 >= 2) {
          e3++;
          c4 /= 2;
        }
        if (e3 + eBias >= eMax) {
          m3 = 0;
          e3 = eMax;
        } else if (e3 + eBias >= 1) {
          m3 = (value * c4 - 1) * Math.pow(2, mLen);
          e3 = e3 + eBias;
        } else {
          m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
          e3 = 0;
        }
      }
      for (; mLen >= 8; buffer[offset5 + i3] = m3 & 255, i3 += d3, m3 /= 256, mLen -= 8) {
      }
      e3 = e3 << mLen | m3;
      eLen += mLen;
      for (; eLen > 0; buffer[offset5 + i3] = e3 & 255, i3 += d3, e3 /= 256, eLen -= 8) {
      }
      buffer[offset5 + i3 - d3] |= s4 * 128;
    };
  }
});

// node_modules/buffer/index.js
var require_buffer = __commonJS({
  "node_modules/buffer/index.js"(exports) {
    "use strict";
    var base642 = require_base64_js();
    var ieee754 = require_ieee754();
    var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
    exports.Buffer = Buffer2;
    exports.SlowBuffer = SlowBuffer;
    exports.INSPECT_MAX_BYTES = 50;
    var K_MAX_LENGTH = 2147483647;
    exports.kMaxLength = K_MAX_LENGTH;
    Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
    if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
      console.error(
        "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
      );
    }
    function typedArraySupport() {
      try {
        const arr2 = new Uint8Array(1);
        const proto = { foo: function() {
          return 42;
        } };
        Object.setPrototypeOf(proto, Uint8Array.prototype);
        Object.setPrototypeOf(arr2, proto);
        return arr2.foo() === 42;
      } catch (e3) {
        return false;
      }
    }
    Object.defineProperty(Buffer2.prototype, "parent", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this))
          return void 0;
        return this.buffer;
      }
    });
    Object.defineProperty(Buffer2.prototype, "offset", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this))
          return void 0;
        return this.byteOffset;
      }
    });
    function createBuffer(length) {
      if (length > K_MAX_LENGTH) {
        throw new RangeError('The value "' + length + '" is invalid for option "size"');
      }
      const buf = new Uint8Array(length);
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function Buffer2(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        if (typeof encodingOrOffset === "string") {
          throw new TypeError(
            'The "string" argument must be of type string. Received type number'
          );
        }
        return allocUnsafe(arg);
      }
      return from(arg, encodingOrOffset, length);
    }
    Buffer2.poolSize = 8192;
    function from(value, encodingOrOffset, length) {
      if (typeof value === "string") {
        return fromString(value, encodingOrOffset);
      }
      if (ArrayBuffer.isView(value)) {
        return fromArrayView(value);
      }
      if (value == null) {
        throw new TypeError(
          "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
        );
      }
      if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof value === "number") {
        throw new TypeError(
          'The "value" argument must not be of type number. Received type number'
        );
      }
      const valueOf = value.valueOf && value.valueOf();
      if (valueOf != null && valueOf !== value) {
        return Buffer2.from(valueOf, encodingOrOffset, length);
      }
      const b3 = fromObject(value);
      if (b3)
        return b3;
      if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
        return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
      }
      throw new TypeError(
        "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
      );
    }
    Buffer2.from = function(value, encodingOrOffset, length) {
      return from(value, encodingOrOffset, length);
    };
    Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
    Object.setPrototypeOf(Buffer2, Uint8Array);
    function assertSize(size4) {
      if (typeof size4 !== "number") {
        throw new TypeError('"size" argument must be of type number');
      } else if (size4 < 0) {
        throw new RangeError('The value "' + size4 + '" is invalid for option "size"');
      }
    }
    function alloc(size4, fill, encoding) {
      assertSize(size4);
      if (size4 <= 0) {
        return createBuffer(size4);
      }
      if (fill !== void 0) {
        return typeof encoding === "string" ? createBuffer(size4).fill(fill, encoding) : createBuffer(size4).fill(fill);
      }
      return createBuffer(size4);
    }
    Buffer2.alloc = function(size4, fill, encoding) {
      return alloc(size4, fill, encoding);
    };
    function allocUnsafe(size4) {
      assertSize(size4);
      return createBuffer(size4 < 0 ? 0 : checked(size4) | 0);
    }
    Buffer2.allocUnsafe = function(size4) {
      return allocUnsafe(size4);
    };
    Buffer2.allocUnsafeSlow = function(size4) {
      return allocUnsafe(size4);
    };
    function fromString(string, encoding) {
      if (typeof encoding !== "string" || encoding === "") {
        encoding = "utf8";
      }
      if (!Buffer2.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      const length = byteLength(string, encoding) | 0;
      let buf = createBuffer(length);
      const actual = buf.write(string, encoding);
      if (actual !== length) {
        buf = buf.slice(0, actual);
      }
      return buf;
    }
    function fromArrayLike(array) {
      const length = array.length < 0 ? 0 : checked(array.length) | 0;
      const buf = createBuffer(length);
      for (let i3 = 0; i3 < length; i3 += 1) {
        buf[i3] = array[i3] & 255;
      }
      return buf;
    }
    function fromArrayView(arrayView) {
      if (isInstance(arrayView, Uint8Array)) {
        const copy = new Uint8Array(arrayView);
        return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
      }
      return fromArrayLike(arrayView);
    }
    function fromArrayBuffer(array, byteOffset, length) {
      if (byteOffset < 0 || array.byteLength < byteOffset) {
        throw new RangeError('"offset" is outside of buffer bounds');
      }
      if (array.byteLength < byteOffset + (length || 0)) {
        throw new RangeError('"length" is outside of buffer bounds');
      }
      let buf;
      if (byteOffset === void 0 && length === void 0) {
        buf = new Uint8Array(array);
      } else if (length === void 0) {
        buf = new Uint8Array(array, byteOffset);
      } else {
        buf = new Uint8Array(array, byteOffset, length);
      }
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function fromObject(obj) {
      if (Buffer2.isBuffer(obj)) {
        const len = checked(obj.length) | 0;
        const buf = createBuffer(len);
        if (buf.length === 0) {
          return buf;
        }
        obj.copy(buf, 0, 0, len);
        return buf;
      }
      if (obj.length !== void 0) {
        if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
          return createBuffer(0);
        }
        return fromArrayLike(obj);
      }
      if (obj.type === "Buffer" && Array.isArray(obj.data)) {
        return fromArrayLike(obj.data);
      }
    }
    function checked(length) {
      if (length >= K_MAX_LENGTH) {
        throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
      }
      return length | 0;
    }
    function SlowBuffer(length) {
      if (+length != length) {
        length = 0;
      }
      return Buffer2.alloc(+length);
    }
    Buffer2.isBuffer = function isBuffer(b3) {
      return b3 != null && b3._isBuffer === true && b3 !== Buffer2.prototype;
    };
    Buffer2.compare = function compare2(a3, b3) {
      if (isInstance(a3, Uint8Array))
        a3 = Buffer2.from(a3, a3.offset, a3.byteLength);
      if (isInstance(b3, Uint8Array))
        b3 = Buffer2.from(b3, b3.offset, b3.byteLength);
      if (!Buffer2.isBuffer(a3) || !Buffer2.isBuffer(b3)) {
        throw new TypeError(
          'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
        );
      }
      if (a3 === b3)
        return 0;
      let x2 = a3.length;
      let y2 = b3.length;
      for (let i3 = 0, len = Math.min(x2, y2); i3 < len; ++i3) {
        if (a3[i3] !== b3[i3]) {
          x2 = a3[i3];
          y2 = b3[i3];
          break;
        }
      }
      if (x2 < y2)
        return -1;
      if (y2 < x2)
        return 1;
      return 0;
    };
    Buffer2.isEncoding = function isEncoding(encoding) {
      switch (String(encoding).toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "latin1":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return true;
        default:
          return false;
      }
    };
    Buffer2.concat = function concat2(list, length) {
      if (!Array.isArray(list)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      }
      if (list.length === 0) {
        return Buffer2.alloc(0);
      }
      let i3;
      if (length === void 0) {
        length = 0;
        for (i3 = 0; i3 < list.length; ++i3) {
          length += list[i3].length;
        }
      }
      const buffer = Buffer2.allocUnsafe(length);
      let pos = 0;
      for (i3 = 0; i3 < list.length; ++i3) {
        let buf = list[i3];
        if (isInstance(buf, Uint8Array)) {
          if (pos + buf.length > buffer.length) {
            if (!Buffer2.isBuffer(buf))
              buf = Buffer2.from(buf);
            buf.copy(buffer, pos);
          } else {
            Uint8Array.prototype.set.call(
              buffer,
              buf,
              pos
            );
          }
        } else if (!Buffer2.isBuffer(buf)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        } else {
          buf.copy(buffer, pos);
        }
        pos += buf.length;
      }
      return buffer;
    };
    function byteLength(string, encoding) {
      if (Buffer2.isBuffer(string)) {
        return string.length;
      }
      if (ArrayBuffer.isView(string) || 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;
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "ascii":
          case "latin1":
          case "binary":
            return len;
          case "utf8":
          case "utf-8":
            return utf8ToBytes(string).length;
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return len * 2;
          case "hex":
            return len >>> 1;
          case "base64":
            return base64ToBytes(string).length;
          default:
            if (loweredCase) {
              return mustMatch ? -1 : utf8ToBytes(string).length;
            }
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.byteLength = byteLength;
    function slowToString(encoding, start, end) {
      let loweredCase = false;
      if (start === void 0 || start < 0) {
        start = 0;
      }
      if (start > this.length) {
        return "";
      }
      if (end === void 0 || end > this.length) {
        end = this.length;
      }
      if (end <= 0) {
        return "";
      }
      end >>>= 0;
      start >>>= 0;
      if (end <= start) {
        return "";
      }
      if (!encoding)
        encoding = "utf8";
      while (true) {
        switch (encoding) {
          case "hex":
            return hexSlice(this, start, end);
          case "utf8":
          case "utf-8":
            return utf8Slice(this, start, end);
          case "ascii":
            return asciiSlice(this, start, end);
          case "latin1":
          case "binary":
            return latin1Slice(this, start, end);
          case "base64":
            return base64Slice(this, start, end);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return utf16leSlice(this, start, end);
          default:
            if (loweredCase)
              throw new TypeError("Unknown encoding: " + encoding);
            encoding = (encoding + "").toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.prototype._isBuffer = true;
    function swap(b3, n4, m3) {
      const i3 = b3[n4];
      b3[n4] = b3[m3];
      b3[m3] = i3;
    }
    Buffer2.prototype.swap16 = function swap16() {
      const len = this.length;
      if (len % 2 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 16-bits");
      }
      for (let i3 = 0; i3 < len; i3 += 2) {
        swap(this, i3, i3 + 1);
      }
      return this;
    };
    Buffer2.prototype.swap32 = function swap32() {
      const len = this.length;
      if (len % 4 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 32-bits");
      }
      for (let i3 = 0; i3 < len; i3 += 4) {
        swap(this, i3, i3 + 3);
        swap(this, i3 + 1, i3 + 2);
      }
      return this;
    };
    Buffer2.prototype.swap64 = function swap64() {
      const len = this.length;
      if (len % 8 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 64-bits");
      }
      for (let i3 = 0; i3 < len; i3 += 8) {
        swap(this, i3, i3 + 7);
        swap(this, i3 + 1, i3 + 6);
        swap(this, i3 + 2, i3 + 5);
        swap(this, i3 + 3, i3 + 4);
      }
      return this;
    };
    Buffer2.prototype.toString = function toString() {
      const length = this.length;
      if (length === 0)
        return "";
      if (arguments.length === 0)
        return utf8Slice(this, 0, length);
      return slowToString.apply(this, arguments);
    };
    Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
    Buffer2.prototype.equals = function equals(b3) {
      if (!Buffer2.isBuffer(b3))
        throw new TypeError("Argument must be a Buffer");
      if (this === b3)
        return true;
      return Buffer2.compare(this, b3) === 0;
    };
    Buffer2.prototype.inspect = function inspect() {
      let str2 = "";
      const max2 = exports.INSPECT_MAX_BYTES;
      str2 = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim();
      if (this.length > max2)
        str2 += " ... ";
      return "<Buffer " + str2 + ">";
    };
    if (customInspectSymbol) {
      Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
    }
    Buffer2.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) {
      if (isInstance(target, Uint8Array)) {
        target = Buffer2.from(target, target.offset, target.byteLength);
      }
      if (!Buffer2.isBuffer(target)) {
        throw new TypeError(
          'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
        );
      }
      if (start === void 0) {
        start = 0;
      }
      if (end === void 0) {
        end = target ? target.length : 0;
      }
      if (thisStart === void 0) {
        thisStart = 0;
      }
      if (thisEnd === void 0) {
        thisEnd = this.length;
      }
      if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
        throw new RangeError("out of range index");
      }
      if (thisStart >= thisEnd && start >= end) {
        return 0;
      }
      if (thisStart >= thisEnd) {
        return -1;
      }
      if (start >= end) {
        return 1;
      }
      start >>>= 0;
      end >>>= 0;
      thisStart >>>= 0;
      thisEnd >>>= 0;
      if (this === target)
        return 0;
      let x2 = thisEnd - thisStart;
      let y2 = end - start;
      const len = Math.min(x2, y2);
      const thisCopy = this.slice(thisStart, thisEnd);
      const targetCopy = target.slice(start, end);
      for (let i3 = 0; i3 < len; ++i3) {
        if (thisCopy[i3] !== targetCopy[i3]) {
          x2 = thisCopy[i3];
          y2 = targetCopy[i3];
          break;
        }
      }
      if (x2 < y2)
        return -1;
      if (y2 < x2)
        return 1;
      return 0;
    };
    function bidirectionalIndexOf(buffer, val2, byteOffset, encoding, dir) {
      if (buffer.length === 0)
        return -1;
      if (typeof byteOffset === "string") {
        encoding = byteOffset;
        byteOffset = 0;
      } else if (byteOffset > 2147483647) {
        byteOffset = 2147483647;
      } else if (byteOffset < -2147483648) {
        byteOffset = -2147483648;
      }
      byteOffset = +byteOffset;
      if (numberIsNaN(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 val2 === "string") {
        val2 = Buffer2.from(val2, encoding);
      }
      if (Buffer2.isBuffer(val2)) {
        if (val2.length === 0) {
          return -1;
        }
        return arrayIndexOf(buffer, val2, byteOffset, encoding, dir);
      } else if (typeof val2 === "number") {
        val2 = val2 & 255;
        if (typeof Uint8Array.prototype.indexOf === "function") {
          if (dir) {
            return Uint8Array.prototype.indexOf.call(buffer, val2, byteOffset);
          } else {
            return Uint8Array.prototype.lastIndexOf.call(buffer, val2, byteOffset);
          }
        }
        return arrayIndexOf(buffer, [val2], byteOffset, encoding, dir);
      }
      throw new TypeError("val must be string, number or Buffer");
    }
    function arrayIndexOf(arr2, val2, byteOffset, encoding, dir) {
      let indexSize = 1;
      let arrLength = arr2.length;
      let valLength = val2.length;
      if (encoding !== void 0) {
        encoding = String(encoding).toLowerCase();
        if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
          if (arr2.length < 2 || val2.length < 2) {
            return -1;
          }
          indexSize = 2;
          arrLength /= 2;
          valLength /= 2;
          byteOffset /= 2;
        }
      }
      function read(buf, i4) {
        if (indexSize === 1) {
          return buf[i4];
        } else {
          return buf.readUInt16BE(i4 * indexSize);
        }
      }
      let i3;
      if (dir) {
        let foundIndex = -1;
        for (i3 = byteOffset; i3 < arrLength; i3++) {
          if (read(arr2, i3) === read(val2, foundIndex === -1 ? 0 : i3 - foundIndex)) {
            if (foundIndex === -1)
              foundIndex = i3;
            if (i3 - foundIndex + 1 === valLength)
              return foundIndex * indexSize;
          } else {
            if (foundIndex !== -1)
              i3 -= i3 - foundIndex;
            foundIndex = -1;
          }
        }
      } else {
        if (byteOffset + valLength > arrLength)
          byteOffset = arrLength - valLength;
        for (i3 = byteOffset; i3 >= 0; i3--) {
          let found = true;
          for (let j3 = 0; j3 < valLength; j3++) {
            if (read(arr2, i3 + j3) !== read(val2, j3)) {
              found = false;
              break;
            }
          }
          if (found)
            return i3;
        }
      }
      return -1;
    }
    Buffer2.prototype.includes = function includes(val2, byteOffset, encoding) {
      return this.indexOf(val2, byteOffset, encoding) !== -1;
    };
    Buffer2.prototype.indexOf = function indexOf(val2, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val2, byteOffset, encoding, true);
    };
    Buffer2.prototype.lastIndexOf = function lastIndexOf(val2, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val2, byteOffset, encoding, false);
    };
    function hexWrite(buf, string, offset5, length) {
      offset5 = Number(offset5) || 0;
      const remaining = buf.length - offset5;
      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 i3;
      for (i3 = 0; i3 < length; ++i3) {
        const parsed = parseInt(string.substr(i3 * 2, 2), 16);
        if (numberIsNaN(parsed))
          return i3;
        buf[offset5 + i3] = parsed;
      }
      return i3;
    }
    function utf8Write(buf, string, offset5, length) {
      return blitBuffer(utf8ToBytes(string, buf.length - offset5), buf, offset5, length);
    }
    function asciiWrite(buf, string, offset5, length) {
      return blitBuffer(asciiToBytes(string), buf, offset5, length);
    }
    function base64Write(buf, string, offset5, length) {
      return blitBuffer(base64ToBytes(string), buf, offset5, length);
    }
    function ucs2Write(buf, string, offset5, length) {
      return blitBuffer(utf16leToBytes(string, buf.length - offset5), buf, offset5, length);
    }
    Buffer2.prototype.write = function write(string, offset5, length, encoding) {
      if (offset5 === void 0) {
        encoding = "utf8";
        length = this.length;
        offset5 = 0;
      } else if (length === void 0 && typeof offset5 === "string") {
        encoding = offset5;
        length = this.length;
        offset5 = 0;
      } else if (isFinite(offset5)) {
        offset5 = offset5 >>> 0;
        if (isFinite(length)) {
          length = length >>> 0;
          if (encoding === void 0)
            encoding = "utf8";
        } else {
          encoding = length;
          length = void 0;
        }
      } else {
        throw new Error(
          "Buffer.write(string, encoding, offset[, length]) is no longer supported"
        );
      }
      const remaining = this.length - offset5;
      if (length === void 0 || length > remaining)
        length = remaining;
      if (string.length > 0 && (length < 0 || offset5 < 0) || offset5 > this.length) {
        throw new RangeError("Attempt to write outside buffer bounds");
      }
      if (!encoding)
        encoding = "utf8";
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "hex":
            return hexWrite(this, string, offset5, length);
          case "utf8":
          case "utf-8":
            return utf8Write(this, string, offset5, length);
          case "ascii":
          case "latin1":
          case "binary":
            return asciiWrite(this, string, offset5, length);
          case "base64":
            return base64Write(this, string, offset5, length);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return ucs2Write(this, string, offset5, length);
          default:
            if (loweredCase)
              throw new TypeError("Unknown encoding: " + encoding);
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    };
    Buffer2.prototype.toJSON = function toJSON() {
      return {
        type: "Buffer",
        data: Array.prototype.slice.call(this._arr || this, 0)
      };
    };
    function base64Slice(buf, start, end) {
      if (start === 0 && end === buf.length) {
        return base642.fromByteArray(buf);
      } else {
        return base642.fromByteArray(buf.slice(start, end));
      }
    }
    function utf8Slice(buf, start, end) {
      end = Math.min(buf.length, end);
      const res = [];
      let i3 = start;
      while (i3 < end) {
        const firstByte = buf[i3];
        let codePoint = null;
        let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
        if (i3 + bytesPerSequence <= end) {
          let secondByte, thirdByte, fourthByte, tempCodePoint;
          switch (bytesPerSequence) {
            case 1:
              if (firstByte < 128) {
                codePoint = firstByte;
              }
              break;
            case 2:
              secondByte = buf[i3 + 1];
              if ((secondByte & 192) === 128) {
                tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                if (tempCodePoint > 127) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 3:
              secondByte = buf[i3 + 1];
              thirdByte = buf[i3 + 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[i3 + 1];
              thirdByte = buf[i3 + 2];
              fourthByte = buf[i3 + 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);
        i3 += bytesPerSequence;
      }
      return decodeCodePointsArray(res);
    }
    var MAX_ARGUMENTS_LENGTH = 4096;
    function decodeCodePointsArray(codePoints) {
      const len = codePoints.length;
      if (len <= MAX_ARGUMENTS_LENGTH) {
        return String.fromCharCode.apply(String, codePoints);
      }
      let res = "";
      let i3 = 0;
      while (i3 < len) {
        res += String.fromCharCode.apply(
          String,
          codePoints.slice(i3, i3 += MAX_ARGUMENTS_LENGTH)
        );
      }
      return res;
    }
    function asciiSlice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i3 = start; i3 < end; ++i3) {
        ret += String.fromCharCode(buf[i3] & 127);
      }
      return ret;
    }
    function latin1Slice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i3 = start; i3 < end; ++i3) {
        ret += String.fromCharCode(buf[i3]);
      }
      return ret;
    }
    function hexSlice(buf, start, end) {
      const len = buf.length;
      if (!start || start < 0)
        start = 0;
      if (!end || end < 0 || end > len)
        end = len;
      let out = "";
      for (let i3 = start; i3 < end; ++i3) {
        out += hexSliceLookupTable[buf[i3]];
      }
      return out;
    }
    function utf16leSlice(buf, start, end) {
      const bytes = buf.slice(start, end);
      let res = "";
      for (let i3 = 0; i3 < bytes.length - 1; i3 += 2) {
        res += String.fromCharCode(bytes[i3] + bytes[i3 + 1] * 256);
      }
      return res;
    }
    Buffer2.prototype.slice = function slice(start, end) {
      const len = this.length;
      start = ~~start;
      end = end === void 0 ? len : ~~end;
      if (start < 0) {
        start += len;
        if (start < 0)
          start = 0;
      } else if (start > len) {
        start = len;
      }
      if (end < 0) {
        end += len;
        if (end < 0)
          end = 0;
      } else if (end > len) {
        end = len;
      }
      if (end < start)
        end = start;
      const newBuf = this.subarray(start, end);
      Object.setPrototypeOf(newBuf, Buffer2.prototype);
      return newBuf;
    };
    function checkOffset(offset5, ext, length) {
      if (offset5 % 1 !== 0 || offset5 < 0)
        throw new RangeError("offset is not uint");
      if (offset5 + ext > length)
        throw new RangeError("Trying to access beyond buffer length");
    }
    Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset5, byteLength2, noAssert) {
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert)
        checkOffset(offset5, byteLength2, this.length);
      let val2 = this[offset5];
      let mul = 1;
      let i3 = 0;
      while (++i3 < byteLength2 && (mul *= 256)) {
        val2 += this[offset5 + i3] * mul;
      }
      return val2;
    };
    Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset5, byteLength2, noAssert) {
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert) {
        checkOffset(offset5, byteLength2, this.length);
      }
      let val2 = this[offset5 + --byteLength2];
      let mul = 1;
      while (byteLength2 > 0 && (mul *= 256)) {
        val2 += this[offset5 + --byteLength2] * mul;
      }
      return val2;
    };
    Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 1, this.length);
      return this[offset5];
    };
    Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 2, this.length);
      return this[offset5] | this[offset5 + 1] << 8;
    };
    Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 2, this.length);
      return this[offset5] << 8 | this[offset5 + 1];
    };
    Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return (this[offset5] | this[offset5 + 1] << 8 | this[offset5 + 2] << 16) + this[offset5 + 3] * 16777216;
    };
    Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return this[offset5] * 16777216 + (this[offset5 + 1] << 16 | this[offset5 + 2] << 8 | this[offset5 + 3]);
    };
    Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset5) {
      offset5 = offset5 >>> 0;
      validateNumber(offset5, "offset");
      const first = this[offset5];
      const last = this[offset5 + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset5, this.length - 8);
      }
      const lo = first + this[++offset5] * 2 ** 8 + this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 24;
      const hi = this[++offset5] + this[++offset5] * 2 ** 8 + this[++offset5] * 2 ** 16 + last * 2 ** 24;
      return BigInt(lo) + (BigInt(hi) << BigInt(32));
    });
    Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset5) {
      offset5 = offset5 >>> 0;
      validateNumber(offset5, "offset");
      const first = this[offset5];
      const last = this[offset5 + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset5, this.length - 8);
      }
      const hi = first * 2 ** 24 + this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 8 + this[++offset5];
      const lo = this[++offset5] * 2 ** 24 + this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 8 + last;
      return (BigInt(hi) << BigInt(32)) + BigInt(lo);
    });
    Buffer2.prototype.readIntLE = function readIntLE(offset5, byteLength2, noAssert) {
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert)
        checkOffset(offset5, byteLength2, this.length);
      let val2 = this[offset5];
      let mul = 1;
      let i3 = 0;
      while (++i3 < byteLength2 && (mul *= 256)) {
        val2 += this[offset5 + i3] * mul;
      }
      mul *= 128;
      if (val2 >= mul)
        val2 -= Math.pow(2, 8 * byteLength2);
      return val2;
    };
    Buffer2.prototype.readIntBE = function readIntBE(offset5, byteLength2, noAssert) {
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert)
        checkOffset(offset5, byteLength2, this.length);
      let i3 = byteLength2;
      let mul = 1;
      let val2 = this[offset5 + --i3];
      while (i3 > 0 && (mul *= 256)) {
        val2 += this[offset5 + --i3] * mul;
      }
      mul *= 128;
      if (val2 >= mul)
        val2 -= Math.pow(2, 8 * byteLength2);
      return val2;
    };
    Buffer2.prototype.readInt8 = function readInt8(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 1, this.length);
      if (!(this[offset5] & 128))
        return this[offset5];
      return (255 - this[offset5] + 1) * -1;
    };
    Buffer2.prototype.readInt16LE = function readInt16LE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 2, this.length);
      const val2 = this[offset5] | this[offset5 + 1] << 8;
      return val2 & 32768 ? val2 | 4294901760 : val2;
    };
    Buffer2.prototype.readInt16BE = function readInt16BE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 2, this.length);
      const val2 = this[offset5 + 1] | this[offset5] << 8;
      return val2 & 32768 ? val2 | 4294901760 : val2;
    };
    Buffer2.prototype.readInt32LE = function readInt32LE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return this[offset5] | this[offset5 + 1] << 8 | this[offset5 + 2] << 16 | this[offset5 + 3] << 24;
    };
    Buffer2.prototype.readInt32BE = function readInt32BE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return this[offset5] << 24 | this[offset5 + 1] << 16 | this[offset5 + 2] << 8 | this[offset5 + 3];
    };
    Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset5) {
      offset5 = offset5 >>> 0;
      validateNumber(offset5, "offset");
      const first = this[offset5];
      const last = this[offset5 + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset5, this.length - 8);
      }
      const val2 = this[offset5 + 4] + this[offset5 + 5] * 2 ** 8 + this[offset5 + 6] * 2 ** 16 + (last << 24);
      return (BigInt(val2) << BigInt(32)) + BigInt(first + this[++offset5] * 2 ** 8 + this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 24);
    });
    Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset5) {
      offset5 = offset5 >>> 0;
      validateNumber(offset5, "offset");
      const first = this[offset5];
      const last = this[offset5 + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset5, this.length - 8);
      }
      const val2 = (first << 24) + // Overflow
      this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 8 + this[++offset5];
      return (BigInt(val2) << BigInt(32)) + BigInt(this[++offset5] * 2 ** 24 + this[++offset5] * 2 ** 16 + this[++offset5] * 2 ** 8 + last);
    });
    Buffer2.prototype.readFloatLE = function readFloatLE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return ieee754.read(this, offset5, true, 23, 4);
    };
    Buffer2.prototype.readFloatBE = function readFloatBE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 4, this.length);
      return ieee754.read(this, offset5, false, 23, 4);
    };
    Buffer2.prototype.readDoubleLE = function readDoubleLE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 8, this.length);
      return ieee754.read(this, offset5, true, 52, 8);
    };
    Buffer2.prototype.readDoubleBE = function readDoubleBE(offset5, noAssert) {
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkOffset(offset5, 8, this.length);
      return ieee754.read(this, offset5, false, 52, 8);
    };
    function checkInt(buf, value, offset5, ext, max2, min2) {
      if (!Buffer2.isBuffer(buf))
        throw new TypeError('"buffer" argument must be a Buffer instance');
      if (value > max2 || value < min2)
        throw new RangeError('"value" argument is out of bounds');
      if (offset5 + ext > buf.length)
        throw new RangeError("Index out of range");
    }
    Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset5, byteLength2, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
        checkInt(this, value, offset5, byteLength2, maxBytes, 0);
      }
      let mul = 1;
      let i3 = 0;
      this[offset5] = value & 255;
      while (++i3 < byteLength2 && (mul *= 256)) {
        this[offset5 + i3] = value / mul & 255;
      }
      return offset5 + byteLength2;
    };
    Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset5, byteLength2, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      byteLength2 = byteLength2 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
        checkInt(this, value, offset5, byteLength2, maxBytes, 0);
      }
      let i3 = byteLength2 - 1;
      let mul = 1;
      this[offset5 + i3] = value & 255;
      while (--i3 >= 0 && (mul *= 256)) {
        this[offset5 + i3] = value / mul & 255;
      }
      return offset5 + byteLength2;
    };
    Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 1, 255, 0);
      this[offset5] = value & 255;
      return offset5 + 1;
    };
    Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 2, 65535, 0);
      this[offset5] = value & 255;
      this[offset5 + 1] = value >>> 8;
      return offset5 + 2;
    };
    Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 2, 65535, 0);
      this[offset5] = value >>> 8;
      this[offset5 + 1] = value & 255;
      return offset5 + 2;
    };
    Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 4, 4294967295, 0);
      this[offset5 + 3] = value >>> 24;
      this[offset5 + 2] = value >>> 16;
      this[offset5 + 1] = value >>> 8;
      this[offset5] = value & 255;
      return offset5 + 4;
    };
    Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 4, 4294967295, 0);
      this[offset5] = value >>> 24;
      this[offset5 + 1] = value >>> 16;
      this[offset5 + 2] = value >>> 8;
      this[offset5 + 3] = value & 255;
      return offset5 + 4;
    };
    function wrtBigUInt64LE(buf, value, offset5, min2, max2) {
      checkIntBI(value, min2, max2, buf, offset5, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset5++] = lo;
      lo = lo >> 8;
      buf[offset5++] = lo;
      lo = lo >> 8;
      buf[offset5++] = lo;
      lo = lo >> 8;
      buf[offset5++] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset5++] = hi;
      hi = hi >> 8;
      buf[offset5++] = hi;
      hi = hi >> 8;
      buf[offset5++] = hi;
      hi = hi >> 8;
      buf[offset5++] = hi;
      return offset5;
    }
    function wrtBigUInt64BE(buf, value, offset5, min2, max2) {
      checkIntBI(value, min2, max2, buf, offset5, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset5 + 7] = lo;
      lo = lo >> 8;
      buf[offset5 + 6] = lo;
      lo = lo >> 8;
      buf[offset5 + 5] = lo;
      lo = lo >> 8;
      buf[offset5 + 4] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset5 + 3] = hi;
      hi = hi >> 8;
      buf[offset5 + 2] = hi;
      hi = hi >> 8;
      buf[offset5 + 1] = hi;
      hi = hi >> 8;
      buf[offset5] = hi;
      return offset5 + 8;
    }
    Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset5 = 0) {
      return wrtBigUInt64LE(this, value, offset5, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset5 = 0) {
      return wrtBigUInt64BE(this, value, offset5, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeIntLE = function writeIntLE(value, offset5, byteLength2, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert) {
        const limit2 = Math.pow(2, 8 * byteLength2 - 1);
        checkInt(this, value, offset5, byteLength2, limit2 - 1, -limit2);
      }
      let i3 = 0;
      let mul = 1;
      let sub = 0;
      this[offset5] = value & 255;
      while (++i3 < byteLength2 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset5 + i3 - 1] !== 0) {
          sub = 1;
        }
        this[offset5 + i3] = (value / mul >> 0) - sub & 255;
      }
      return offset5 + byteLength2;
    };
    Buffer2.prototype.writeIntBE = function writeIntBE(value, offset5, byteLength2, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert) {
        const limit2 = Math.pow(2, 8 * byteLength2 - 1);
        checkInt(this, value, offset5, byteLength2, limit2 - 1, -limit2);
      }
      let i3 = byteLength2 - 1;
      let mul = 1;
      let sub = 0;
      this[offset5 + i3] = value & 255;
      while (--i3 >= 0 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset5 + i3 + 1] !== 0) {
          sub = 1;
        }
        this[offset5 + i3] = (value / mul >> 0) - sub & 255;
      }
      return offset5 + byteLength2;
    };
    Buffer2.prototype.writeInt8 = function writeInt8(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 1, 127, -128);
      if (value < 0)
        value = 255 + value + 1;
      this[offset5] = value & 255;
      return offset5 + 1;
    };
    Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 2, 32767, -32768);
      this[offset5] = value & 255;
      this[offset5 + 1] = value >>> 8;
      return offset5 + 2;
    };
    Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 2, 32767, -32768);
      this[offset5] = value >>> 8;
      this[offset5 + 1] = value & 255;
      return offset5 + 2;
    };
    Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 4, 2147483647, -2147483648);
      this[offset5] = value & 255;
      this[offset5 + 1] = value >>> 8;
      this[offset5 + 2] = value >>> 16;
      this[offset5 + 3] = value >>> 24;
      return offset5 + 4;
    };
    Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset5, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert)
        checkInt(this, value, offset5, 4, 2147483647, -2147483648);
      if (value < 0)
        value = 4294967295 + value + 1;
      this[offset5] = value >>> 24;
      this[offset5 + 1] = value >>> 16;
      this[offset5 + 2] = value >>> 8;
      this[offset5 + 3] = value & 255;
      return offset5 + 4;
    };
    Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset5 = 0) {
      return wrtBigUInt64LE(this, value, offset5, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset5 = 0) {
      return wrtBigUInt64BE(this, value, offset5, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    function checkIEEE754(buf, value, offset5, ext, max2, min2) {
      if (offset5 + ext > buf.length)
        throw new RangeError("Index out of range");
      if (offset5 < 0)
        throw new RangeError("Index out of range");
    }
    function writeFloat(buf, value, offset5, littleEndian, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset5, 4, 34028234663852886e22, -34028234663852886e22);
      }
      ieee754.write(buf, value, offset5, littleEndian, 23, 4);
      return offset5 + 4;
    }
    Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset5, noAssert) {
      return writeFloat(this, value, offset5, true, noAssert);
    };
    Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset5, noAssert) {
      return writeFloat(this, value, offset5, false, noAssert);
    };
    function writeDouble(buf, value, offset5, littleEndian, noAssert) {
      value = +value;
      offset5 = offset5 >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset5, 8, 17976931348623157e292, -17976931348623157e292);
      }
      ieee754.write(buf, value, offset5, littleEndian, 52, 8);
      return offset5 + 8;
    }
    Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset5, noAssert) {
      return writeDouble(this, value, offset5, true, noAssert);
    };
    Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset5, noAssert) {
      return writeDouble(this, value, offset5, false, noAssert);
    };
    Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
      if (!Buffer2.isBuffer(target))
        throw new TypeError("argument should be a Buffer");
      if (!start)
        start = 0;
      if (!end && end !== 0)
        end = this.length;
      if (targetStart >= target.length)
        targetStart = target.length;
      if (!targetStart)
        targetStart = 0;
      if (end > 0 && end < start)
        end = start;
      if (end === start)
        return 0;
      if (target.length === 0 || this.length === 0)
        return 0;
      if (targetStart < 0) {
        throw new RangeError("targetStart out of bounds");
      }
      if (start < 0 || start >= this.length)
        throw new RangeError("Index out of range");
      if (end < 0)
        throw new RangeError("sourceEnd out of bounds");
      if (end > this.length)
        end = this.length;
      if (target.length - targetStart < end - start) {
        end = target.length - targetStart + start;
      }
      const len = end - start;
      if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
        this.copyWithin(targetStart, start, end);
      } else {
        Uint8Array.prototype.set.call(
          target,
          this.subarray(start, end),
          targetStart
        );
      }
      return len;
    };
    Buffer2.prototype.fill = function fill(val2, start, end, encoding) {
      if (typeof val2 === "string") {
        if (typeof start === "string") {
          encoding = start;
          start = 0;
          end = this.length;
        } else if (typeof end === "string") {
          encoding = end;
          end = this.length;
        }
        if (encoding !== void 0 && typeof encoding !== "string") {
          throw new TypeError("encoding must be a string");
        }
        if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        if (val2.length === 1) {
          const code = val2.charCodeAt(0);
          if (encoding === "utf8" && code < 128 || encoding === "latin1") {
            val2 = code;
          }
        }
      } else if (typeof val2 === "number") {
        val2 = val2 & 255;
      } else if (typeof val2 === "boolean") {
        val2 = Number(val2);
      }
      if (start < 0 || this.length < start || this.length < end) {
        throw new RangeError("Out of range index");
      }
      if (end <= start) {
        return this;
      }
      start = start >>> 0;
      end = end === void 0 ? this.length : end >>> 0;
      if (!val2)
        val2 = 0;
      let i3;
      if (typeof val2 === "number") {
        for (i3 = start; i3 < end; ++i3) {
          this[i3] = val2;
        }
      } else {
        const bytes = Buffer2.isBuffer(val2) ? val2 : Buffer2.from(val2, encoding);
        const len = bytes.length;
        if (len === 0) {
          throw new TypeError('The value "' + val2 + '" is invalid for argument "value"');
        }
        for (i3 = 0; i3 < end - start; ++i3) {
          this[i3 + start] = bytes[i3 % len];
        }
      }
      return this;
    };
    var errors2 = {};
    function E2(sym, getMessage, Base) {
      errors2[sym] = class NodeError extends Base {
        constructor() {
          super();
          Object.defineProperty(this, "message", {
            value: getMessage.apply(this, arguments),
            writable: true,
            configurable: true
          });
          this.name = `${this.name} [${sym}]`;
          this.stack;
          delete this.name;
        }
        get code() {
          return sym;
        }
        set code(value) {
          Object.defineProperty(this, "code", {
            configurable: true,
            enumerable: true,
            value,
            writable: true
          });
        }
        toString() {
          return `${this.name} [${sym}]: ${this.message}`;
        }
      };
    }
    E2(
      "ERR_BUFFER_OUT_OF_BOUNDS",
      function(name) {
        if (name) {
          return `${name} is outside of buffer bounds`;
        }
        return "Attempt to access memory outside buffer bounds";
      },
      RangeError
    );
    E2(
      "ERR_INVALID_ARG_TYPE",
      function(name, actual) {
        return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
      },
      TypeError
    );
    E2(
      "ERR_OUT_OF_RANGE",
      function(str2, range, input) {
        let msg = `The value of "${str2}" is out of range.`;
        let received = input;
        if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
          received = addNumericalSeparator(String(input));
        } else if (typeof input === "bigint") {
          received = String(input);
          if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
            received = addNumericalSeparator(received);
          }
          received += "n";
        }
        msg += ` It must be ${range}. Received ${received}`;
        return msg;
      },
      RangeError
    );
    function addNumericalSeparator(val2) {
      let res = "";
      let i3 = val2.length;
      const start = val2[0] === "-" ? 1 : 0;
      for (; i3 >= start + 4; i3 -= 3) {
        res = `_${val2.slice(i3 - 3, i3)}${res}`;
      }
      return `${val2.slice(0, i3)}${res}`;
    }
    function checkBounds(buf, offset5, byteLength2) {
      validateNumber(offset5, "offset");
      if (buf[offset5] === void 0 || buf[offset5 + byteLength2] === void 0) {
        boundsError(offset5, buf.length - (byteLength2 + 1));
      }
    }
    function checkIntBI(value, min2, max2, buf, offset5, byteLength2) {
      if (value > max2 || value < min2) {
        const n4 = typeof min2 === "bigint" ? "n" : "";
        let range;
        if (byteLength2 > 3) {
          if (min2 === 0 || min2 === BigInt(0)) {
            range = `>= 0${n4} and < 2${n4} ** ${(byteLength2 + 1) * 8}${n4}`;
          } else {
            range = `>= -(2${n4} ** ${(byteLength2 + 1) * 8 - 1}${n4}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n4}`;
          }
        } else {
          range = `>= ${min2}${n4} and <= ${max2}${n4}`;
        }
        throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
      }
      checkBounds(buf, offset5, byteLength2);
    }
    function validateNumber(value, name) {
      if (typeof value !== "number") {
        throw new errors2.ERR_INVALID_ARG_TYPE(name, "number", value);
      }
    }
    function boundsError(value, length, type) {
      if (Math.floor(value) !== value) {
        validateNumber(value, type);
        throw new errors2.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
      }
      if (length < 0) {
        throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS();
      }
      throw new errors2.ERR_OUT_OF_RANGE(
        type || "offset",
        `>= ${type ? 1 : 0} and <= ${length}`,
        value
      );
    }
    var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
    function base64clean(str2) {
      str2 = str2.split("=")[0];
      str2 = str2.trim().replace(INVALID_BASE64_RE, "");
      if (str2.length < 2)
        return "";
      while (str2.length % 4 !== 0) {
        str2 = str2 + "=";
      }
      return str2;
    }
    function utf8ToBytes(string, units) {
      units = units || Infinity;
      let codePoint;
      const length = string.length;
      let leadSurrogate = null;
      const bytes = [];
      for (let i3 = 0; i3 < length; ++i3) {
        codePoint = string.charCodeAt(i3);
        if (codePoint > 55295 && codePoint < 57344) {
          if (!leadSurrogate) {
            if (codePoint > 56319) {
              if ((units -= 3) > -1)
                bytes.push(239, 191, 189);
              continue;
            } else if (i3 + 1 === length) {
              if ((units -= 3) > -1)
                bytes.push(239, 191, 189);
              continue;
            }
            leadSurrogate = codePoint;
            continue;
          }
          if (codePoint < 56320) {
            if ((units -= 3) > -1)
              bytes.push(239, 191, 189);
            leadSurrogate = codePoint;
            continue;
          }
          codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
        } else if (leadSurrogate) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
        }
        leadSurrogate = null;
        if (codePoint < 128) {
          if ((units -= 1) < 0)
            break;
          bytes.push(codePoint);
        } else if (codePoint < 2048) {
          if ((units -= 2) < 0)
            break;
          bytes.push(
            codePoint >> 6 | 192,
            codePoint & 63 | 128
          );
        } else if (codePoint < 65536) {
          if ((units -= 3) < 0)
            break;
          bytes.push(
            codePoint >> 12 | 224,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else if (codePoint < 1114112) {
          if ((units -= 4) < 0)
            break;
          bytes.push(
            codePoint >> 18 | 240,
            codePoint >> 12 & 63 | 128,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else {
          throw new Error("Invalid code point");
        }
      }
      return bytes;
    }
    function asciiToBytes(str2) {
      const byteArray = [];
      for (let i3 = 0; i3 < str2.length; ++i3) {
        byteArray.push(str2.charCodeAt(i3) & 255);
      }
      return byteArray;
    }
    function utf16leToBytes(str2, units) {
      let c4, hi, lo;
      const byteArray = [];
      for (let i3 = 0; i3 < str2.length; ++i3) {
        if ((units -= 2) < 0)
          break;
        c4 = str2.charCodeAt(i3);
        hi = c4 >> 8;
        lo = c4 % 256;
        byteArray.push(lo);
        byteArray.push(hi);
      }
      return byteArray;
    }
    function base64ToBytes(str2) {
      return base642.toByteArray(base64clean(str2));
    }
    function blitBuffer(src, dst, offset5, length) {
      let i3;
      for (i3 = 0; i3 < length; ++i3) {
        if (i3 + offset5 >= dst.length || i3 >= src.length)
          break;
        dst[i3 + offset5] = src[i3];
      }
      return i3;
    }
    function isInstance(obj, type) {
      return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
    }
    function numberIsNaN(obj) {
      return obj !== obj;
    }
    var hexSliceLookupTable = function() {
      const alphabet = "0123456789abcdef";
      const table = new Array(256);
      for (let i3 = 0; i3 < 16; ++i3) {
        const i16 = i3 * 16;
        for (let j3 = 0; j3 < 16; ++j3) {
          table[i16 + j3] = alphabet[i3] + alphabet[j3];
        }
      }
      return table;
    }();
    function defineBigIntMethod(fn) {
      return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
    }
    function BufferBigIntNotDefined() {
      throw new Error("BigInt not supported");
    }
  }
});

// node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
var require_dist_cjs2 = __commonJS({
  "node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports, module2) {
    var __defProp4 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp4(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp4(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp4({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromArrayBuffer: () => fromArrayBuffer,
      fromString: () => fromString
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_is_array_buffer2 = require_dist_cjs();
    var import_buffer = require_buffer();
    var fromArrayBuffer = /* @__PURE__ */ __name((input, offset5 = 0, length = input.byteLength - offset5) => {
      if (!(0, import_is_array_buffer2.isArrayBuffer)(input)) {
        throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
      }
      return import_buffer.Buffer.from(input, offset5, length);
    }, "fromArrayBuffer");
    var fromString = /* @__PURE__ */ __name((input, encoding) => {
      if (typeof input !== "string") {
        throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
      }
      return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input);
    }, "fromString");
  }
});

// node_modules/@smithy/util-utf8/dist-cjs/index.js
var require_dist_cjs3 = __commonJS({
  "node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports, module2) {
    var __defProp4 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __name = (target, value) => __defProp4(target, "name", { value, configurable: true });
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp4(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp4({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      fromUtf8: () => fromUtf86,
      toUint8Array: () => toUint8Array2,
      toUtf8: () => toUtf84
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_util_buffer_from = require_dist_cjs2();
    var fromUtf86 = /* @__PURE__ */ __name((input) => {
      const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
      return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    }, "fromUtf8");
    var toUint8Array2 = /* @__PURE__ */ __name((data) => {
      if (typeof data === "string") {
        return fromUtf86(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    }, "toUint8Array");
    var toUtf84 = /* @__PURE__ */ __name((input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
    }, "toUtf8");
  }
});

// node_modules/@aws-crypto/util/build/main/convertToBuffer.js
var require_convertToBuffer = __commonJS({
  "node_modules/@aws-crypto/util/build/main/convertToBuffer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.convertToBuffer = void 0;
    var util_utf8_1 = require_dist_cjs3();
    var fromUtf86 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
      return Buffer.from(input, "utf8");
    } : util_utf8_1.fromUtf8;
    function convertToBuffer3(data) {
      if (data instanceof Uint8Array)
        return data;
      if (typeof data === "string") {
        return fromUtf86(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    }
    exports.convertToBuffer = convertToBuffer3;
  }
});

// node_modules/@aws-crypto/util/build/main/isEmptyData.js
var require_isEmptyData = __commonJS({
  "node_modules/@aws-crypto/util/build/main/isEmptyData.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isEmptyData = void 0;
    function isEmptyData2(data) {
      if (typeof data === "string") {
        return data.length === 0;
      }
      return data.byteLength === 0;
    }
    exports.isEmptyData = isEmptyData2;
  }
});

// node_modules/@aws-crypto/util/build/main/numToUint8.js
var require_numToUint8 = __commonJS({
  "node_modules/@aws-crypto/util/build/main/numToUint8.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.numToUint8 = void 0;
    function numToUint8(num) {
      return new Uint8Array([
        (num & 4278190080) >> 24,
        (num & 16711680) >> 16,
        (num & 65280) >> 8,
        num & 255
      ]);
    }
    exports.numToUint8 = numToUint8;
  }
});

// node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js
var require_uint32ArrayFrom = __commonJS({
  "node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.uint32ArrayFrom = void 0;
    function uint32ArrayFrom(a_lookUpTable) {
      if (!Uint32Array.from) {
        var return_array = new Uint32Array(a_lookUpTable.length);
        var a_index = 0;
        while (a_index < a_lookUpTable.length) {
          return_array[a_index] = a_lookUpTable[a_index];
          a_index += 1;
        }
        return return_array;
      }
      return Uint32Array.from(a_lookUpTable);
    }
    exports.uint32ArrayFrom = uint32ArrayFrom;
  }
});

// node_modules/@aws-crypto/util/build/main/index.js
var require_main = __commonJS({
  "node_modules/@aws-crypto/util/build/main/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0;
    var convertToBuffer_1 = require_convertToBuffer();
    Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() {
      return convertToBuffer_1.convertToBuffer;
    } });
    var isEmptyData_1 = require_isEmptyData();
    Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() {
      return isEmptyData_1.isEmptyData;
    } });
    var numToUint8_1 = require_numToUint8();
    Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() {
      return numToUint8_1.numToUint8;
    } });
    var uint32ArrayFrom_1 = require_uint32ArrayFrom();
    Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() {
      return uint32ArrayFrom_1.uint32ArrayFrom;
    } });
  }
});

// node_modules/@aws-crypto/sha256-js/build/main/jsSha256.js
var require_jsSha256 = __commonJS({
  "node_modules/@aws-crypto/sha256-js/build/main/jsSha256.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Sha256 = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var constants_1 = require_constants2();
    var RawSha256_1 = require_RawSha256();
    var util_1 = require_main();
    var Sha2563 = (
      /** @class */
      function() {
        function Sha2564(secret) {
          this.secret = secret;
          this.hash = new RawSha256_1.RawSha256();
          this.reset();
        }
        Sha2564.prototype.update = function(toHash) {
          if ((0, util_1.isEmptyData)(toHash) || this.error) {
            return;
          }
          try {
            this.hash.update((0, util_1.convertToBuffer)(toHash));
          } catch (e3) {
            this.error = e3;
          }
        };
        Sha2564.prototype.digestSync = function() {
          if (this.error) {
            throw this.error;
          }
          if (this.outer) {
            if (!this.outer.finished) {
              this.outer.update(this.hash.digest());
            }
            return this.outer.digest();
          }
          return this.hash.digest();
        };
        Sha2564.prototype.digest = function() {
          return tslib_1.__awaiter(this, void 0, void 0, function() {
            return tslib_1.__generator(this, function(_a5) {
              return [2, this.digestSync()];
            });
          });
        };
        Sha2564.prototype.reset = function() {
          this.hash = new RawSha256_1.RawSha256();
          if (this.secret) {
            this.outer = new RawSha256_1.RawSha256();
            var inner = bufferFromSecret(this.secret);
            var outer = new Uint8Array(constants_1.BLOCK_SIZE);
            outer.set(inner);
            for (var i3 = 0; i3 < constants_1.BLOCK_SIZE; i3++) {
              inner[i3] ^= 54;
              outer[i3] ^= 92;
            }
            this.hash.update(inner);
            this.outer.update(outer);
            for (var i3 = 0; i3 < inner.byteLength; i3++) {
              inner[i3] = 0;
            }
          }
        };
        return Sha2564;
      }()
    );
    exports.Sha256 = Sha2563;
    function bufferFromSecret(secret) {
      var input = (0, util_1.convertToBuffer)(secret);
      if (input.byteLength > constants_1.BLOCK_SIZE) {
        var bufferHash = new RawSha256_1.RawSha256();
        bufferHash.update(input);
        input = bufferHash.digest();
      }
      var buffer = new Uint8Array(constants_1.BLOCK_SIZE);
      buffer.set(input);
      return buffer;
    }
  }
});

// node_modules/@aws-crypto/sha256-js/build/main/index.js
var require_main2 = __commonJS({
  "node_modules/@aws-crypto/sha256-js/build/main/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    tslib_1.__exportStar(require_jsSha256(), exports);
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/CognitoProviderParameters.js
var init_CognitoProviderParameters = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/CognitoProviderParameters.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Logins.js
var init_Logins = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Logins.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Storage.js
var init_Storage = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/Storage.js"() {
  }
});

// node_modules/@smithy/property-provider/dist-es/ProviderError.js
var ProviderError;
var init_ProviderError = __esm({
  "node_modules/@smithy/property-provider/dist-es/ProviderError.js"() {
    ProviderError = class extends Error {
      constructor(message, options = true) {
        let logger2;
        let tryNextLink = true;
        if (typeof options === "boolean") {
          logger2 = void 0;
          tryNextLink = options;
        } else if (options != null && typeof options === "object") {
          logger2 = options.logger;
          tryNextLink = options.tryNextLink ?? true;
        }
        super(message);
        this.name = "ProviderError";
        this.tryNextLink = tryNextLink;
        Object.setPrototypeOf(this, ProviderError.prototype);
        logger2?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
      }
      static from(error, options = true) {
        return Object.assign(new this(error.message, options), error);
      }
    };
  }
});

// node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js
var CredentialsProviderError;
var init_CredentialsProviderError = __esm({
  "node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() {
    init_ProviderError();
    CredentialsProviderError = class extends ProviderError {
      constructor(message, options = true) {
        super(message, options);
        this.name = "CredentialsProviderError";
        Object.setPrototypeOf(this, CredentialsProviderError.prototype);
      }
    };
  }
});

// node_modules/@smithy/property-provider/dist-es/TokenProviderError.js
var init_TokenProviderError = __esm({
  "node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() {
    init_ProviderError();
  }
});

// node_modules/@smithy/property-provider/dist-es/chain.js
var init_chain = __esm({
  "node_modules/@smithy/property-provider/dist-es/chain.js"() {
    init_ProviderError();
  }
});

// node_modules/@smithy/property-provider/dist-es/fromStatic.js
var init_fromStatic = __esm({
  "node_modules/@smithy/property-provider/dist-es/fromStatic.js"() {
  }
});

// node_modules/@smithy/property-provider/dist-es/memoize.js
var memoize;
var init_memoize = __esm({
  "node_modules/@smithy/property-provider/dist-es/memoize.js"() {
    memoize = (provider, isExpired, requiresRefresh) => {
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = async () => {
        if (!pending) {
          pending = provider();
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      };
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || options?.forceRefresh) {
            resolved = await coalesceProvider();
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider();
        }
        if (isConstant) {
          return resolved;
        }
        if (requiresRefresh && !requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider();
          return resolved;
        }
        return resolved;
      };
    };
  }
});

// node_modules/@smithy/property-provider/dist-es/index.js
var init_dist_es = __esm({
  "node_modules/@smithy/property-provider/dist-es/index.js"() {
    init_CredentialsProviderError();
    init_ProviderError();
    init_TokenProviderError();
    init_chain();
    init_fromStatic();
    init_memoize();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js
function resolveLogins(logins) {
  return Promise.all(Object.keys(logins).reduce((arr2, name) => {
    const tokenOrProvider = logins[name];
    if (typeof tokenOrProvider === "string") {
      arr2.push([name, tokenOrProvider]);
    } else {
      arr2.push(tokenOrProvider().then((token) => [name, token]));
    }
    return arr2;
  }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins2, [key, value]) => {
    logins2[key] = value;
    return logins2;
  }, {}));
}
var init_resolveLogins = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration();
  }
});

// node_modules/@smithy/types/dist-es/abort.js
var init_abort = __esm({
  "node_modules/@smithy/types/dist-es/abort.js"() {
  }
});

// node_modules/@smithy/types/dist-es/auth/auth.js
var HttpAuthLocation;
var init_auth = __esm({
  "node_modules/@smithy/types/dist-es/auth/auth.js"() {
    (function(HttpAuthLocation2) {
      HttpAuthLocation2["HEADER"] = "header";
      HttpAuthLocation2["QUERY"] = "query";
    })(HttpAuthLocation || (HttpAuthLocation = {}));
  }
});

// node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
var HttpApiKeyAuthLocation;
var init_HttpApiKeyAuth = __esm({
  "node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() {
    (function(HttpApiKeyAuthLocation2) {
      HttpApiKeyAuthLocation2["HEADER"] = "header";
      HttpApiKeyAuthLocation2["QUERY"] = "query";
    })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
  }
});

// node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js
var init_HttpAuthScheme = __esm({
  "node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() {
  }
});

// node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js
var init_HttpAuthSchemeProvider = __esm({
  "node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() {
  }
});

// node_modules/@smithy/types/dist-es/auth/HttpSigner.js
var init_HttpSigner = __esm({
  "node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() {
  }
});

// node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js
var init_IdentityProviderConfig = __esm({
  "node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() {
  }
});

// node_modules/@smithy/types/dist-es/auth/index.js
var init_auth2 = __esm({
  "node_modules/@smithy/types/dist-es/auth/index.js"() {
    init_auth();
    init_HttpApiKeyAuth();
    init_HttpAuthScheme();
    init_HttpAuthSchemeProvider();
    init_HttpSigner();
    init_IdentityProviderConfig();
  }
});

// node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js
var init_blob_payload_input_types = __esm({
  "node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() {
  }
});

// node_modules/@smithy/types/dist-es/checksum.js
var init_checksum = __esm({
  "node_modules/@smithy/types/dist-es/checksum.js"() {
  }
});

// node_modules/@smithy/types/dist-es/client.js
var init_client2 = __esm({
  "node_modules/@smithy/types/dist-es/client.js"() {
  }
});

// node_modules/@smithy/types/dist-es/command.js
var init_command = __esm({
  "node_modules/@smithy/types/dist-es/command.js"() {
  }
});

// node_modules/@smithy/types/dist-es/connection/config.js
var init_config2 = __esm({
  "node_modules/@smithy/types/dist-es/connection/config.js"() {
  }
});

// node_modules/@smithy/types/dist-es/connection/manager.js
var init_manager2 = __esm({
  "node_modules/@smithy/types/dist-es/connection/manager.js"() {
  }
});

// node_modules/@smithy/types/dist-es/connection/pool.js
var init_pool = __esm({
  "node_modules/@smithy/types/dist-es/connection/pool.js"() {
  }
});

// node_modules/@smithy/types/dist-es/connection/index.js
var init_connection = __esm({
  "node_modules/@smithy/types/dist-es/connection/index.js"() {
    init_config2();
    init_manager2();
    init_pool();
  }
});

// node_modules/@smithy/types/dist-es/crypto.js
var init_crypto = __esm({
  "node_modules/@smithy/types/dist-es/crypto.js"() {
  }
});

// node_modules/@smithy/types/dist-es/encode.js
var init_encode = __esm({
  "node_modules/@smithy/types/dist-es/encode.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoint.js
var EndpointURLScheme;
var init_endpoint = __esm({
  "node_modules/@smithy/types/dist-es/endpoint.js"() {
    (function(EndpointURLScheme2) {
      EndpointURLScheme2["HTTP"] = "http";
      EndpointURLScheme2["HTTPS"] = "https";
    })(EndpointURLScheme || (EndpointURLScheme = {}));
  }
});

// node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js
var init_EndpointRuleObject = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js
var init_ErrorRuleObject = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js
var init_RuleSetObject = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoints/shared.js
var init_shared = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/shared.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js
var init_TreeRuleObject = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() {
  }
});

// node_modules/@smithy/types/dist-es/endpoints/index.js
var init_endpoints = __esm({
  "node_modules/@smithy/types/dist-es/endpoints/index.js"() {
    init_EndpointRuleObject();
    init_ErrorRuleObject();
    init_RuleSetObject();
    init_shared();
    init_TreeRuleObject();
  }
});

// node_modules/@smithy/types/dist-es/eventStream.js
var init_eventStream = __esm({
  "node_modules/@smithy/types/dist-es/eventStream.js"() {
  }
});

// node_modules/@smithy/types/dist-es/extensions/checksum.js
var AlgorithmId;
var init_checksum2 = __esm({
  "node_modules/@smithy/types/dist-es/extensions/checksum.js"() {
    (function(AlgorithmId2) {
      AlgorithmId2["MD5"] = "md5";
      AlgorithmId2["CRC32"] = "crc32";
      AlgorithmId2["CRC32C"] = "crc32c";
      AlgorithmId2["SHA1"] = "sha1";
      AlgorithmId2["SHA256"] = "sha256";
    })(AlgorithmId || (AlgorithmId = {}));
  }
});

// node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js
var init_defaultClientConfiguration = __esm({
  "node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() {
    init_checksum2();
  }
});

// node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js
var init_defaultExtensionConfiguration = __esm({
  "node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() {
  }
});

// node_modules/@smithy/types/dist-es/extensions/index.js
var init_extensions2 = __esm({
  "node_modules/@smithy/types/dist-es/extensions/index.js"() {
    init_defaultClientConfiguration();
    init_defaultExtensionConfiguration();
    init_checksum2();
  }
});

// node_modules/@smithy/types/dist-es/http.js
var FieldPosition;
var init_http = __esm({
  "node_modules/@smithy/types/dist-es/http.js"() {
    (function(FieldPosition2) {
      FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
      FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
    })(FieldPosition || (FieldPosition = {}));
  }
});

// node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js
var init_httpHandlerInitialization = __esm({
  "node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() {
  }
});

// node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js
var init_apiKeyIdentity = __esm({
  "node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() {
  }
});

// node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js
var init_awsCredentialIdentity = __esm({
  "node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() {
  }
});

// node_modules/@smithy/types/dist-es/identity/identity.js
var init_identity = __esm({
  "node_modules/@smithy/types/dist-es/identity/identity.js"() {
  }
});

// node_modules/@smithy/types/dist-es/identity/tokenIdentity.js
var init_tokenIdentity = __esm({
  "node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() {
  }
});

// node_modules/@smithy/types/dist-es/identity/index.js
var init_identity2 = __esm({
  "node_modules/@smithy/types/dist-es/identity/index.js"() {
    init_apiKeyIdentity();
    init_awsCredentialIdentity();
    init_identity();
    init_tokenIdentity();
  }
});

// node_modules/@smithy/types/dist-es/logger.js
var init_logger = __esm({
  "node_modules/@smithy/types/dist-es/logger.js"() {
  }
});

// node_modules/@smithy/types/dist-es/middleware.js
var SMITHY_CONTEXT_KEY;
var init_middleware = __esm({
  "node_modules/@smithy/types/dist-es/middleware.js"() {
    SMITHY_CONTEXT_KEY = "__smithy_context";
  }
});

// node_modules/@smithy/types/dist-es/pagination.js
var init_pagination = __esm({
  "node_modules/@smithy/types/dist-es/pagination.js"() {
  }
});

// node_modules/@smithy/types/dist-es/profile.js
var IniSectionType;
var init_profile = __esm({
  "node_modules/@smithy/types/dist-es/profile.js"() {
    (function(IniSectionType2) {
      IniSectionType2["PROFILE"] = "profile";
      IniSectionType2["SSO_SESSION"] = "sso-session";
      IniSectionType2["SERVICES"] = "services";
    })(IniSectionType || (IniSectionType = {}));
  }
});

// node_modules/@smithy/types/dist-es/response.js
var init_response = __esm({
  "node_modules/@smithy/types/dist-es/response.js"() {
  }
});

// node_modules/@smithy/types/dist-es/retry.js
var init_retry = __esm({
  "node_modules/@smithy/types/dist-es/retry.js"() {
  }
});

// node_modules/@smithy/types/dist-es/serde.js
var init_serde2 = __esm({
  "node_modules/@smithy/types/dist-es/serde.js"() {
  }
});

// node_modules/@smithy/types/dist-es/shapes.js
var init_shapes = __esm({
  "node_modules/@smithy/types/dist-es/shapes.js"() {
  }
});

// node_modules/@smithy/types/dist-es/signature.js
var init_signature = __esm({
  "node_modules/@smithy/types/dist-es/signature.js"() {
  }
});

// node_modules/@smithy/types/dist-es/stream.js
var init_stream2 = __esm({
  "node_modules/@smithy/types/dist-es/stream.js"() {
  }
});

// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js
var init_streaming_blob_common_types = __esm({
  "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() {
  }
});

// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js
var init_streaming_blob_payload_input_types = __esm({
  "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() {
  }
});

// node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js
var init_streaming_blob_payload_output_types = __esm({
  "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() {
  }
});

// node_modules/@smithy/types/dist-es/transfer.js
var RequestHandlerProtocol;
var init_transfer = __esm({
  "node_modules/@smithy/types/dist-es/transfer.js"() {
    (function(RequestHandlerProtocol2) {
      RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
      RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
      RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
    })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
  }
});

// node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js
var init_client_payload_blob_type_narrow = __esm({
  "node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() {
  }
});

// node_modules/@smithy/types/dist-es/transform/no-undefined.js
var init_no_undefined = __esm({
  "node_modules/@smithy/types/dist-es/transform/no-undefined.js"() {
  }
});

// node_modules/@smithy/types/dist-es/transform/type-transform.js
var init_type_transform = __esm({
  "node_modules/@smithy/types/dist-es/transform/type-transform.js"() {
  }
});

// node_modules/@smithy/types/dist-es/uri.js
var init_uri = __esm({
  "node_modules/@smithy/types/dist-es/uri.js"() {
  }
});

// node_modules/@smithy/types/dist-es/util.js
var init_util = __esm({
  "node_modules/@smithy/types/dist-es/util.js"() {
  }
});

// node_modules/@smithy/types/dist-es/waiter.js
var init_waiter = __esm({
  "node_modules/@smithy/types/dist-es/waiter.js"() {
  }
});

// node_modules/@smithy/types/dist-es/index.js
var init_dist_es2 = __esm({
  "node_modules/@smithy/types/dist-es/index.js"() {
    init_abort();
    init_auth2();
    init_blob_payload_input_types();
    init_checksum();
    init_client2();
    init_command();
    init_connection();
    init_crypto();
    init_encode();
    init_endpoint();
    init_endpoints();
    init_eventStream();
    init_extensions2();
    init_http();
    init_httpHandlerInitialization();
    init_identity2();
    init_logger();
    init_middleware();
    init_pagination();
    init_profile();
    init_response();
    init_retry();
    init_serde2();
    init_shapes();
    init_signature();
    init_stream2();
    init_streaming_blob_common_types();
    init_streaming_blob_payload_input_types();
    init_streaming_blob_payload_output_types();
    init_transfer();
    init_client_payload_blob_type_narrow();
    init_no_undefined();
    init_type_transform();
    init_uri();
    init_util();
    init_waiter();
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest;
var init_httpRequest = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types2 = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es3 = __esm({
  "node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions();
    init_Field();
    init_Fields();
    init_httpHandler();
    init_httpRequest();
    init_httpResponse();
    init_isValidHostname();
    init_types2();
  }
});

// node_modules/@aws-sdk/middleware-host-header/dist-es/index.js
function resolveHostHeaderConfig(input) {
  return input;
}
var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin;
var init_dist_es4 = __esm({
  "node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() {
    init_dist_es3();
    hostHeaderMiddleware = (options) => (next) => async (args) => {
      if (!HttpRequest.isInstance(args.request))
        return next(args);
      const { request } = args;
      const { handlerProtocol = "" } = options.requestHandler.metadata || {};
      if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) {
        delete request.headers["host"];
        request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : "");
      } else if (!request.headers["host"]) {
        let host = request.hostname;
        if (request.port != null)
          host += `:${request.port}`;
        request.headers["host"] = host;
      }
      return next(args);
    };
    hostHeaderMiddlewareOptions = {
      name: "hostHeaderMiddleware",
      step: "build",
      priority: "low",
      tags: ["HOST"],
      override: true
    };
    getHostHeaderPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
      }
    });
  }
});

// node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js
var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin;
var init_loggerMiddleware = __esm({
  "node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() {
    loggerMiddleware = () => (next, context) => async (args) => {
      try {
        const response = await next(args);
        const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
        const { $metadata, ...outputWithoutMetadata } = response.output;
        logger2?.info?.({
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          output: outputFilterSensitiveLog(outputWithoutMetadata),
          metadata: $metadata
        });
        return response;
      } catch (error) {
        const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context;
        const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
        const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
        logger2?.error?.({
          clientName,
          commandName,
          input: inputFilterSensitiveLog(args.input),
          error,
          metadata: error.$metadata
        });
        throw error;
      }
    };
    loggerMiddlewareOptions = {
      name: "loggerMiddleware",
      tags: ["LOGGER"],
      step: "initialize",
      override: true
    };
    getLoggerPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
      }
    });
  }
});

// node_modules/@aws-sdk/middleware-logger/dist-es/index.js
var init_dist_es5 = __esm({
  "node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() {
    init_loggerMiddleware();
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions3 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration2();
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery2(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest2;
var init_httpRequest2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest2 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest2({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery2(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest2.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname2 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types3 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es6 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions3();
    init_Field2();
    init_Fields2();
    init_httpHandler2();
    init_httpRequest2();
    init_httpResponse2();
    init_isValidHostname2();
    init_types3();
  }
});

// node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js
var TRACE_ID_HEADER_NAME, ENV_LAMBDA_FUNCTION_NAME, ENV_TRACE_ID, recursionDetectionMiddleware, addRecursionDetectionMiddlewareOptions, getRecursionDetectionPlugin;
var init_dist_es7 = __esm({
  "node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() {
    init_dist_es6();
    TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
    ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
    ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
    recursionDetectionMiddleware = (options) => (next) => async (args) => {
      const { request } = args;
      if (!HttpRequest2.isInstance(request) || options.runtime !== "node" || request.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)) {
        return next(args);
      }
      const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
      const traceId = process.env[ENV_TRACE_ID];
      const nonEmptyString = (str2) => typeof str2 === "string" && str2.length > 0;
      if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
        request.headers[TRACE_ID_HEADER_NAME] = traceId;
      }
      return next({
        ...args,
        request
      });
    };
    addRecursionDetectionMiddlewareOptions = {
      step: "build",
      tags: ["RECURSION_DETECTION"],
      name: "recursionDetectionMiddleware",
      override: true,
      priority: "low"
    };
    getRecursionDetectionPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
      }
    });
  }
});

// node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js
function resolveUserAgentConfig(input) {
  return {
    ...input,
    customUserAgent: typeof input.customUserAgent === "string" ? [[input.customUserAgent]] : input.customUserAgent
  };
}
var init_configurations = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js
var IP_V4_REGEX, isIpAddress;
var init_isIpAddress = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() {
    IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
    isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]");
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js
var VALID_HOST_LABEL_REGEX, isValidHostLabel;
var init_isValidHostLabel = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() {
    VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
    isValidHostLabel = (value, allowSubDomains = false) => {
      if (!allowSubDomains) {
        return VALID_HOST_LABEL_REGEX.test(value);
      }
      const labels = value.split(".");
      for (const label of labels) {
        if (!isValidHostLabel(label)) {
          return false;
        }
      }
      return true;
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js
var customEndpointFunctions;
var init_customEndpointFunctions = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() {
    customEndpointFunctions = {};
  }
});

// node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js
var debugId;
var init_debugId = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() {
    debugId = "endpoints";
  }
});

// node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js
function toDebugString(input) {
  if (typeof input !== "object" || input == null) {
    return input;
  }
  if ("ref" in input) {
    return `$${toDebugString(input.ref)}`;
  }
  if ("fn" in input) {
    return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
  }
  return JSON.stringify(input, null, 2);
}
var init_toDebugString = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/debug/index.js
var init_debug = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() {
    init_debugId();
    init_toDebugString();
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js
var EndpointError;
var init_EndpointError = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() {
    EndpointError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "EndpointError";
      }
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js
var init_EndpointFunctions = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/shared.js
var init_shared2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() {
  }
});

// node_modules/@smithy/util-endpoints/dist-es/types/index.js
var init_types4 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/types/index.js"() {
    init_EndpointError();
    init_EndpointFunctions();
    init_EndpointRuleObject2();
    init_ErrorRuleObject2();
    init_RuleSetObject2();
    init_TreeRuleObject2();
    init_shared2();
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js
var booleanEquals;
var init_booleanEquals = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() {
    booleanEquals = (value1, value2) => value1 === value2;
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js
var getAttrPathList;
var init_getAttrPathList = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() {
    init_types4();
    getAttrPathList = (path) => {
      const parts = path.split(".");
      const pathList = [];
      for (const part of parts) {
        const squareBracketIndex = part.indexOf("[");
        if (squareBracketIndex !== -1) {
          if (part.indexOf("]") !== part.length - 1) {
            throw new EndpointError(`Path: '${path}' does not end with ']'`);
          }
          const arrayIndex = part.slice(squareBracketIndex + 1, -1);
          if (Number.isNaN(parseInt(arrayIndex))) {
            throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`);
          }
          if (squareBracketIndex !== 0) {
            pathList.push(part.slice(0, squareBracketIndex));
          }
          pathList.push(arrayIndex);
        } else {
          pathList.push(part);
        }
      }
      return pathList;
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js
var getAttr;
var init_getAttr = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() {
    init_types4();
    init_getAttrPathList();
    getAttr = (value, path) => getAttrPathList(path).reduce((acc, index2) => {
      if (typeof acc !== "object") {
        throw new EndpointError(`Index '${index2}' in '${path}' not found in '${JSON.stringify(value)}'`);
      } else if (Array.isArray(acc)) {
        return acc[parseInt(index2)];
      }
      return acc[index2];
    }, value);
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js
var isSet;
var init_isSet = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() {
    isSet = (value) => value != null;
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/not.js
var not;
var init_not = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() {
    not = (value) => !value;
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js
var DEFAULT_PORTS, parseURL;
var init_parseURL = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() {
    init_dist_es2();
    init_isIpAddress();
    DEFAULT_PORTS = {
      [EndpointURLScheme.HTTP]: 80,
      [EndpointURLScheme.HTTPS]: 443
    };
    parseURL = (value) => {
      const whatwgURL = (() => {
        try {
          if (value instanceof URL) {
            return value;
          }
          if (typeof value === "object" && "hostname" in value) {
            const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value;
            const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`);
            url.search = Object.entries(query).map(([k3, v5]) => `${k3}=${v5}`).join("&");
            return url;
          }
          return new URL(value);
        } catch (error) {
          return null;
        }
      })();
      if (!whatwgURL) {
        console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
        return null;
      }
      const urlString = whatwgURL.href;
      const { host, hostname, pathname, protocol, search: search3 } = whatwgURL;
      if (search3) {
        return null;
      }
      const scheme = protocol.slice(0, -1);
      if (!Object.values(EndpointURLScheme).includes(scheme)) {
        return null;
      }
      const isIp = isIpAddress(hostname);
      const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
      const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
      return {
        scheme,
        authority,
        path: pathname,
        normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
        isIp
      };
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js
var stringEquals;
var init_stringEquals = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() {
    stringEquals = (value1, value2) => value1 === value2;
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/substring.js
var substring;
var init_substring = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() {
    substring = (input, start, stop, reverse) => {
      if (start >= stop || input.length < stop) {
        return null;
      }
      if (!reverse) {
        return input.substring(start, stop);
      }
      return input.substring(input.length - stop, input.length - start);
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js
var uriEncode;
var init_uriEncode = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() {
    uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}`);
  }
});

// node_modules/@smithy/util-endpoints/dist-es/lib/index.js
var init_lib2 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() {
    init_booleanEquals();
    init_getAttr();
    init_isSet();
    init_isValidHostLabel();
    init_not();
    init_parseURL();
    init_stringEquals();
    init_substring();
    init_uriEncode();
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js
var endpointFunctions;
var init_endpointFunctions = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() {
    init_lib2();
    endpointFunctions = {
      booleanEquals,
      getAttr,
      isSet,
      isValidHostLabel,
      not,
      parseURL,
      stringEquals,
      substring,
      uriEncode
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js
var evaluateTemplate;
var init_evaluateTemplate = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() {
    init_lib2();
    evaluateTemplate = (template, options) => {
      const evaluatedTemplateArr = [];
      const templateContext = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      let currentIndex = 0;
      while (currentIndex < template.length) {
        const openingBraceIndex = template.indexOf("{", currentIndex);
        if (openingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(currentIndex));
          break;
        }
        evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
        const closingBraceIndex = template.indexOf("}", openingBraceIndex);
        if (closingBraceIndex === -1) {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex));
          break;
        }
        if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
          evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
          currentIndex = closingBraceIndex + 2;
        }
        const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
        if (parameterName.includes("#")) {
          const [refName, attrName] = parameterName.split("#");
          evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
        } else {
          evaluatedTemplateArr.push(templateContext[parameterName]);
        }
        currentIndex = closingBraceIndex + 1;
      }
      return evaluatedTemplateArr.join("");
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js
var getReferenceValue;
var init_getReferenceValue = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() {
    getReferenceValue = ({ ref }, options) => {
      const referenceRecord = {
        ...options.endpointParams,
        ...options.referenceRecord
      };
      return referenceRecord[ref];
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js
var evaluateExpression;
var init_evaluateExpression = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() {
    init_types4();
    init_callFunction();
    init_evaluateTemplate();
    init_getReferenceValue();
    evaluateExpression = (obj, keyName, options) => {
      if (typeof obj === "string") {
        return evaluateTemplate(obj, options);
      } else if (obj["fn"]) {
        return callFunction(obj, options);
      } else if (obj["ref"]) {
        return getReferenceValue(obj, options);
      }
      throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js
var callFunction;
var init_callFunction = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() {
    init_customEndpointFunctions();
    init_endpointFunctions();
    init_evaluateExpression();
    callFunction = ({ fn, argv }, options) => {
      const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options));
      const fnSegments = fn.split(".");
      if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
        return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
      }
      return endpointFunctions[fn](...evaluatedArgs);
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js
var evaluateCondition;
var init_evaluateCondition = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() {
    init_debug();
    init_types4();
    init_callFunction();
    evaluateCondition = ({ assign, ...fnArgs }, options) => {
      if (assign && assign in options.referenceRecord) {
        throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
      }
      const value = callFunction(fnArgs, options);
      options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
      return {
        result: value === "" ? true : !!value,
        ...assign != null && { toAssign: { name: assign, value } }
      };
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js
var evaluateConditions;
var init_evaluateConditions = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() {
    init_debug();
    init_evaluateCondition();
    evaluateConditions = (conditions = [], options) => {
      const conditionsReferenceRecord = {};
      for (const condition of conditions) {
        const { result, toAssign } = evaluateCondition(condition, {
          ...options,
          referenceRecord: {
            ...options.referenceRecord,
            ...conditionsReferenceRecord
          }
        });
        if (!result) {
          return { result };
        }
        if (toAssign) {
          conditionsReferenceRecord[toAssign.name] = toAssign.value;
          options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
        }
      }
      return { result: true, referenceRecord: conditionsReferenceRecord };
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js
var getEndpointHeaders;
var init_getEndpointHeaders = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() {
    init_types4();
    init_evaluateExpression();
    getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
      ...acc,
      [headerKey]: headerVal.map((headerValEntry) => {
        const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
        if (typeof processedExpr !== "string") {
          throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
        }
        return processedExpr;
      })
    }), {});
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js
var getEndpointProperty;
var init_getEndpointProperty = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() {
    init_types4();
    init_evaluateTemplate();
    init_getEndpointProperties();
    getEndpointProperty = (property, options) => {
      if (Array.isArray(property)) {
        return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
      }
      switch (typeof property) {
        case "string":
          return evaluateTemplate(property, options);
        case "object":
          if (property === null) {
            throw new EndpointError(`Unexpected endpoint property: ${property}`);
          }
          return getEndpointProperties(property, options);
        case "boolean":
          return property;
        default:
          throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);
      }
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js
var getEndpointProperties;
var init_getEndpointProperties = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() {
    init_getEndpointProperty();
    getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
      ...acc,
      [propertyKey]: getEndpointProperty(propertyVal, options)
    }), {});
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js
var getEndpointUrl;
var init_getEndpointUrl = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() {
    init_types4();
    init_evaluateExpression();
    getEndpointUrl = (endpointUrl, options) => {
      const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
      if (typeof expression === "string") {
        try {
          return new URL(expression);
        } catch (error) {
          console.error(`Failed to construct URL with ${expression}`, error);
          throw error;
        }
      }
      throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js
var evaluateEndpointRule;
var init_evaluateEndpointRule = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() {
    init_debug();
    init_evaluateConditions();
    init_getEndpointHeaders();
    init_getEndpointProperties();
    init_getEndpointUrl();
    evaluateEndpointRule = (endpointRule, options) => {
      const { conditions, endpoint } = endpointRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      const endpointRuleOptions = {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      };
      const { url, properties, headers } = endpoint;
      options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
      return {
        ...headers != void 0 && {
          headers: getEndpointHeaders(headers, endpointRuleOptions)
        },
        ...properties != void 0 && {
          properties: getEndpointProperties(properties, endpointRuleOptions)
        },
        url: getEndpointUrl(url, endpointRuleOptions)
      };
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js
var evaluateErrorRule;
var init_evaluateErrorRule = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() {
    init_types4();
    init_evaluateConditions();
    init_evaluateExpression();
    evaluateErrorRule = (errorRule, options) => {
      const { conditions, error } = errorRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      throw new EndpointError(evaluateExpression(error, "Error", {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      }));
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js
var evaluateTreeRule;
var init_evaluateTreeRule = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() {
    init_evaluateConditions();
    init_evaluateRules();
    evaluateTreeRule = (treeRule, options) => {
      const { conditions, rules } = treeRule;
      const { result, referenceRecord } = evaluateConditions(conditions, options);
      if (!result) {
        return;
      }
      return evaluateRules(rules, {
        ...options,
        referenceRecord: { ...options.referenceRecord, ...referenceRecord }
      });
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js
var evaluateRules;
var init_evaluateRules = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() {
    init_types4();
    init_evaluateEndpointRule();
    init_evaluateErrorRule();
    init_evaluateTreeRule();
    evaluateRules = (rules, options) => {
      for (const rule of rules) {
        if (rule.type === "endpoint") {
          const endpointOrUndefined = evaluateEndpointRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else if (rule.type === "error") {
          evaluateErrorRule(rule, options);
        } else if (rule.type === "tree") {
          const endpointOrUndefined = evaluateTreeRule(rule, options);
          if (endpointOrUndefined) {
            return endpointOrUndefined;
          }
        } else {
          throw new EndpointError(`Unknown endpoint rule: ${rule}`);
        }
      }
      throw new EndpointError(`Rules evaluation failed`);
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/utils/index.js
var init_utils4 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() {
    init_customEndpointFunctions();
    init_evaluateRules();
  }
});

// node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js
var resolveEndpoint;
var init_resolveEndpoint = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() {
    init_debug();
    init_types4();
    init_utils4();
    resolveEndpoint = (ruleSetObject, options) => {
      const { endpointParams, logger: logger2 } = options;
      const { parameters, rules } = ruleSetObject;
      options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
      const paramsWithDefault = Object.entries(parameters).filter(([, v5]) => v5.default != null).map(([k3, v5]) => [k3, v5.default]);
      if (paramsWithDefault.length > 0) {
        for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
          endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
        }
      }
      const requiredParams = Object.entries(parameters).filter(([, v5]) => v5.required).map(([k3]) => k3);
      for (const requiredParam of requiredParams) {
        if (endpointParams[requiredParam] == null) {
          throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
        }
      }
      const endpoint = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} });
      if (options.endpointParams?.Endpoint) {
        try {
          const givenEndpoint = new URL(options.endpointParams.Endpoint);
          const { protocol, port } = givenEndpoint;
          endpoint.url.protocol = protocol;
          endpoint.url.port = port;
        } catch (e3) {
        }
      }
      options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
      return endpoint;
    };
  }
});

// node_modules/@smithy/util-endpoints/dist-es/index.js
var init_dist_es8 = __esm({
  "node_modules/@smithy/util-endpoints/dist-es/index.js"() {
    init_isIpAddress();
    init_isValidHostLabel();
    init_customEndpointFunctions();
    init_resolveEndpoint();
    init_types4();
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js
var init_isIpAddress2 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() {
    init_dist_es8();
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js
var isVirtualHostableS3Bucket;
var init_isVirtualHostableS3Bucket = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() {
    init_dist_es8();
    init_isIpAddress2();
    isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {
      if (allowSubDomains) {
        for (const label of value.split(".")) {
          if (!isVirtualHostableS3Bucket(label)) {
            return false;
          }
        }
        return true;
      }
      if (!isValidHostLabel(value)) {
        return false;
      }
      if (value.length < 3 || value.length > 63) {
        return false;
      }
      if (value !== value.toLowerCase()) {
        return false;
      }
      if (isIpAddress(value)) {
        return false;
      }
      return true;
    };
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js
var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn;
var init_parseArn = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() {
    ARN_DELIMITER = ":";
    RESOURCE_DELIMITER = "/";
    parseArn = (value) => {
      const segments = value.split(ARN_DELIMITER);
      if (segments.length < 6)
        return null;
      const [arn, partition5, service, region, accountId, ...resourcePath] = segments;
      if (arn !== "arn" || partition5 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
        return null;
      const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
      return {
        partition: partition5,
        service,
        region,
        accountId,
        resourceId
      };
    };
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json
var partitions_default;
var init_partitions = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() {
    partitions_default = {
      partitions: [{
        id: "aws",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-east-1",
          name: "aws",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
        regions: {
          "af-south-1": {
            description: "Africa (Cape Town)"
          },
          "ap-east-1": {
            description: "Asia Pacific (Hong Kong)"
          },
          "ap-northeast-1": {
            description: "Asia Pacific (Tokyo)"
          },
          "ap-northeast-2": {
            description: "Asia Pacific (Seoul)"
          },
          "ap-northeast-3": {
            description: "Asia Pacific (Osaka)"
          },
          "ap-south-1": {
            description: "Asia Pacific (Mumbai)"
          },
          "ap-south-2": {
            description: "Asia Pacific (Hyderabad)"
          },
          "ap-southeast-1": {
            description: "Asia Pacific (Singapore)"
          },
          "ap-southeast-2": {
            description: "Asia Pacific (Sydney)"
          },
          "ap-southeast-3": {
            description: "Asia Pacific (Jakarta)"
          },
          "ap-southeast-4": {
            description: "Asia Pacific (Melbourne)"
          },
          "ap-southeast-5": {
            description: "Asia Pacific (Malaysia)"
          },
          "aws-global": {
            description: "AWS Standard global region"
          },
          "ca-central-1": {
            description: "Canada (Central)"
          },
          "ca-west-1": {
            description: "Canada West (Calgary)"
          },
          "eu-central-1": {
            description: "Europe (Frankfurt)"
          },
          "eu-central-2": {
            description: "Europe (Zurich)"
          },
          "eu-north-1": {
            description: "Europe (Stockholm)"
          },
          "eu-south-1": {
            description: "Europe (Milan)"
          },
          "eu-south-2": {
            description: "Europe (Spain)"
          },
          "eu-west-1": {
            description: "Europe (Ireland)"
          },
          "eu-west-2": {
            description: "Europe (London)"
          },
          "eu-west-3": {
            description: "Europe (Paris)"
          },
          "il-central-1": {
            description: "Israel (Tel Aviv)"
          },
          "me-central-1": {
            description: "Middle East (UAE)"
          },
          "me-south-1": {
            description: "Middle East (Bahrain)"
          },
          "sa-east-1": {
            description: "South America (Sao Paulo)"
          },
          "us-east-1": {
            description: "US East (N. Virginia)"
          },
          "us-east-2": {
            description: "US East (Ohio)"
          },
          "us-west-1": {
            description: "US West (N. California)"
          },
          "us-west-2": {
            description: "US West (Oregon)"
          }
        }
      }, {
        id: "aws-cn",
        outputs: {
          dnsSuffix: "amazonaws.com.cn",
          dualStackDnsSuffix: "api.amazonwebservices.com.cn",
          implicitGlobalRegion: "cn-northwest-1",
          name: "aws-cn",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^cn\\-\\w+\\-\\d+$",
        regions: {
          "aws-cn-global": {
            description: "AWS China global region"
          },
          "cn-north-1": {
            description: "China (Beijing)"
          },
          "cn-northwest-1": {
            description: "China (Ningxia)"
          }
        }
      }, {
        id: "aws-us-gov",
        outputs: {
          dnsSuffix: "amazonaws.com",
          dualStackDnsSuffix: "api.aws",
          implicitGlobalRegion: "us-gov-west-1",
          name: "aws-us-gov",
          supportsDualStack: true,
          supportsFIPS: true
        },
        regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
        regions: {
          "aws-us-gov-global": {
            description: "AWS GovCloud (US) global region"
          },
          "us-gov-east-1": {
            description: "AWS GovCloud (US-East)"
          },
          "us-gov-west-1": {
            description: "AWS GovCloud (US-West)"
          }
        }
      }, {
        id: "aws-iso",
        outputs: {
          dnsSuffix: "c2s.ic.gov",
          dualStackDnsSuffix: "c2s.ic.gov",
          implicitGlobalRegion: "us-iso-east-1",
          name: "aws-iso",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-global": {
            description: "AWS ISO (US) global region"
          },
          "us-iso-east-1": {
            description: "US ISO East"
          },
          "us-iso-west-1": {
            description: "US ISO WEST"
          }
        }
      }, {
        id: "aws-iso-b",
        outputs: {
          dnsSuffix: "sc2s.sgov.gov",
          dualStackDnsSuffix: "sc2s.sgov.gov",
          implicitGlobalRegion: "us-isob-east-1",
          name: "aws-iso-b",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
        regions: {
          "aws-iso-b-global": {
            description: "AWS ISOB (US) global region"
          },
          "us-isob-east-1": {
            description: "US ISOB East (Ohio)"
          }
        }
      }, {
        id: "aws-iso-e",
        outputs: {
          dnsSuffix: "cloud.adc-e.uk",
          dualStackDnsSuffix: "cloud.adc-e.uk",
          implicitGlobalRegion: "eu-isoe-west-1",
          name: "aws-iso-e",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
        regions: {
          "eu-isoe-west-1": {
            description: "EU ISOE West"
          }
        }
      }, {
        id: "aws-iso-f",
        outputs: {
          dnsSuffix: "csp.hci.ic.gov",
          dualStackDnsSuffix: "csp.hci.ic.gov",
          implicitGlobalRegion: "us-isof-south-1",
          name: "aws-iso-f",
          supportsDualStack: false,
          supportsFIPS: true
        },
        regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
        regions: {}
      }],
      version: "1.1"
    };
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js
var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix;
var init_partition = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() {
    init_partitions();
    selectedPartitionsInfo = partitions_default;
    selectedUserAgentPrefix = "";
    partition = (value) => {
      const { partitions } = selectedPartitionsInfo;
      for (const partition5 of partitions) {
        const { regions, outputs } = partition5;
        for (const [region, regionData] of Object.entries(regions)) {
          if (region === value) {
            return {
              ...outputs,
              ...regionData
            };
          }
        }
      }
      for (const partition5 of partitions) {
        const { regionRegex, outputs } = partition5;
        if (new RegExp(regionRegex).test(value)) {
          return {
            ...outputs
          };
        }
      }
      const DEFAULT_PARTITION = partitions.find((partition5) => partition5.id === "aws");
      if (!DEFAULT_PARTITION) {
        throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
      }
      return {
        ...DEFAULT_PARTITION.outputs
      };
    };
    getUserAgentPrefix = () => selectedUserAgentPrefix;
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/aws.js
var awsEndpointFunctions;
var init_aws = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() {
    init_dist_es8();
    init_isVirtualHostableS3Bucket();
    init_parseArn();
    init_partition();
    awsEndpointFunctions = {
      isVirtualHostableS3Bucket,
      parseArn,
      partition
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js
var init_resolveEndpoint2 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() {
    init_dist_es8();
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js
var init_EndpointError2 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() {
    init_dist_es8();
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js
var init_EndpointRuleObject3 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() {
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js
var init_ErrorRuleObject3 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() {
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js
var init_RuleSetObject3 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() {
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js
var init_TreeRuleObject3 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() {
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js
var init_shared3 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() {
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js
var init_types5 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() {
    init_EndpointError2();
    init_EndpointRuleObject3();
    init_ErrorRuleObject3();
    init_RuleSetObject3();
    init_TreeRuleObject3();
    init_shared3();
  }
});

// node_modules/@aws-sdk/util-endpoints/dist-es/index.js
var init_dist_es9 = __esm({
  "node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() {
    init_aws();
    init_partition();
    init_isIpAddress2();
    init_resolveEndpoint2();
    init_types5();
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions4 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration3();
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery3(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest3;
var init_httpRequest3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest3 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest3({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery3(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest3.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname3 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types6 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es10 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions4();
    init_Field3();
    init_Fields3();
    init_httpHandler3();
    init_httpRequest3();
    init_httpResponse3();
    init_isValidHostname3();
    init_types6();
  }
});

// node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js
var USER_AGENT, X_AMZ_USER_AGENT, SPACE, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR;
var init_constants2 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() {
    USER_AGENT = "user-agent";
    X_AMZ_USER_AGENT = "x-amz-user-agent";
    SPACE = " ";
    UA_NAME_SEPARATOR = "/";
    UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
    UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
    UA_ESCAPE_CHAR = "-";
  }
});

// node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js
var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin;
var init_user_agent_middleware = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() {
    init_dist_es9();
    init_dist_es10();
    init_constants2();
    userAgentMiddleware = (options) => (next, context) => async (args) => {
      const { request } = args;
      if (!HttpRequest3.isInstance(request))
        return next(args);
      const { headers } = request;
      const userAgent = context?.userAgent?.map(escapeUserAgent) || [];
      const defaultUserAgent2 = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
      const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
      const prefix = getUserAgentPrefix();
      const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent2, ...userAgent, ...customUserAgent]).join(SPACE);
      const normalUAValue = [
        ...defaultUserAgent2.filter((section) => section.startsWith("aws-sdk-")),
        ...customUserAgent
      ].join(SPACE);
      if (options.runtime !== "browser") {
        if (normalUAValue) {
          headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
        }
        headers[USER_AGENT] = sdkUserAgentValue;
      } else {
        headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
      }
      return next({
        ...args,
        request
      });
    };
    escapeUserAgent = (userAgentPair) => {
      const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
      const version2 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
      const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
      const prefix = name.substring(0, prefixSeparatorIndex);
      let uaName = name.substring(prefixSeparatorIndex + 1);
      if (prefix === "api") {
        uaName = uaName.toLowerCase();
      }
      return [prefix, uaName, version2].filter((item) => item && item.length > 0).reduce((acc, item, index2) => {
        switch (index2) {
          case 0:
            return item;
          case 1:
            return `${acc}/${item}`;
          default:
            return `${acc}#${item}`;
        }
      }, "");
    };
    getUserAgentMiddlewareOptions = {
      name: "getUserAgentMiddleware",
      step: "build",
      priority: "low",
      tags: ["SET_USER_AGENT", "USER_AGENT"],
      override: true
    };
    getUserAgentPlugin = (config) => ({
      applyToStack: (clientStack) => {
        clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
      }
    });
  }
});

// node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js
var init_dist_es11 = __esm({
  "node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() {
    init_configurations();
    init_user_agent_middleware();
  }
});

// node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js
var init_booleanSelector = __esm({
  "node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"() {
  }
});

// node_modules/@smithy/util-config-provider/dist-es/numberSelector.js
var init_numberSelector = __esm({
  "node_modules/@smithy/util-config-provider/dist-es/numberSelector.js"() {
  }
});

// node_modules/@smithy/util-config-provider/dist-es/types.js
var SelectorType;
var init_types7 = __esm({
  "node_modules/@smithy/util-config-provider/dist-es/types.js"() {
    (function(SelectorType2) {
      SelectorType2["ENV"] = "env";
      SelectorType2["CONFIG"] = "shared config entry";
    })(SelectorType || (SelectorType = {}));
  }
});

// node_modules/@smithy/util-config-provider/dist-es/index.js
var init_dist_es12 = __esm({
  "node_modules/@smithy/util-config-provider/dist-es/index.js"() {
    init_booleanSelector();
    init_numberSelector();
    init_types7();
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js
var DEFAULT_USE_DUALSTACK_ENDPOINT;
var init_NodeUseDualstackEndpointConfigOptions = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() {
    init_dist_es12();
    DEFAULT_USE_DUALSTACK_ENDPOINT = false;
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js
var DEFAULT_USE_FIPS_ENDPOINT;
var init_NodeUseFipsEndpointConfigOptions = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() {
    init_dist_es12();
    DEFAULT_USE_FIPS_ENDPOINT = false;
  }
});

// node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
var getSmithyContext;
var init_getSmithyContext = __esm({
  "node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() {
    init_dist_es2();
    getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {});
  }
});

// node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
var normalizeProvider;
var init_normalizeProvider = __esm({
  "node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() {
    normalizeProvider = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
  }
});

// node_modules/@smithy/util-middleware/dist-es/index.js
var init_dist_es13 = __esm({
  "node_modules/@smithy/util-middleware/dist-es/index.js"() {
    init_getSmithyContext();
    init_normalizeProvider();
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js
var init_resolveCustomEndpointsConfig = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() {
    init_dist_es13();
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js
var init_getEndpointFromRegion = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/utils/getEndpointFromRegion.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js
var init_resolveEndpointsConfig = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() {
    init_dist_es13();
    init_getEndpointFromRegion();
  }
});

// node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js
var init_endpointsConfig = __esm({
  "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() {
    init_NodeUseDualstackEndpointConfigOptions();
    init_NodeUseFipsEndpointConfigOptions();
    init_resolveCustomEndpointsConfig();
    init_resolveEndpointsConfig();
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js
var init_config3 = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js
var isFipsRegion;
var init_isFipsRegion = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
    isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js
var getRealRegion;
var init_getRealRegion = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() {
    init_isFipsRegion();
    getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var resolveRegionConfig;
var init_resolveRegionConfig = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
    init_getRealRegion();
    init_isFipsRegion();
    resolveRegionConfig = (input) => {
      const { region, useFipsEndpoint } = input;
      if (!region) {
        throw new Error("Region is missing");
      }
      return {
        ...input,
        region: async () => {
          if (typeof region === "string") {
            return getRealRegion(region);
          }
          const providedRegion = await region();
          return getRealRegion(providedRegion);
        },
        useFipsEndpoint: async () => {
          const providedRegion = typeof region === "string" ? region : await region();
          if (isFipsRegion(providedRegion)) {
            return true;
          }
          return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
        }
      };
    };
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js
var init_regionConfig = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() {
    init_config3();
    init_resolveRegionConfig();
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js
var init_PartitionHash = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js
var init_RegionHash = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js
var init_getHostnameFromVariants = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/getHostnameFromVariants.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js
var init_getResolvedHostname = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedHostname.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js
var init_getResolvedPartition = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedPartition.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js
var init_getResolvedSigningRegion = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/getResolvedSigningRegion.js"() {
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js
var init_getRegionInfo = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() {
    init_getHostnameFromVariants();
    init_getResolvedHostname();
    init_getResolvedPartition();
    init_getResolvedSigningRegion();
  }
});

// node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js
var init_regionInfo = __esm({
  "node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() {
    init_PartitionHash();
    init_RegionHash();
    init_getRegionInfo();
  }
});

// node_modules/@smithy/config-resolver/dist-es/index.js
var init_dist_es14 = __esm({
  "node_modules/@smithy/config-resolver/dist-es/index.js"() {
    init_endpointsConfig();
    init_regionConfig();
    init_regionInfo();
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
function convertHttpAuthSchemesToMap(httpAuthSchemes) {
  const map = /* @__PURE__ */ new Map();
  for (const scheme of httpAuthSchemes) {
    map.set(scheme.schemeId, scheme);
  }
  return map;
}
var httpAuthSchemeMiddleware;
var init_httpAuthSchemeMiddleware = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
    init_dist_es2();
    init_dist_es13();
    httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
      const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));
      const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
      const smithyContext = getSmithyContext(context);
      const failureReasons = [];
      for (const option of options) {
        const scheme = authSchemes.get(option.schemeId);
        if (!scheme) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
          continue;
        }
        const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
        if (!identityProvider) {
          failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
          continue;
        }
        const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {};
        option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
        option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
        smithyContext.selectedHttpAuthScheme = {
          httpAuthOption: option,
          identity: await identityProvider(option.identityProperties),
          signer: scheme.signer
        };
        break;
      }
      if (!smithyContext.selectedHttpAuthScheme) {
        throw new Error(failureReasons.join("\n"));
      }
      return next(args);
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js
var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName;
var init_s3 = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() {
    resolveParamsForS3 = async (endpointParams) => {
      const bucket = endpointParams?.Bucket || "";
      if (typeof endpointParams.Bucket === "string") {
        endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
      }
      if (isArnBucketName(bucket)) {
        if (endpointParams.ForcePathStyle === true) {
          throw new Error("Path-style addressing cannot be used with ARN buckets");
        }
      } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
        endpointParams.ForcePathStyle = true;
      }
      if (endpointParams.DisableMultiRegionAccessPoints) {
        endpointParams.disableMultiRegionAccessPoints = true;
        endpointParams.DisableMRAP = true;
      }
      return endpointParams;
    };
    DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
    IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
    DOTS_PATTERN = /\.\./;
    isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
    isArnBucketName = (bucketName) => {
      const [arn, partition5, service, , , bucket] = bucketName.split(":");
      const isArn = arn === "arn" && bucketName.split(":").length >= 6;
      const isValidArn = Boolean(isArn && partition5 && service && bucket);
      if (isArn && !isValidArn) {
        throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
      }
      return isValidArn;
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js
var init_service_customizations = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() {
    init_s3();
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js
var createConfigValueProvider;
var init_createConfigValueProvider = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() {
    createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => {
      const configProvider = async () => {
        const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
        if (typeof configValue === "function") {
          return configValue();
        }
        return configValue;
      };
      if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
        return async () => {
          const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = credentials?.credentialScope ?? credentials?.CredentialScope;
          return configValue;
        };
      }
      if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
        return async () => {
          const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
          const configValue = credentials?.accountId ?? credentials?.AccountId;
          return configValue;
        };
      }
      if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
        return async () => {
          const endpoint = await configProvider();
          if (endpoint && typeof endpoint === "object") {
            if ("url" in endpoint) {
              return endpoint.url.href;
            }
            if ("hostname" in endpoint) {
              const { protocol, hostname, port, path } = endpoint;
              return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`;
            }
          }
          return endpoint;
        };
      }
      return configProvider;
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js
var getEndpointFromConfig;
var init_getEndpointFromConfig_browser = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js"() {
    getEndpointFromConfig = async (serviceId) => void 0;
  }
});

// node_modules/@smithy/querystring-parser/dist-es/index.js
function parseQueryString(querystring) {
  const query = {};
  querystring = querystring.replace(/^\?/, "");
  if (querystring) {
    for (const pair of querystring.split("&")) {
      let [key, value = null] = pair.split("=");
      key = decodeURIComponent(key);
      if (value) {
        value = decodeURIComponent(value);
      }
      if (!(key in query)) {
        query[key] = value;
      } else if (Array.isArray(query[key])) {
        query[key].push(value);
      } else {
        query[key] = [query[key], value];
      }
    }
  }
  return query;
}
var init_dist_es15 = __esm({
  "node_modules/@smithy/querystring-parser/dist-es/index.js"() {
  }
});

// node_modules/@smithy/url-parser/dist-es/index.js
var parseUrl;
var init_dist_es16 = __esm({
  "node_modules/@smithy/url-parser/dist-es/index.js"() {
    init_dist_es15();
    parseUrl = (url) => {
      if (typeof url === "string") {
        return parseUrl(new URL(url));
      }
      const { hostname, pathname, port, protocol, search: search3 } = url;
      let query;
      if (search3) {
        query = parseQueryString(search3);
      }
      return {
        hostname,
        port: port ? parseInt(port) : void 0,
        protocol,
        path: pathname,
        query
      };
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js
var toEndpointV1;
var init_toEndpointV1 = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() {
    init_dist_es16();
    toEndpointV1 = (endpoint) => {
      if (typeof endpoint === "object") {
        if ("url" in endpoint) {
          return parseUrl(endpoint.url);
        }
        return endpoint;
      }
      return parseUrl(endpoint);
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js
var getEndpointFromInstructions, resolveParams;
var init_getEndpointFromInstructions = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() {
    init_service_customizations();
    init_createConfigValueProvider();
    init_getEndpointFromConfig_browser();
    init_toEndpointV1();
    getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {
      if (!clientConfig.endpoint) {
        const endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId || "");
        if (endpointFromConfig) {
          clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
        }
      }
      const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
      if (typeof clientConfig.endpointProvider !== "function") {
        throw new Error("config.endpointProvider is not set.");
      }
      const endpoint = clientConfig.endpointProvider(endpointParams, context);
      return endpoint;
    };
    resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {
      const endpointParams = {};
      const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
      for (const [name, instruction] of Object.entries(instructions)) {
        switch (instruction.type) {
          case "staticContextParams":
            endpointParams[name] = instruction.value;
            break;
          case "contextParams":
            endpointParams[name] = commandInput[instruction.name];
            break;
          case "clientContextParams":
          case "builtInParams":
            endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)();
            break;
          default:
            throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
        }
      }
      if (Object.keys(instructions).length === 0) {
        Object.assign(endpointParams, clientConfig);
      }
      if (String(clientConfig.serviceId).toLowerCase() === "s3") {
        await resolveParamsForS3(endpointParams);
      }
      return endpointParams;
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js
var init_adaptors = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() {
    init_getEndpointFromInstructions();
    init_toEndpointV1();
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js
var endpointMiddleware;
var init_endpointMiddleware = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() {
    init_dist_es13();
    init_getEndpointFromInstructions();
    endpointMiddleware = ({ config, instructions }) => {
      return (next, context) => async (args) => {
        const endpoint = await getEndpointFromInstructions(args.input, {
          getEndpointParameterInstructions() {
            return instructions;
          }
        }, { ...config }, context);
        context.endpointV2 = endpoint;
        context.authSchemes = endpoint.properties?.authSchemes;
        const authScheme = context.authSchemes?.[0];
        if (authScheme) {
          context["signing_region"] = authScheme.signingRegion;
          context["signing_service"] = authScheme.signingName;
          const smithyContext = getSmithyContext(context);
          const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
          if (httpAuthOption) {
            httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
              signing_region: authScheme.signingRegion,
              signingRegion: authScheme.signingRegion,
              signing_service: authScheme.signingName,
              signingName: authScheme.signingName,
              signingRegionSet: authScheme.signingRegionSet
            }, authScheme.properties);
          }
        }
        return next({
          ...args
        });
      };
    };
  }
});

// node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js
var deserializerMiddleware;
var init_deserializerMiddleware = __esm({
  "node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() {
    deserializerMiddleware = (options, deserializer) => (next) => async (args) => {
      const { response } = await next(args);
      try {
        const parsed = await deserializer(response, options);
        return {
          response,
          output: parsed
        };
      } catch (error) {
        Object.defineProperty(error, "$response", {
          value: response
        });
        if (!("$metadata" in error)) {
          const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
          error.message += "\n  " + hint;
          if (typeof error.$responseBodyText !== "undefined") {
            if (error.$response) {
              error.$response.body = error.$responseBodyText;
            }
          }
        }
        throw error;
      }
    };
  }
});

// node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js
var serializerMiddleware;
var init_serializerMiddleware = __esm({
  "node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() {
    serializerMiddleware = (options, serializer) => (next, context) => async (args) => {
      const endpoint = context.endpointV2?.url && options.urlParser ? async () => options.urlParser(context.endpointV2.url) : options.endpoint;
      if (!endpoint) {
        throw new Error("No valid endpoint provider available.");
      }
      const request = await serializer(args.input, { ...options, endpoint });
      return next({
        ...args,
        request
      });
    };
  }
});

// node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js
function getSerdePlugin(config, serializer, deserializer) {
  return {
    applyToStack: (commandStack) => {
      commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
      commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
    }
  };
}
var deserializerMiddlewareOption, serializerMiddlewareOption;
var init_serdePlugin = __esm({
  "node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() {
    init_deserializerMiddleware();
    init_serializerMiddleware();
    deserializerMiddlewareOption = {
      name: "deserializerMiddleware",
      step: "deserialize",
      tags: ["DESERIALIZER"],
      override: true
    };
    serializerMiddlewareOption = {
      name: "serializerMiddleware",
      step: "serialize",
      tags: ["SERIALIZER"],
      override: true
    };
  }
});

// node_modules/@smithy/middleware-serde/dist-es/index.js
var init_dist_es17 = __esm({
  "node_modules/@smithy/middleware-serde/dist-es/index.js"() {
    init_deserializerMiddleware();
    init_serdePlugin();
    init_serializerMiddleware();
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js
var endpointMiddlewareOptions, getEndpointPlugin;
var init_getEndpointPlugin = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() {
    init_dist_es17();
    init_endpointMiddleware();
    endpointMiddlewareOptions = {
      step: "serialize",
      tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
      name: "endpointV2Middleware",
      override: true,
      relation: "before",
      toMiddleware: serializerMiddlewareOption.name
    };
    getEndpointPlugin = (config, instructions) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(endpointMiddleware({
          config,
          instructions
        }), endpointMiddlewareOptions);
      }
    });
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js
var resolveEndpointConfig;
var init_resolveEndpointConfig = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() {
    init_dist_es13();
    init_toEndpointV1();
    resolveEndpointConfig = (input) => {
      const tls = input.tls ?? true;
      const { endpoint } = input;
      const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0;
      const isCustomEndpoint = !!endpoint;
      return {
        ...input,
        endpoint: customEndpointProvider,
        tls,
        isCustomEndpoint,
        useDualstackEndpoint: normalizeProvider(input.useDualstackEndpoint ?? false),
        useFipsEndpoint: normalizeProvider(input.useFipsEndpoint ?? false)
      };
    };
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/types.js
var init_types8 = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/types.js"() {
  }
});

// node_modules/@smithy/middleware-endpoint/dist-es/index.js
var init_dist_es18 = __esm({
  "node_modules/@smithy/middleware-endpoint/dist-es/index.js"() {
    init_adaptors();
    init_endpointMiddleware();
    init_getEndpointPlugin();
    init_resolveEndpointConfig();
    init_types8();
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
    init_dist_es18();
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: endpointMiddlewareOptions.name
    };
    getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
          httpAuthSchemeParametersProvider,
          identityProviderConfigProvider
        }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
      }
    });
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
var httpAuthSchemeMiddlewareOptions;
var init_getHttpAuthSchemePlugin = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
    init_dist_es17();
    init_httpAuthSchemeMiddleware();
    httpAuthSchemeMiddlewareOptions = {
      step: "serialize",
      tags: ["HTTP_AUTH_SCHEME"],
      name: "httpAuthSchemeMiddleware",
      override: true,
      relation: "before",
      toMiddleware: serializerMiddlewareOption.name
    };
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
var init_middleware_http_auth_scheme = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
    init_httpAuthSchemeMiddleware();
    init_getHttpAuthSchemeEndpointRuleSetPlugin();
    init_getHttpAuthSchemePlugin();
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions5 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration4();
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery4(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest4;
var init_httpRequest4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest4 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest4({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery4(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest4.clone(this);
      }
    };
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname4 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types9 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es19 = __esm({
  "node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions5();
    init_Field4();
    init_Fields4();
    init_httpHandler4();
    init_httpRequest4();
    init_httpResponse4();
    init_isValidHostname4();
    init_types9();
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
var init_httpSigningMiddleware = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
    init_dist_es19();
    init_dist_es2();
    init_dist_es13();
    defaultErrorHandler = (signingProperties) => (error) => {
      throw error;
    };
    defaultSuccessHandler = (httpResponse, signingProperties) => {
    };
    httpSigningMiddleware = (config) => (next, context) => async (args) => {
      if (!HttpRequest4.isInstance(args.request)) {
        return next(args);
      }
      const smithyContext = getSmithyContext(context);
      const scheme = smithyContext.selectedHttpAuthScheme;
      if (!scheme) {
        throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
      }
      const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
      const output = await next({
        ...args,
        request: await signer.sign(args.request, identity, signingProperties)
      }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
      (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
      return output;
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/config.js
var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE;
var init_config4 = __esm({
  "node_modules/@smithy/util-retry/dist-es/config.js"() {
    (function(RETRY_MODES2) {
      RETRY_MODES2["STANDARD"] = "standard";
      RETRY_MODES2["ADAPTIVE"] = "adaptive";
    })(RETRY_MODES || (RETRY_MODES = {}));
    DEFAULT_MAX_ATTEMPTS = 3;
    DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;
  }
});

// node_modules/@smithy/service-error-classification/dist-es/constants.js
var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES;
var init_constants3 = __esm({
  "node_modules/@smithy/service-error-classification/dist-es/constants.js"() {
    THROTTLING_ERROR_CODES = [
      "BandwidthLimitExceeded",
      "EC2ThrottledException",
      "LimitExceededException",
      "PriorRequestNotComplete",
      "ProvisionedThroughputExceededException",
      "RequestLimitExceeded",
      "RequestThrottled",
      "RequestThrottledException",
      "SlowDown",
      "ThrottledException",
      "Throttling",
      "ThrottlingException",
      "TooManyRequestsException",
      "TransactionInProgressException"
    ];
    TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
    TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
    NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
  }
});

// node_modules/@smithy/service-error-classification/dist-es/index.js
var isClockSkewCorrectedError, isThrottlingError, isTransientError, isServerError;
var init_dist_es20 = __esm({
  "node_modules/@smithy/service-error-classification/dist-es/index.js"() {
    init_constants3();
    isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected;
    isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true;
    isTransientError = (error) => isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0);
    isServerError = (error) => {
      if (error.$metadata?.httpStatusCode !== void 0) {
        const statusCode = error.$metadata.httpStatusCode;
        if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) {
          return true;
        }
        return false;
      }
      return false;
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js
var DefaultRateLimiter;
var init_DefaultRateLimiter = __esm({
  "node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() {
    init_dist_es20();
    DefaultRateLimiter = class {
      constructor(options) {
        this.currentCapacity = 0;
        this.enabled = false;
        this.lastMaxRate = 0;
        this.measuredTxRate = 0;
        this.requestCount = 0;
        this.lastTimestamp = 0;
        this.timeWindow = 0;
        this.beta = options?.beta ?? 0.7;
        this.minCapacity = options?.minCapacity ?? 1;
        this.minFillRate = options?.minFillRate ?? 0.5;
        this.scaleConstant = options?.scaleConstant ?? 0.4;
        this.smooth = options?.smooth ?? 0.8;
        const currentTimeInSeconds = this.getCurrentTimeInSeconds();
        this.lastThrottleTime = currentTimeInSeconds;
        this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
        this.fillRate = this.minFillRate;
        this.maxCapacity = this.minCapacity;
      }
      getCurrentTimeInSeconds() {
        return Date.now() / 1e3;
      }
      async getSendToken() {
        return this.acquireTokenBucket(1);
      }
      async acquireTokenBucket(amount) {
        if (!this.enabled) {
          return;
        }
        this.refillTokenBucket();
        if (amount > this.currentCapacity) {
          const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
          await new Promise((resolve) => setTimeout(resolve, delay));
        }
        this.currentCapacity = this.currentCapacity - amount;
      }
      refillTokenBucket() {
        const timestamp = this.getCurrentTimeInSeconds();
        if (!this.lastTimestamp) {
          this.lastTimestamp = timestamp;
          return;
        }
        const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
        this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
        this.lastTimestamp = timestamp;
      }
      updateClientSendingRate(response) {
        let calculatedRate;
        this.updateMeasuredRate();
        if (isThrottlingError(response)) {
          const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
          this.lastMaxRate = rateToUse;
          this.calculateTimeWindow();
          this.lastThrottleTime = this.getCurrentTimeInSeconds();
          calculatedRate = this.cubicThrottle(rateToUse);
          this.enableTokenBucket();
        } else {
          this.calculateTimeWindow();
          calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
        }
        const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
        this.updateTokenBucketRate(newRate);
      }
      calculateTimeWindow() {
        this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
      }
      cubicThrottle(rateToUse) {
        return this.getPrecise(rateToUse * this.beta);
      }
      cubicSuccess(timestamp) {
        return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
      }
      enableTokenBucket() {
        this.enabled = true;
      }
      updateTokenBucketRate(newRate) {
        this.refillTokenBucket();
        this.fillRate = Math.max(newRate, this.minFillRate);
        this.maxCapacity = Math.max(newRate, this.minCapacity);
        this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
      }
      updateMeasuredRate() {
        const t3 = this.getCurrentTimeInSeconds();
        const timeBucket = Math.floor(t3 * 2) / 2;
        this.requestCount++;
        if (timeBucket > this.lastTxRateBucket) {
          const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
          this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
          this.requestCount = 0;
          this.lastTxRateBucket = timeBucket;
        }
      }
      getPrecise(num) {
        return parseFloat(num.toFixed(8));
      }
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/constants.js
var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER;
var init_constants4 = __esm({
  "node_modules/@smithy/util-retry/dist-es/constants.js"() {
    DEFAULT_RETRY_DELAY_BASE = 100;
    MAXIMUM_RETRY_DELAY = 20 * 1e3;
    THROTTLING_RETRY_DELAY_BASE = 500;
    INITIAL_RETRY_TOKENS = 500;
    RETRY_COST = 5;
    TIMEOUT_RETRY_COST = 10;
    NO_RETRY_INCREMENT = 1;
    INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
    REQUEST_HEADER = "amz-sdk-request";
  }
});

// node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js
var getDefaultRetryBackoffStrategy;
var init_defaultRetryBackoffStrategy = __esm({
  "node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() {
    init_constants4();
    getDefaultRetryBackoffStrategy = () => {
      let delayBase = DEFAULT_RETRY_DELAY_BASE;
      const computeNextBackoffDelay = (attempts) => {
        return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
      };
      const setDelayBase = (delay) => {
        delayBase = delay;
      };
      return {
        computeNextBackoffDelay,
        setDelayBase
      };
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js
var createDefaultRetryToken;
var init_defaultRetryToken = __esm({
  "node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() {
    init_constants4();
    createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
      const getRetryCount = () => retryCount;
      const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
      const getRetryCost = () => retryCost;
      return {
        getRetryCount,
        getRetryDelay,
        getRetryCost
      };
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js
var StandardRetryStrategy;
var init_StandardRetryStrategy = __esm({
  "node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() {
    init_config4();
    init_constants4();
    init_defaultRetryBackoffStrategy();
    init_defaultRetryToken();
    StandardRetryStrategy = class {
      constructor(maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.mode = RETRY_MODES.STANDARD;
        this.capacity = INITIAL_RETRY_TOKENS;
        this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
        this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
      }
      async acquireInitialRetryToken(retryTokenScope) {
        return createDefaultRetryToken({
          retryDelay: DEFAULT_RETRY_DELAY_BASE,
          retryCount: 0
        });
      }
      async refreshRetryTokenForRetry(token, errorInfo) {
        const maxAttempts = await this.getMaxAttempts();
        if (this.shouldRetry(token, errorInfo, maxAttempts)) {
          const errorType = errorInfo.errorType;
          this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
          const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
          const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
          const capacityCost = this.getCapacityCost(errorType);
          this.capacity -= capacityCost;
          return createDefaultRetryToken({
            retryDelay,
            retryCount: token.getRetryCount() + 1,
            retryCost: capacityCost
          });
        }
        throw new Error("No retry token available");
      }
      recordSuccess(token) {
        this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
      }
      getCapacity() {
        return this.capacity;
      }
      async getMaxAttempts() {
        try {
          return await this.maxAttemptsProvider();
        } catch (error) {
          console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
          return DEFAULT_MAX_ATTEMPTS;
        }
      }
      shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
        const attempts = tokenToRenew.getRetryCount() + 1;
        return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
      }
      getCapacityCost(errorType) {
        return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
      }
      isRetryableError(errorType) {
        return errorType === "THROTTLING" || errorType === "TRANSIENT";
      }
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js
var AdaptiveRetryStrategy;
var init_AdaptiveRetryStrategy = __esm({
  "node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() {
    init_config4();
    init_DefaultRateLimiter();
    init_StandardRetryStrategy();
    AdaptiveRetryStrategy = class {
      constructor(maxAttemptsProvider, options) {
        this.maxAttemptsProvider = maxAttemptsProvider;
        this.mode = RETRY_MODES.ADAPTIVE;
        const { rateLimiter } = options ?? {};
        this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
        this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
      }
      async acquireInitialRetryToken(retryTokenScope) {
        await this.rateLimiter.getSendToken();
        return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
      }
      async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
        this.rateLimiter.updateClientSendingRate(errorInfo);
        return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
      }
      recordSuccess(token) {
        this.rateLimiter.updateClientSendingRate({});
        this.standardRetryStrategy.recordSuccess(token);
      }
    };
  }
});

// node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js
var init_ConfiguredRetryStrategy = __esm({
  "node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() {
    init_constants4();
    init_StandardRetryStrategy();
  }
});

// node_modules/@smithy/util-retry/dist-es/types.js
var init_types10 = __esm({
  "node_modules/@smithy/util-retry/dist-es/types.js"() {
  }
});

// node_modules/@smithy/util-retry/dist-es/index.js
var init_dist_es21 = __esm({
  "node_modules/@smithy/util-retry/dist-es/index.js"() {
    init_AdaptiveRetryStrategy();
    init_ConfiguredRetryStrategy();
    init_DefaultRateLimiter();
    init_StandardRetryStrategy();
    init_config4();
    init_constants4();
    init_types10();
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions6 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration5();
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery5(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest5;
var init_httpRequest5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest5 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest5({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery5(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest5.clone(this);
      }
    };
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var HttpResponse;
var init_httpResponse5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
    HttpResponse = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    };
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname5 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types11 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es22 = __esm({
  "node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions6();
    init_Field5();
    init_Fields5();
    init_httpHandler5();
    init_httpRequest5();
    init_httpResponse5();
    init_isValidHostname5();
    init_types11();
  }
});

// node_modules/uuid/dist/esm-browser/rng.js
function rng3() {
  if (!getRandomValues3) {
    getRandomValues3 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues3) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues3(rnds83);
}
var getRandomValues3, rnds83;
var init_rng3 = __esm({
  "node_modules/uuid/dist/esm-browser/rng.js"() {
    rnds83 = new Uint8Array(16);
  }
});

// node_modules/uuid/dist/esm-browser/stringify.js
function unsafeStringify3(arr2, offset5 = 0) {
  return byteToHex3[arr2[offset5 + 0]] + byteToHex3[arr2[offset5 + 1]] + byteToHex3[arr2[offset5 + 2]] + byteToHex3[arr2[offset5 + 3]] + "-" + byteToHex3[arr2[offset5 + 4]] + byteToHex3[arr2[offset5 + 5]] + "-" + byteToHex3[arr2[offset5 + 6]] + byteToHex3[arr2[offset5 + 7]] + "-" + byteToHex3[arr2[offset5 + 8]] + byteToHex3[arr2[offset5 + 9]] + "-" + byteToHex3[arr2[offset5 + 10]] + byteToHex3[arr2[offset5 + 11]] + byteToHex3[arr2[offset5 + 12]] + byteToHex3[arr2[offset5 + 13]] + byteToHex3[arr2[offset5 + 14]] + byteToHex3[arr2[offset5 + 15]];
}
var byteToHex3;
var init_stringify3 = __esm({
  "node_modules/uuid/dist/esm-browser/stringify.js"() {
    byteToHex3 = [];
    for (let i3 = 0; i3 < 256; ++i3) {
      byteToHex3.push((i3 + 256).toString(16).slice(1));
    }
  }
});

// node_modules/uuid/dist/esm-browser/native.js
var randomUUID3, native_default3;
var init_native3 = __esm({
  "node_modules/uuid/dist/esm-browser/native.js"() {
    randomUUID3 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
    native_default3 = {
      randomUUID: randomUUID3
    };
  }
});

// node_modules/uuid/dist/esm-browser/v4.js
function v43(options, buf, offset5) {
  if (native_default3.randomUUID && !buf && !options) {
    return native_default3.randomUUID();
  }
  options = options || {};
  const rnds = options.random || (options.rng || rng3)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset5 = offset5 || 0;
    for (let i3 = 0; i3 < 16; ++i3) {
      buf[offset5 + i3] = rnds[i3];
    }
    return buf;
  }
  return unsafeStringify3(rnds);
}
var v4_default3;
var init_v43 = __esm({
  "node_modules/uuid/dist/esm-browser/v4.js"() {
    init_native3();
    init_rng3();
    init_stringify3();
    v4_default3 = v43;
  }
});

// node_modules/uuid/dist/esm-browser/index.js
var init_esm_browser3 = __esm({
  "node_modules/uuid/dist/esm-browser/index.js"() {
    init_v43();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js
var init_defaultRetryQuota = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/defaultRetryQuota.js"() {
    init_dist_es21();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/delayDecider.js
var init_delayDecider = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() {
    init_dist_es21();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/retryDecider.js
var init_retryDecider = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() {
    init_dist_es20();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/util.js
var asSdkError;
var init_util2 = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/util.js"() {
    asSdkError = (error) => {
      if (error instanceof Error)
        return error;
      if (error instanceof Object)
        return Object.assign(new Error(), error);
      if (typeof error === "string")
        return new Error(error);
      return new Error(`AWS SDK error wrapper for ${error}`);
    };
  }
});

// node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js
var init_StandardRetryStrategy2 = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() {
    init_dist_es22();
    init_dist_es20();
    init_dist_es21();
    init_defaultRetryQuota();
    init_delayDecider();
    init_retryDecider();
    init_util2();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js
var init_AdaptiveRetryStrategy2 = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() {
    init_dist_es21();
    init_StandardRetryStrategy2();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/configurations.js
var resolveRetryConfig;
var init_configurations2 = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/configurations.js"() {
    init_dist_es13();
    init_dist_es21();
    resolveRetryConfig = (input) => {
      const { retryStrategy } = input;
      const maxAttempts = normalizeProvider(input.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
      return {
        ...input,
        maxAttempts,
        retryStrategy: async () => {
          if (retryStrategy) {
            return retryStrategy;
          }
          const retryMode = await normalizeProvider(input.retryMode)();
          if (retryMode === RETRY_MODES.ADAPTIVE) {
            return new AdaptiveRetryStrategy(maxAttempts);
          }
          return new StandardRetryStrategy(maxAttempts);
        }
      };
    };
  }
});

// node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js
var init_omitRetryHeadersMiddleware = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() {
    init_dist_es22();
    init_dist_es21();
  }
});

// node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
var NoOpLogger;
var init_NoOpLogger = __esm({
  "node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() {
    NoOpLogger = class {
      trace() {
      }
      debug() {
      }
      info() {
      }
      warn() {
      }
      error() {
      }
    };
  }
});

// node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights;
var init_MiddlewareStack = __esm({
  "node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() {
    getAllAliases = (name, aliases) => {
      const _aliases = [];
      if (name) {
        _aliases.push(name);
      }
      if (aliases) {
        for (const alias of aliases) {
          _aliases.push(alias);
        }
      }
      return _aliases;
    };
    getMiddlewareNameWithAliases = (name, aliases) => {
      return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
    };
    constructStack = () => {
      let absoluteEntries = [];
      let relativeEntries = [];
      let identifyOnResolve = false;
      const entriesNameSet = /* @__PURE__ */ new Set();
      const sort = (entries) => entries.sort((a3, b3) => stepWeights[b3.step] - stepWeights[a3.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a3.priority || "normal"]);
      const removeByName = (toRemove) => {
        let isRemoved = false;
        const filterCb = (entry) => {
          const aliases = getAllAliases(entry.name, entry.aliases);
          if (aliases.includes(toRemove)) {
            isRemoved = true;
            for (const alias of aliases) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        };
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      };
      const removeByReference = (toRemove) => {
        let isRemoved = false;
        const filterCb = (entry) => {
          if (entry.middleware === toRemove) {
            isRemoved = true;
            for (const alias of getAllAliases(entry.name, entry.aliases)) {
              entriesNameSet.delete(alias);
            }
            return false;
          }
          return true;
        };
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      };
      const cloneTo = (toStack) => {
        absoluteEntries.forEach((entry) => {
          toStack.add(entry.middleware, { ...entry });
        });
        relativeEntries.forEach((entry) => {
          toStack.addRelativeTo(entry.middleware, { ...entry });
        });
        toStack.identifyOnResolve?.(stack.identifyOnResolve());
        return toStack;
      };
      const expandRelativeMiddlewareList = (from) => {
        const expandedMiddlewareList = [];
        from.before.forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        expandedMiddlewareList.push(from);
        from.after.reverse().forEach((entry) => {
          if (entry.before.length === 0 && entry.after.length === 0) {
            expandedMiddlewareList.push(entry);
          } else {
            expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
          }
        });
        return expandedMiddlewareList;
      };
      const getMiddlewareList = (debug4 = false) => {
        const normalizedAbsoluteEntries = [];
        const normalizedRelativeEntries = [];
        const normalizedEntriesNameMap = {};
        absoluteEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedAbsoluteEntries.push(normalizedEntry);
        });
        relativeEntries.forEach((entry) => {
          const normalizedEntry = {
            ...entry,
            before: [],
            after: []
          };
          for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
            normalizedEntriesNameMap[alias] = normalizedEntry;
          }
          normalizedRelativeEntries.push(normalizedEntry);
        });
        normalizedRelativeEntries.forEach((entry) => {
          if (entry.toMiddleware) {
            const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
            if (toMiddleware === void 0) {
              if (debug4) {
                return;
              }
              throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`);
            }
            if (entry.relation === "after") {
              toMiddleware.after.push(entry);
            }
            if (entry.relation === "before") {
              toMiddleware.before.push(entry);
            }
          }
        });
        const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
          wholeList.push(...expandedMiddlewareList);
          return wholeList;
        }, []);
        return mainChain;
      };
      const stack = {
        add: (middleware, options = {}) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            step: "initialize",
            priority: "normal",
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a3) => a3 === alias));
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = absoluteEntries[toOverrideIndex];
                if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
                  throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);
                }
                absoluteEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          absoluteEntries.push(entry);
        },
        addRelativeTo: (middleware, options) => {
          const { name, override, aliases: _aliases } = options;
          const entry = {
            middleware,
            ...options
          };
          const aliases = getAllAliases(name, _aliases);
          if (aliases.length > 0) {
            if (aliases.some((alias) => entriesNameSet.has(alias))) {
              if (!override)
                throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
              for (const alias of aliases) {
                const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a3) => a3 === alias));
                if (toOverrideIndex === -1) {
                  continue;
                }
                const toOverride = relativeEntries[toOverrideIndex];
                if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
                  throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);
                }
                relativeEntries.splice(toOverrideIndex, 1);
              }
            }
            for (const alias of aliases) {
              entriesNameSet.add(alias);
            }
          }
          relativeEntries.push(entry);
        },
        clone: () => cloneTo(constructStack()),
        use: (plugin) => {
          plugin.applyToStack(stack);
        },
        remove: (toRemove) => {
          if (typeof toRemove === "string")
            return removeByName(toRemove);
          else
            return removeByReference(toRemove);
        },
        removeByTag: (toRemove) => {
          let isRemoved = false;
          const filterCb = (entry) => {
            const { tags, name, aliases: _aliases } = entry;
            if (tags && tags.includes(toRemove)) {
              const aliases = getAllAliases(name, _aliases);
              for (const alias of aliases) {
                entriesNameSet.delete(alias);
              }
              isRemoved = true;
              return false;
            }
            return true;
          };
          absoluteEntries = absoluteEntries.filter(filterCb);
          relativeEntries = relativeEntries.filter(filterCb);
          return isRemoved;
        },
        concat: (from) => {
          const cloned = cloneTo(constructStack());
          cloned.use(from);
          cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
          return cloned;
        },
        applyToStack: cloneTo,
        identify: () => {
          return getMiddlewareList(true).map((mw) => {
            const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
            return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
          });
        },
        identifyOnResolve(toggle) {
          if (typeof toggle === "boolean")
            identifyOnResolve = toggle;
          return identifyOnResolve;
        },
        resolve: (handler, context) => {
          for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
            handler = middleware(handler, context);
          }
          if (identifyOnResolve) {
            console.log(stack.identify());
          }
          return handler;
        }
      };
      return stack;
    };
    stepWeights = {
      initialize: 5,
      serialize: 4,
      build: 3,
      finalizeRequest: 2,
      deserialize: 1
    };
    priorityWeights = {
      high: 3,
      normal: 2,
      low: 1
    };
  }
});

// node_modules/@smithy/middleware-stack/dist-es/index.js
var init_dist_es23 = __esm({
  "node_modules/@smithy/middleware-stack/dist-es/index.js"() {
    init_MiddlewareStack();
  }
});

// node_modules/@smithy/smithy-client/dist-es/client.js
var Client2;
var init_client3 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/client.js"() {
    init_dist_es23();
    Client2 = class {
      constructor(config) {
        this.middlewareStack = constructStack();
        this.config = config;
      }
      send(command, optionsOrCb, cb) {
        const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
        const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
        const handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
        if (callback) {
          handler(command).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {
          });
        } else {
          return handler(command).then((result) => result.output);
        }
      }
      destroy() {
        if (this.config.requestHandler.destroy)
          this.config.requestHandler.destroy();
      }
    };
  }
});

// node_modules/@smithy/util-base64/dist-es/constants.browser.js
var alphabetByEncoding, alphabetByValue, bitsPerLetter, bitsPerByte, maxLetterValue;
var init_constants_browser = __esm({
  "node_modules/@smithy/util-base64/dist-es/constants.browser.js"() {
    alphabetByEncoding = {};
    alphabetByValue = new Array(64);
    for (let i3 = 0, start = "A".charCodeAt(0), limit2 = "Z".charCodeAt(0); i3 + start <= limit2; i3++) {
      const char = String.fromCharCode(i3 + start);
      alphabetByEncoding[char] = i3;
      alphabetByValue[i3] = char;
    }
    for (let i3 = 0, start = "a".charCodeAt(0), limit2 = "z".charCodeAt(0); i3 + start <= limit2; i3++) {
      const char = String.fromCharCode(i3 + start);
      const index2 = i3 + 26;
      alphabetByEncoding[char] = index2;
      alphabetByValue[index2] = char;
    }
    for (let i3 = 0; i3 < 10; i3++) {
      alphabetByEncoding[i3.toString(10)] = i3 + 52;
      const char = i3.toString(10);
      const index2 = i3 + 52;
      alphabetByEncoding[char] = index2;
      alphabetByValue[index2] = char;
    }
    alphabetByEncoding["+"] = 62;
    alphabetByValue[62] = "+";
    alphabetByEncoding["/"] = 63;
    alphabetByValue[63] = "/";
    bitsPerLetter = 6;
    bitsPerByte = 8;
    maxLetterValue = 63;
  }
});

// node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js
var fromBase64;
var init_fromBase64_browser = __esm({
  "node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js"() {
    init_constants_browser();
    fromBase64 = (input) => {
      let totalByteLength = input.length / 4 * 3;
      if (input.slice(-2) === "==") {
        totalByteLength -= 2;
      } else if (input.slice(-1) === "=") {
        totalByteLength--;
      }
      const out = new ArrayBuffer(totalByteLength);
      const dataView = new DataView(out);
      for (let i3 = 0; i3 < input.length; i3 += 4) {
        let bits = 0;
        let bitLength = 0;
        for (let j3 = i3, limit2 = i3 + 3; j3 <= limit2; j3++) {
          if (input[j3] !== "=") {
            if (!(input[j3] in alphabetByEncoding)) {
              throw new TypeError(`Invalid character ${input[j3]} in base64 string.`);
            }
            bits |= alphabetByEncoding[input[j3]] << (limit2 - j3) * bitsPerLetter;
            bitLength += bitsPerLetter;
          } else {
            bits >>= bitsPerLetter;
          }
        }
        const chunkOffset = i3 / 4 * 3;
        bits >>= bitLength % bitsPerByte;
        const byteLength = Math.floor(bitLength / bitsPerByte);
        for (let k3 = 0; k3 < byteLength; k3++) {
          const offset5 = (byteLength - k3 - 1) * bitsPerByte;
          dataView.setUint8(chunkOffset + k3, (bits & 255 << offset5) >> offset5);
        }
      }
      return new Uint8Array(out);
    };
  }
});

// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
var fromUtf8;
var init_fromUtf8_browser = __esm({
  "node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() {
    fromUtf8 = (input) => new TextEncoder().encode(input);
  }
});

// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var init_toUint8Array = __esm({
  "node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    init_fromUtf8_browser();
  }
});

// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
var init_toUtf8_browser = __esm({
  "node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() {
  }
});

// node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es24 = __esm({
  "node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    init_fromUtf8_browser();
    init_toUint8Array();
    init_toUtf8_browser();
  }
});

// node_modules/@smithy/util-base64/dist-es/toBase64.browser.js
function toBase64(_input) {
  let input;
  if (typeof _input === "string") {
    input = fromUtf8(_input);
  } else {
    input = _input;
  }
  const isArrayLike = typeof input === "object" && typeof input.length === "number";
  const isUint8Array = typeof input === "object" && typeof input.byteOffset === "number" && typeof input.byteLength === "number";
  if (!isArrayLike && !isUint8Array) {
    throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
  }
  let str2 = "";
  for (let i3 = 0; i3 < input.length; i3 += 3) {
    let bits = 0;
    let bitLength = 0;
    for (let j3 = i3, limit2 = Math.min(i3 + 3, input.length); j3 < limit2; j3++) {
      bits |= input[j3] << (limit2 - j3 - 1) * bitsPerByte;
      bitLength += bitsPerByte;
    }
    const bitClusterCount = Math.ceil(bitLength / bitsPerLetter);
    bits <<= bitClusterCount * bitsPerLetter - bitLength;
    for (let k3 = 1; k3 <= bitClusterCount; k3++) {
      const offset5 = (bitClusterCount - k3) * bitsPerLetter;
      str2 += alphabetByValue[(bits & maxLetterValue << offset5) >> offset5];
    }
    str2 += "==".slice(0, 4 - bitClusterCount);
  }
  return str2;
}
var init_toBase64_browser = __esm({
  "node_modules/@smithy/util-base64/dist-es/toBase64.browser.js"() {
    init_dist_es24();
    init_constants_browser();
  }
});

// node_modules/@smithy/util-base64/dist-es/index.js
var init_dist_es25 = __esm({
  "node_modules/@smithy/util-base64/dist-es/index.js"() {
    init_fromBase64_browser();
    init_toBase64_browser();
  }
});

// node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
var fromUtf82;
var init_fromUtf8_browser2 = __esm({
  "node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() {
    fromUtf82 = (input) => new TextEncoder().encode(input);
  }
});

// node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var init_toUint8Array2 = __esm({
  "node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    init_fromUtf8_browser2();
  }
});

// node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
var toUtf8;
var init_toUtf8_browser2 = __esm({
  "node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() {
    toUtf8 = (input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return new TextDecoder("utf-8").decode(input);
    };
  }
});

// node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es26 = __esm({
  "node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    init_fromUtf8_browser2();
    init_toUint8Array2();
    init_toUtf8_browser2();
  }
});

// node_modules/@smithy/util-stream/dist-es/blob/transforms.js
function transformToString(payload, encoding = "utf-8") {
  if (encoding === "base64") {
    return toBase64(payload);
  }
  return toUtf8(payload);
}
function transformFromString(str2, encoding) {
  if (encoding === "base64") {
    return Uint8ArrayBlobAdapter.mutate(fromBase64(str2));
  }
  return Uint8ArrayBlobAdapter.mutate(fromUtf82(str2));
}
var init_transforms = __esm({
  "node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() {
    init_dist_es25();
    init_dist_es26();
    init_Uint8ArrayBlobAdapter();
  }
});

// node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
var Uint8ArrayBlobAdapter;
var init_Uint8ArrayBlobAdapter = __esm({
  "node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() {
    init_transforms();
    Uint8ArrayBlobAdapter = class extends Uint8Array {
      static fromString(source, encoding = "utf-8") {
        switch (typeof source) {
          case "string":
            return transformFromString(source, encoding);
          default:
            throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
        }
      }
      static mutate(source) {
        Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype);
        return source;
      }
      transformToString(encoding = "utf-8") {
        return transformToString(this, encoding);
      }
    };
  }
});

// node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.browser.js
var init_getAwsChunkedEncodingStream_browser = __esm({
  "node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.browser.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions7 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration6();
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
var init_httpRequest6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var HttpResponse2;
var init_httpResponse6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
    HttpResponse2 = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    };
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname6 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types12 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es27 = __esm({
  "node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions7();
    init_Field6();
    init_Fields6();
    init_httpHandler6();
    init_httpRequest6();
    init_httpResponse6();
    init_isValidHostname6();
    init_types12();
  }
});

// node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
var escapeUri, hexEncode;
var init_escape_uri = __esm({
  "node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() {
    escapeUri = (uri2) => encodeURIComponent(uri2).replace(/[!'()*]/g, hexEncode);
    hexEncode = (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}`;
  }
});

// node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js
var init_escape_uri_path = __esm({
  "node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() {
    init_escape_uri();
  }
});

// node_modules/@smithy/util-uri-escape/dist-es/index.js
var init_dist_es28 = __esm({
  "node_modules/@smithy/util-uri-escape/dist-es/index.js"() {
    init_escape_uri();
    init_escape_uri_path();
  }
});

// node_modules/@smithy/querystring-builder/dist-es/index.js
function buildQueryString(query) {
  const parts = [];
  for (let key of Object.keys(query).sort()) {
    const value = query[key];
    key = escapeUri(key);
    if (Array.isArray(value)) {
      for (let i3 = 0, iLen = value.length; i3 < iLen; i3++) {
        parts.push(`${key}=${escapeUri(value[i3])}`);
      }
    } else {
      let qsEntry = key;
      if (value || typeof value === "string") {
        qsEntry += `=${escapeUri(value)}`;
      }
      parts.push(qsEntry);
    }
  }
  return parts.join("&");
}
var init_dist_es29 = __esm({
  "node_modules/@smithy/querystring-builder/dist-es/index.js"() {
    init_dist_es28();
  }
});

// node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js
function requestTimeout(timeoutInMs = 0) {
  return new Promise((resolve, reject) => {
    if (timeoutInMs) {
      setTimeout(() => {
        const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
        timeoutError.name = "TimeoutError";
        reject(timeoutError);
      }, timeoutInMs);
    }
  });
}
var init_request_timeout = __esm({
  "node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() {
  }
});

// node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js
var keepAliveSupport, FetchHttpHandler;
var init_fetch_http_handler = __esm({
  "node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() {
    init_dist_es27();
    init_dist_es29();
    init_request_timeout();
    keepAliveSupport = {
      supported: void 0
    };
    FetchHttpHandler = class {
      static create(instanceOrOptions) {
        if (typeof instanceOrOptions?.handle === "function") {
          return instanceOrOptions;
        }
        return new FetchHttpHandler(instanceOrOptions);
      }
      constructor(options) {
        if (typeof options === "function") {
          this.configProvider = options().then((opts) => opts || {});
        } else {
          this.config = options ?? {};
          this.configProvider = Promise.resolve(this.config);
        }
        if (keepAliveSupport.supported === void 0) {
          keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in new Request("https://[::1]"));
        }
      }
      destroy() {
      }
      async handle(request, { abortSignal } = {}) {
        if (!this.config) {
          this.config = await this.configProvider;
        }
        const requestTimeoutInMs = this.config.requestTimeout;
        const keepAlive = this.config.keepAlive === true;
        const credentials = this.config.credentials;
        if (abortSignal?.aborted) {
          const abortError = new Error("Request aborted");
          abortError.name = "AbortError";
          return Promise.reject(abortError);
        }
        let path = request.path;
        const queryString = buildQueryString(request.query || {});
        if (queryString) {
          path += `?${queryString}`;
        }
        if (request.fragment) {
          path += `#${request.fragment}`;
        }
        let auth = "";
        if (request.username != null || request.password != null) {
          const username = request.username ?? "";
          const password = request.password ?? "";
          auth = `${username}:${password}@`;
        }
        const { port, method } = request;
        const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`;
        const body = method === "GET" || method === "HEAD" ? void 0 : request.body;
        const requestOptions = {
          body,
          headers: new Headers(request.headers),
          method,
          credentials
        };
        if (body) {
          requestOptions.duplex = "half";
        }
        if (typeof AbortController !== "undefined") {
          requestOptions.signal = abortSignal;
        }
        if (keepAliveSupport.supported) {
          requestOptions.keepalive = keepAlive;
        }
        let removeSignalEventListener = () => {
        };
        const fetchRequest = new Request(url, requestOptions);
        const raceOfPromises = [
          fetch(fetchRequest).then((response) => {
            const fetchHeaders = response.headers;
            const transformedHeaders = {};
            for (const pair of fetchHeaders.entries()) {
              transformedHeaders[pair[0]] = pair[1];
            }
            const hasReadableStream = response.body != void 0;
            if (!hasReadableStream) {
              return response.blob().then((body2) => ({
                response: new HttpResponse2({
                  headers: transformedHeaders,
                  reason: response.statusText,
                  statusCode: response.status,
                  body: body2
                })
              }));
            }
            return {
              response: new HttpResponse2({
                headers: transformedHeaders,
                reason: response.statusText,
                statusCode: response.status,
                body: response.body
              })
            };
          }),
          requestTimeout(requestTimeoutInMs)
        ];
        if (abortSignal) {
          raceOfPromises.push(new Promise((resolve, reject) => {
            const onAbort = () => {
              const abortError = new Error("Request aborted");
              abortError.name = "AbortError";
              reject(abortError);
            };
            if (typeof abortSignal.addEventListener === "function") {
              const signal = abortSignal;
              signal.addEventListener("abort", onAbort, { once: true });
              removeSignalEventListener = () => signal.removeEventListener("abort", onAbort);
            } else {
              abortSignal.onabort = onAbort;
            }
          }));
        }
        return Promise.race(raceOfPromises).finally(removeSignalEventListener);
      }
      updateHttpClientConfig(key, value) {
        this.config = void 0;
        this.configProvider = this.configProvider.then((config) => {
          config[key] = value;
          return config;
        });
      }
      httpHandlerConfigs() {
        return this.config ?? {};
      }
    };
  }
});

// node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js
async function collectBlob(blob) {
  const base642 = await readToBase64(blob);
  const arrayBuffer = fromBase64(base642);
  return new Uint8Array(arrayBuffer);
}
async function collectStream(stream) {
  const chunks = [];
  const reader = stream.getReader();
  let isDone = false;
  let length = 0;
  while (!isDone) {
    const { done, value } = await reader.read();
    if (value) {
      chunks.push(value);
      length += value.length;
    }
    isDone = done;
  }
  const collected = new Uint8Array(length);
  let offset5 = 0;
  for (const chunk of chunks) {
    collected.set(chunk, offset5);
    offset5 += chunk.length;
  }
  return collected;
}
function readToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      if (reader.readyState !== 2) {
        return reject(new Error("Reader aborted too early"));
      }
      const result = reader.result ?? "";
      const commaIndex = result.indexOf(",");
      const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
      resolve(result.substring(dataOffset));
    };
    reader.onabort = () => reject(new Error("Read aborted"));
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(blob);
  });
}
var streamCollector;
var init_stream_collector = __esm({
  "node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() {
    init_dist_es25();
    streamCollector = (stream) => {
      if (typeof Blob === "function" && stream instanceof Blob) {
        return collectBlob(stream);
      }
      return collectStream(stream);
    };
  }
});

// node_modules/@smithy/fetch-http-handler/dist-es/index.js
var init_dist_es30 = __esm({
  "node_modules/@smithy/fetch-http-handler/dist-es/index.js"() {
    init_fetch_http_handler();
    init_stream_collector();
  }
});

// node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-es/index.js
function toHex(bytes) {
  let out = "";
  for (let i3 = 0; i3 < bytes.byteLength; i3++) {
    out += SHORT_TO_HEX[bytes[i3]];
  }
  return out;
}
var SHORT_TO_HEX, HEX_TO_SHORT;
var init_dist_es31 = __esm({
  "node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() {
    SHORT_TO_HEX = {};
    HEX_TO_SHORT = {};
    for (let i3 = 0; i3 < 256; i3++) {
      let encodedByte = i3.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX[i3] = encodedByte;
      HEX_TO_SHORT[encodedByte] = i3;
    }
  }
});

// node_modules/@smithy/util-stream/dist-es/stream-type-check.js
var isReadableStream;
var init_stream_type_check = __esm({
  "node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() {
    isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream);
  }
});

// node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js
var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED, sdkStreamMixin, isBlobInstance;
var init_sdk_stream_mixin_browser = __esm({
  "node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() {
    init_dist_es30();
    init_dist_es25();
    init_dist_es31();
    init_dist_es26();
    init_stream_type_check();
    ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
    sdkStreamMixin = (stream) => {
      if (!isBlobInstance(stream) && !isReadableStream(stream)) {
        const name = stream?.__proto__?.constructor?.name || stream;
        throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
      }
      let transformed = false;
      const transformToByteArray = async () => {
        if (transformed) {
          throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
        }
        transformed = true;
        return await streamCollector(stream);
      };
      const blobToWebStream = (blob) => {
        if (typeof blob.stream !== "function") {
          throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
        }
        return blob.stream();
      };
      return Object.assign(stream, {
        transformToByteArray,
        transformToString: async (encoding) => {
          const buf = await transformToByteArray();
          if (encoding === "base64") {
            return toBase64(buf);
          } else if (encoding === "hex") {
            return toHex(buf);
          } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
            return toUtf8(buf);
          } else if (typeof TextDecoder === "function") {
            return new TextDecoder(encoding).decode(buf);
          } else {
            throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
          }
        },
        transformToWebStream: () => {
          if (transformed) {
            throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
          }
          transformed = true;
          if (isBlobInstance(stream)) {
            return blobToWebStream(stream);
          } else if (isReadableStream(stream)) {
            return stream;
          } else {
            throw new Error(`Cannot transform payload to web stream, got ${stream}`);
          }
        }
      });
    };
    isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
  }
});

// node_modules/@smithy/util-stream/dist-es/splitStream.browser.js
var init_splitStream_browser = __esm({
  "node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() {
  }
});

// node_modules/@smithy/util-stream/dist-es/headStream.browser.js
var init_headStream_browser = __esm({
  "node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() {
  }
});

// node_modules/@smithy/util-stream/dist-es/index.js
var init_dist_es32 = __esm({
  "node_modules/@smithy/util-stream/dist-es/index.js"() {
    init_Uint8ArrayBlobAdapter();
    init_getAwsChunkedEncodingStream_browser();
    init_sdk_stream_mixin_browser();
    init_splitStream_browser();
    init_headStream_browser();
    init_stream_type_check();
  }
});

// node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js
var collectBody;
var init_collect_stream_body = __esm({
  "node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() {
    init_dist_es32();
    collectBody = async (streamBody = new Uint8Array(), context) => {
      if (streamBody instanceof Uint8Array) {
        return Uint8ArrayBlobAdapter.mutate(streamBody);
      }
      if (!streamBody) {
        return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
      }
      const fromContext = context.streamCollector(streamBody);
      return Uint8ArrayBlobAdapter.mutate(await fromContext);
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/command.js
var Command2, ClassBuilder;
var init_command2 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/command.js"() {
    init_dist_es23();
    init_dist_es2();
    Command2 = class {
      constructor() {
        this.middlewareStack = constructStack();
      }
      static classBuilder() {
        return new ClassBuilder();
      }
      resolveMiddlewareWithContext(clientStack, configuration2, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
        for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration2, options)) {
          this.middlewareStack.use(mw);
        }
        const stack = clientStack.concat(this.middlewareStack);
        const { logger: logger2 } = configuration2;
        const handlerExecutionContext = {
          logger: logger2,
          clientName,
          commandName,
          inputFilterSensitiveLog,
          outputFilterSensitiveLog,
          [SMITHY_CONTEXT_KEY]: {
            commandInstance: this,
            ...smithyContext
          },
          ...additionalContext
        };
        const { requestHandler } = configuration2;
        return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
      }
    };
    ClassBuilder = class {
      constructor() {
        this._init = () => {
        };
        this._ep = {};
        this._middlewareFn = () => [];
        this._commandName = "";
        this._clientName = "";
        this._additionalContext = {};
        this._smithyContext = {};
        this._inputFilterSensitiveLog = (_2) => _2;
        this._outputFilterSensitiveLog = (_2) => _2;
        this._serializer = null;
        this._deserializer = null;
      }
      init(cb) {
        this._init = cb;
      }
      ep(endpointParameterInstructions) {
        this._ep = endpointParameterInstructions;
        return this;
      }
      m(middlewareSupplier) {
        this._middlewareFn = middlewareSupplier;
        return this;
      }
      s(service, operation, smithyContext = {}) {
        this._smithyContext = {
          service,
          operation,
          ...smithyContext
        };
        return this;
      }
      c(additionalContext = {}) {
        this._additionalContext = additionalContext;
        return this;
      }
      n(clientName, commandName) {
        this._clientName = clientName;
        this._commandName = commandName;
        return this;
      }
      f(inputFilter = (_2) => _2, outputFilter = (_2) => _2) {
        this._inputFilterSensitiveLog = inputFilter;
        this._outputFilterSensitiveLog = outputFilter;
        return this;
      }
      ser(serializer) {
        this._serializer = serializer;
        return this;
      }
      de(deserializer) {
        this._deserializer = deserializer;
        return this;
      }
      build() {
        const closure = this;
        let CommandRef;
        return CommandRef = class extends Command2 {
          static getEndpointParameterInstructions() {
            return closure._ep;
          }
          constructor(...[input]) {
            super();
            this.serialize = closure._serializer;
            this.deserialize = closure._deserializer;
            this.input = input ?? {};
            closure._init(this);
          }
          resolveMiddleware(stack, configuration2, options) {
            return this.resolveMiddlewareWithContext(stack, configuration2, options, {
              CommandCtor: CommandRef,
              middlewareFn: closure._middlewareFn,
              clientName: closure._clientName,
              commandName: closure._commandName,
              inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
              outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
              smithyContext: closure._smithyContext,
              additionalContext: closure._additionalContext
            });
          }
        };
      }
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/constants.js
var SENSITIVE_STRING;
var init_constants5 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/constants.js"() {
    SENSITIVE_STRING = "***SensitiveInformation***";
  }
});

// node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js
var createAggregatedClient;
var init_create_aggregated_client = __esm({
  "node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() {
    createAggregatedClient = (commands3, Client3) => {
      for (const command of Object.keys(commands3)) {
        const CommandCtor = commands3[command];
        const methodImpl = async function(args, optionsOrCb, cb) {
          const command2 = new CommandCtor(args);
          if (typeof optionsOrCb === "function") {
            this.send(command2, optionsOrCb);
          } else if (typeof cb === "function") {
            if (typeof optionsOrCb !== "object")
              throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
            this.send(command2, optionsOrCb || {}, cb);
          } else {
            return this.send(command2, optionsOrCb);
          }
        };
        const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
        Client3.prototype[methodName] = methodImpl;
      }
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/parse-utils.js
var expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectString, strictParseDouble, strictParseFloat32, NUMBER_REGEX, parseNumber, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger;
var init_parse_utils = __esm({
  "node_modules/@smithy/smithy-client/dist-es/parse-utils.js"() {
    expectNumber = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        const parsed = parseFloat(value);
        if (!Number.isNaN(parsed)) {
          if (String(parsed) !== String(value)) {
            logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
          }
          return parsed;
        }
      }
      if (typeof value === "number") {
        return value;
      }
      throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
    };
    MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
    expectFloat32 = (value) => {
      const expected = expectNumber(value);
      if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
        if (Math.abs(expected) > MAX_FLOAT) {
          throw new TypeError(`Expected 32-bit float, got ${value}`);
        }
      }
      return expected;
    };
    expectLong = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (Number.isInteger(value) && !Number.isNaN(value)) {
        return value;
      }
      throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
    };
    expectInt32 = (value) => expectSizedInt(value, 32);
    expectShort = (value) => expectSizedInt(value, 16);
    expectByte = (value) => expectSizedInt(value, 8);
    expectSizedInt = (value, size4) => {
      const expected = expectLong(value);
      if (expected !== void 0 && castInt(expected, size4) !== expected) {
        throw new TypeError(`Expected ${size4}-bit integer, got ${value}`);
      }
      return expected;
    };
    castInt = (value, size4) => {
      switch (size4) {
        case 32:
          return Int32Array.of(value)[0];
        case 16:
          return Int16Array.of(value)[0];
        case 8:
          return Int8Array.of(value)[0];
      }
    };
    expectNonNull = (value, location2) => {
      if (value === null || value === void 0) {
        if (location2) {
          throw new TypeError(`Expected a non-null value for ${location2}`);
        }
        throw new TypeError("Expected a non-null value");
      }
      return value;
    };
    expectString = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value === "string") {
        return value;
      }
      if (["boolean", "number", "bigint"].includes(typeof value)) {
        logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
        return String(value);
      }
      throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
    };
    strictParseDouble = (value) => {
      if (typeof value == "string") {
        return expectNumber(parseNumber(value));
      }
      return expectNumber(value);
    };
    strictParseFloat32 = (value) => {
      if (typeof value == "string") {
        return expectFloat32(parseNumber(value));
      }
      return expectFloat32(value);
    };
    NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
    parseNumber = (value) => {
      const matches = value.match(NUMBER_REGEX);
      if (matches === null || matches[0].length !== value.length) {
        throw new TypeError(`Expected real number, got implicit NaN`);
      }
      return parseFloat(value);
    };
    strictParseInt32 = (value) => {
      if (typeof value === "string") {
        return expectInt32(parseNumber(value));
      }
      return expectInt32(value);
    };
    strictParseShort = (value) => {
      if (typeof value === "string") {
        return expectShort(parseNumber(value));
      }
      return expectShort(value);
    };
    strictParseByte = (value) => {
      if (typeof value === "string") {
        return expectByte(parseNumber(value));
      }
      return expectByte(value);
    };
    stackTraceWarning = (message) => {
      return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s4) => !s4.includes("stackTraceWarning")).join("\n");
    };
    logger = {
      warn: console.warn
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/date-utils.js
var MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseEpochTimestamp, buildDate, FIFTY_YEARS_IN_MILLIS, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear2, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
var init_date_utils = __esm({
  "node_modules/@smithy/smithy-client/dist-es/date-utils.js"() {
    init_parse_utils();
    MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
    parseRfc3339DateTime = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
      const year = strictParseShort(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
    };
    RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
    parseRfc3339DateTimeWithOffset = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      if (typeof value !== "string") {
        throw new TypeError("RFC-3339 date-times must be expressed as strings");
      }
      const match2 = RFC3339_WITH_OFFSET.exec(value);
      if (!match2) {
        throw new TypeError("Invalid RFC-3339 date-time value");
      }
      const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
      const year = strictParseShort(stripLeadingZeroes(yearStr));
      const month = parseDateValue(monthStr, "month", 1, 12);
      const day = parseDateValue(dayStr, "day", 1, 31);
      const date2 = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
      if (offsetStr.toUpperCase() != "Z") {
        date2.setTime(date2.getTime() - parseOffsetToMilliseconds(offsetStr));
      }
      return date2;
    };
    IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
    ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
    parseEpochTimestamp = (value) => {
      if (value === null || value === void 0) {
        return void 0;
      }
      let valueAsDouble;
      if (typeof value === "number") {
        valueAsDouble = value;
      } else if (typeof value === "string") {
        valueAsDouble = strictParseDouble(value);
      } else if (typeof value === "object" && value.tag === 1) {
        valueAsDouble = value.value;
      } else {
        throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
      }
      if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
        throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
      }
      return new Date(Math.round(valueAsDouble * 1e3));
    };
    buildDate = (year, month, day, time2) => {
      const adjustedMonth = month - 1;
      validateDayOfMonth(year, adjustedMonth, day);
      return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time2.hours, "hour", 0, 23), parseDateValue(time2.minutes, "minute", 0, 59), parseDateValue(time2.seconds, "seconds", 0, 60), parseMilliseconds(time2.fractionalMilliseconds)));
    };
    FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
    DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    validateDayOfMonth = (year, month, day) => {
      let maxDays = DAYS_IN_MONTH[month];
      if (month === 1 && isLeapYear2(year)) {
        maxDays = 29;
      }
      if (day > maxDays) {
        throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
      }
    };
    isLeapYear2 = (year) => {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    };
    parseDateValue = (value, type, lower, upper) => {
      const dateVal = strictParseByte(stripLeadingZeroes(value));
      if (dateVal < lower || dateVal > upper) {
        throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);
      }
      return dateVal;
    };
    parseMilliseconds = (value) => {
      if (value === null || value === void 0) {
        return 0;
      }
      return strictParseFloat32("0." + value) * 1e3;
    };
    parseOffsetToMilliseconds = (value) => {
      const directionStr = value[0];
      let direction = 1;
      if (directionStr == "+") {
        direction = 1;
      } else if (directionStr == "-") {
        direction = -1;
      } else {
        throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
      }
      const hour = Number(value.substring(1, 3));
      const minute = Number(value.substring(4, 6));
      return direction * (hour * 60 + minute) * 60 * 1e3;
    };
    stripLeadingZeroes = (value) => {
      let idx = 0;
      while (idx < value.length - 1 && value.charAt(idx) === "0") {
        idx++;
      }
      if (idx === 0) {
        return value;
      }
      return value.slice(idx);
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/exceptions.js
var ServiceException, decorateServiceException;
var init_exceptions = __esm({
  "node_modules/@smithy/smithy-client/dist-es/exceptions.js"() {
    ServiceException = class extends Error {
      constructor(options) {
        super(options.message);
        Object.setPrototypeOf(this, ServiceException.prototype);
        this.name = options.name;
        this.$fault = options.$fault;
        this.$metadata = options.$metadata;
      }
    };
    decorateServiceException = (exception, additions = {}) => {
      Object.entries(additions).filter(([, v5]) => v5 !== void 0).forEach(([k3, v5]) => {
        if (exception[k3] == void 0 || exception[k3] === "") {
          exception[k3] = v5;
        }
      });
      const message = exception.message || exception.Message || "UnknownError";
      exception.message = message;
      delete exception.Message;
      return exception;
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
var throwDefaultError, withBaseException, deserializeMetadata;
var init_default_error_handler = __esm({
  "node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() {
    init_exceptions();
    throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
      const $metadata = deserializeMetadata(output);
      const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
      const response = new exceptionCtor({
        name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
        $fault: "client",
        $metadata
      });
      throw decorateServiceException(response, parsedBody);
    };
    withBaseException = (ExceptionCtor) => {
      return ({ output, parsedBody, errorCode }) => {
        throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
      };
    };
    deserializeMetadata = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
  }
});

// node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
var loadConfigsForDefaultMode;
var init_defaults_mode = __esm({
  "node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() {
    loadConfigsForDefaultMode = (mode) => {
      switch (mode) {
        case "standard":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "in-region":
          return {
            retryMode: "standard",
            connectionTimeout: 1100
          };
        case "cross-region":
          return {
            retryMode: "standard",
            connectionTimeout: 3100
          };
        case "mobile":
          return {
            retryMode: "standard",
            connectionTimeout: 3e4
          };
        default:
          return {};
      }
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js
var init_emitWarningIfUnsupportedVersion = __esm({
  "node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() {
  }
});

// node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
var getChecksumConfiguration2, resolveChecksumRuntimeConfig2;
var init_checksum3 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() {
    init_dist_es2();
    getChecksumConfiguration2 = (runtimeConfig) => {
      const checksumAlgorithms = [];
      for (const id in AlgorithmId) {
        const algorithmId = AlgorithmId[id];
        if (runtimeConfig[algorithmId] === void 0) {
          continue;
        }
        checksumAlgorithms.push({
          algorithmId: () => algorithmId,
          checksumConstructor: () => runtimeConfig[algorithmId]
        });
      }
      return {
        _checksumAlgorithms: checksumAlgorithms,
        addChecksumAlgorithm(algo) {
          this._checksumAlgorithms.push(algo);
        },
        checksumAlgorithms() {
          return this._checksumAlgorithms;
        }
      };
    };
    resolveChecksumRuntimeConfig2 = (clientConfig) => {
      const runtimeConfig = {};
      clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
        runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
      });
      return runtimeConfig;
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
var getRetryConfiguration, resolveRetryRuntimeConfig;
var init_retry2 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() {
    getRetryConfiguration = (runtimeConfig) => {
      let _retryStrategy = runtimeConfig.retryStrategy;
      return {
        setRetryStrategy(retryStrategy) {
          _retryStrategy = retryStrategy;
        },
        retryStrategy() {
          return _retryStrategy;
        }
      };
    };
    resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
      const runtimeConfig = {};
      runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
      return runtimeConfig;
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig;
var init_defaultExtensionConfiguration2 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() {
    init_checksum3();
    init_retry2();
    getDefaultExtensionConfiguration = (runtimeConfig) => {
      return {
        ...getChecksumConfiguration2(runtimeConfig),
        ...getRetryConfiguration(runtimeConfig)
      };
    };
    resolveDefaultRuntimeConfig = (config) => {
      return {
        ...resolveChecksumRuntimeConfig2(config),
        ...resolveRetryRuntimeConfig(config)
      };
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/extensions/index.js
var init_extensions8 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() {
    init_defaultExtensionConfiguration2();
  }
});

// node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js
function extendedEncodeURIComponent(str2) {
  return encodeURIComponent(str2).replace(/[!'()*]/g, function(c4) {
    return "%" + c4.charCodeAt(0).toString(16).toUpperCase();
  });
}
var init_extended_encode_uri_component = __esm({
  "node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() {
  }
});

// node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js
var init_get_array_if_single_item = __esm({
  "node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() {
  }
});

// node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js
var getValueFromTextNode;
var init_get_value_from_text_node = __esm({
  "node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() {
    getValueFromTextNode = (obj) => {
      const textNodeName = "#text";
      for (const key in obj) {
        if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
          obj[key] = obj[key][textNodeName];
        } else if (typeof obj[key] === "object" && obj[key] !== null) {
          obj[key] = getValueFromTextNode(obj[key]);
        }
      }
      return obj;
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/lazy-json.js
var StringWrapper;
var init_lazy_json = __esm({
  "node_modules/@smithy/smithy-client/dist-es/lazy-json.js"() {
    StringWrapper = function() {
      const Class = Object.getPrototypeOf(this).constructor;
      const Constructor = Function.bind.apply(String, [null, ...arguments]);
      const instance = new Constructor();
      Object.setPrototypeOf(instance, Class.prototype);
      return instance;
    };
    StringWrapper.prototype = Object.create(String.prototype, {
      constructor: {
        value: StringWrapper,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Object.setPrototypeOf(StringWrapper, String);
  }
});

// node_modules/@smithy/smithy-client/dist-es/object-mapping.js
var take, applyInstruction, nonNullish, pass;
var init_object_mapping = __esm({
  "node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() {
    take = (source, instructions) => {
      const out = {};
      for (const key in instructions) {
        applyInstruction(out, source, instructions, key);
      }
      return out;
    };
    applyInstruction = (target, source, instructions, targetKey) => {
      if (source !== null) {
        let instruction = instructions[targetKey];
        if (typeof instruction === "function") {
          instruction = [, instruction];
        }
        const [filter3 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
        if (typeof filter3 === "function" && filter3(source[sourceKey]) || typeof filter3 !== "function" && !!filter3) {
          target[targetKey] = valueFn(source[sourceKey]);
        }
        return;
      }
      let [filter2, value] = instructions[targetKey];
      if (typeof value === "function") {
        let _value;
        const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed) {
          target[targetKey] = _value;
        } else if (customFilterPassed) {
          target[targetKey] = value();
        }
      } else {
        const defaultFilterPassed = filter2 === void 0 && value != null;
        const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
        if (defaultFilterPassed || customFilterPassed) {
          target[targetKey] = value;
        }
      }
    };
    nonNullish = (_2) => _2 != null;
    pass = (_2) => _2;
  }
});

// node_modules/@smithy/smithy-client/dist-es/resolve-path.js
var init_resolve_path = __esm({
  "node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() {
    init_extended_encode_uri_component();
  }
});

// node_modules/@smithy/smithy-client/dist-es/ser-utils.js
var init_ser_utils = __esm({
  "node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() {
  }
});

// node_modules/@smithy/smithy-client/dist-es/serde-json.js
var _json;
var init_serde_json = __esm({
  "node_modules/@smithy/smithy-client/dist-es/serde-json.js"() {
    _json = (obj) => {
      if (obj == null) {
        return {};
      }
      if (Array.isArray(obj)) {
        return obj.filter((_2) => _2 != null).map(_json);
      }
      if (typeof obj === "object") {
        const target = {};
        for (const key of Object.keys(obj)) {
          if (obj[key] == null) {
            continue;
          }
          target[key] = _json(obj[key]);
        }
        return target;
      }
      return obj;
    };
  }
});

// node_modules/@smithy/smithy-client/dist-es/split-every.js
var init_split_every = __esm({
  "node_modules/@smithy/smithy-client/dist-es/split-every.js"() {
  }
});

// node_modules/@smithy/smithy-client/dist-es/index.js
var init_dist_es33 = __esm({
  "node_modules/@smithy/smithy-client/dist-es/index.js"() {
    init_NoOpLogger();
    init_client3();
    init_collect_stream_body();
    init_command2();
    init_constants5();
    init_create_aggregated_client();
    init_date_utils();
    init_default_error_handler();
    init_defaults_mode();
    init_emitWarningIfUnsupportedVersion();
    init_extensions8();
    init_exceptions();
    init_extended_encode_uri_component();
    init_get_array_if_single_item();
    init_get_value_from_text_node();
    init_lazy_json();
    init_object_mapping();
    init_parse_utils();
    init_resolve_path();
    init_ser_utils();
    init_serde_json();
    init_split_every();
  }
});

// node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js
var isStreamingPayload;
var init_isStreamingPayload_browser = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js"() {
    isStreamingPayload = (request) => request?.body instanceof ReadableStream;
  }
});

// node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js
var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint;
var init_retryMiddleware = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() {
    init_dist_es22();
    init_dist_es20();
    init_dist_es33();
    init_dist_es21();
    init_esm_browser3();
    init_isStreamingPayload_browser();
    init_util2();
    retryMiddleware = (options) => (next, context) => async (args) => {
      let retryStrategy = await options.retryStrategy();
      const maxAttempts = await options.maxAttempts();
      if (isRetryStrategyV2(retryStrategy)) {
        retryStrategy = retryStrategy;
        let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
        let lastError = new Error();
        let attempts = 0;
        let totalRetryDelay = 0;
        const { request } = args;
        const isRequest = HttpRequest5.isInstance(request);
        if (isRequest) {
          request.headers[INVOCATION_ID_HEADER] = v4_default3();
        }
        while (true) {
          try {
            if (isRequest) {
              request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
            }
            const { response, output } = await next(args);
            retryStrategy.recordSuccess(retryToken);
            output.$metadata.attempts = attempts + 1;
            output.$metadata.totalRetryDelay = totalRetryDelay;
            return { response, output };
          } catch (e3) {
            const retryErrorInfo = getRetryErrorInfo(e3);
            lastError = asSdkError(e3);
            if (isRequest && isStreamingPayload(request)) {
              (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request.");
              throw lastError;
            }
            try {
              retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
            } catch (refreshError) {
              if (!lastError.$metadata) {
                lastError.$metadata = {};
              }
              lastError.$metadata.attempts = attempts + 1;
              lastError.$metadata.totalRetryDelay = totalRetryDelay;
              throw lastError;
            }
            attempts = retryToken.getRetryCount();
            const delay = retryToken.getRetryDelay();
            totalRetryDelay += delay;
            await new Promise((resolve) => setTimeout(resolve, delay));
          }
        }
      } else {
        retryStrategy = retryStrategy;
        if (retryStrategy?.mode)
          context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
        return retryStrategy.retry(next, args);
      }
    };
    isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
    getRetryErrorInfo = (error) => {
      const errorInfo = {
        error,
        errorType: getRetryErrorType(error)
      };
      const retryAfterHint = getRetryAfterHint(error.$response);
      if (retryAfterHint) {
        errorInfo.retryAfterHint = retryAfterHint;
      }
      return errorInfo;
    };
    getRetryErrorType = (error) => {
      if (isThrottlingError(error))
        return "THROTTLING";
      if (isTransientError(error))
        return "TRANSIENT";
      if (isServerError(error))
        return "SERVER_ERROR";
      return "CLIENT_ERROR";
    };
    retryMiddlewareOptions = {
      name: "retryMiddleware",
      tags: ["RETRY"],
      step: "finalizeRequest",
      priority: "high",
      override: true
    };
    getRetryPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
      }
    });
    getRetryAfterHint = (response) => {
      if (!HttpResponse.isInstance(response))
        return;
      const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
      if (!retryAfterHeaderName)
        return;
      const retryAfter = response.headers[retryAfterHeaderName];
      const retryAfterSeconds = Number(retryAfter);
      if (!Number.isNaN(retryAfterSeconds))
        return new Date(retryAfterSeconds * 1e3);
      const retryAfterDate = new Date(retryAfter);
      return retryAfterDate;
    };
  }
});

// node_modules/@smithy/middleware-retry/dist-es/index.js
var init_dist_es34 = __esm({
  "node_modules/@smithy/middleware-retry/dist-es/index.js"() {
    init_AdaptiveRetryStrategy2();
    init_StandardRetryStrategy2();
    init_configurations2();
    init_delayDecider();
    init_omitRetryHeadersMiddleware();
    init_retryDecider();
    init_retryMiddleware();
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
var httpSigningMiddlewareOptions, getHttpSigningPlugin;
var init_getHttpSigningMiddleware = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
    init_dist_es34();
    init_httpSigningMiddleware();
    httpSigningMiddlewareOptions = {
      step: "finalizeRequest",
      tags: ["HTTP_SIGNING"],
      name: "httpSigningMiddleware",
      aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
      override: true,
      relation: "after",
      toMiddleware: retryMiddlewareOptions.name
    };
    getHttpSigningPlugin = (config) => ({
      applyToStack: (clientStack) => {
        clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
      }
    });
  }
});

// node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
var init_middleware_http_signing = __esm({
  "node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
    init_httpSigningMiddleware();
    init_getHttpSigningMiddleware();
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
var DefaultIdentityProviderConfig;
var init_DefaultIdentityProviderConfig = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
    DefaultIdentityProviderConfig = class {
      constructor(config) {
        this.authSchemes = /* @__PURE__ */ new Map();
        for (const [key, value] of Object.entries(config)) {
          if (value !== void 0) {
            this.authSchemes.set(key, value);
          }
        }
      }
      getIdentityProvider(schemeId) {
        return this.authSchemes.get(schemeId);
      }
    };
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
var init_httpApiKeyAuth = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
    init_dist_es19();
    init_dist_es2();
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
var init_httpBearerAuth = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
    init_dist_es19();
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
var NoAuthSigner;
var init_noAuth = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
    NoAuthSigner = class {
      async sign(httpRequest, identity, signingProperties) {
        return httpRequest;
      }
    };
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
var init_httpAuthSchemes = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
    init_httpApiKeyAuth();
    init_httpBearerAuth();
    init_noAuth();
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
var init_memoizeIdentityProvider = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
    createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
    EXPIRATION_MS = 3e5;
    isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
    doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
    memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
      if (provider === void 0) {
        return void 0;
      }
      const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
      let resolved;
      let pending;
      let hasResult;
      let isConstant = false;
      const coalesceProvider = async (options) => {
        if (!pending) {
          pending = normalizedProvider(options);
        }
        try {
          resolved = await pending;
          hasResult = true;
          isConstant = false;
        } finally {
          pending = void 0;
        }
        return resolved;
      };
      if (isExpired === void 0) {
        return async (options) => {
          if (!hasResult || options?.forceRefresh) {
            resolved = await coalesceProvider(options);
          }
          return resolved;
        };
      }
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider(options);
        }
        if (isConstant) {
          return resolved;
        }
        if (!requiresRefresh(resolved)) {
          isConstant = true;
          return resolved;
        }
        if (isExpired(resolved)) {
          await coalesceProvider(options);
          return resolved;
        }
        return resolved;
      };
    };
  }
});

// node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
var init_util_identity_and_auth = __esm({
  "node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
    init_DefaultIdentityProviderConfig();
    init_httpAuthSchemes();
    init_memoizeIdentityProvider();
  }
});

// node_modules/@smithy/core/dist-es/getSmithyContext.js
var init_getSmithyContext2 = __esm({
  "node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
    init_dist_es2();
  }
});

// node_modules/@smithy/core/dist-es/normalizeProvider.js
var normalizeProvider2;
var init_normalizeProvider2 = __esm({
  "node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
    normalizeProvider2 = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
  }
});

// node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
var init_requestBuilder = __esm({
  "node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
    init_dist_es19();
    init_dist_es33();
  }
});

// node_modules/@smithy/core/dist-es/pagination/createPaginator.js
function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
  return async function* paginateOperation(config, input, ...additionalArguments) {
    let token = config.startingToken || void 0;
    let hasNext = true;
    let page;
    while (hasNext) {
      input[inputTokenName] = token;
      if (pageSizeTokenName) {
        input[pageSizeTokenName] = input[pageSizeTokenName] ?? config.pageSize;
      }
      if (config.client instanceof ClientCtor) {
        page = await makePagedClientRequest(CommandCtor, config.client, input, ...additionalArguments);
      } else {
        throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
      }
      yield page;
      const prevToken = token;
      token = get(page, outputTokenName);
      hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
    }
    return void 0;
  };
}
var makePagedClientRequest, get;
var init_createPaginator = __esm({
  "node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
    makePagedClientRequest = async (CommandCtor, client2, input, ...args) => {
      return await client2.send(new CommandCtor(input), ...args);
    };
    get = (fromObject, path) => {
      let cursor = fromObject;
      const pathComponents = path.split(".");
      for (const step of pathComponents) {
        if (!cursor || typeof cursor !== "object") {
          return void 0;
        }
        cursor = cursor[step];
      }
      return cursor;
    };
  }
});

// node_modules/@smithy/core/dist-es/index.js
var init_dist_es35 = __esm({
  "node_modules/@smithy/core/dist-es/index.js"() {
    init_middleware_http_auth_scheme();
    init_middleware_http_signing();
    init_util_identity_and_auth();
    init_getSmithyContext2();
    init_normalizeProvider2();
    init_requestBuilder();
    init_createPaginator();
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions9 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration7();
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery6(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest6;
var init_httpRequest7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest6 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest6({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery6(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest6.clone(this);
      }
    };
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname7 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types13 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es36 = __esm({
  "node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions9();
    init_Field7();
    init_Fields7();
    init_httpHandler7();
    init_httpRequest7();
    init_httpResponse7();
    init_isValidHostname7();
    init_types13();
  }
});

// node_modules/@smithy/middleware-content-length/dist-es/index.js
function contentLengthMiddleware(bodyLengthChecker) {
  return (next) => async (args) => {
    const request = args.request;
    if (HttpRequest6.isInstance(request)) {
      const { body, headers } = request;
      if (body && Object.keys(headers).map((str2) => str2.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
        try {
          const length = bodyLengthChecker(body);
          request.headers = {
            ...request.headers,
            [CONTENT_LENGTH_HEADER]: String(length)
          };
        } catch (error) {
        }
      }
    }
    return next({
      ...args,
      request
    });
  };
}
var CONTENT_LENGTH_HEADER, contentLengthMiddlewareOptions, getContentLengthPlugin;
var init_dist_es37 = __esm({
  "node_modules/@smithy/middleware-content-length/dist-es/index.js"() {
    init_dist_es36();
    CONTENT_LENGTH_HEADER = "content-length";
    contentLengthMiddlewareOptions = {
      step: "build",
      tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
      name: "contentLengthMiddleware",
      override: true
    };
    getContentLengthPlugin = (options) => ({
      applyToStack: (clientStack) => {
        clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
      }
    });
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
var init_emitWarningIfUnsupportedVersion2 = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
var init_client4 = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
    init_emitWarningIfUnsupportedVersion2();
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions10 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration8();
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery7(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest7;
var init_httpRequest8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest7 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest7({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery7(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest7.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var HttpResponse3;
var init_httpResponse8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
    HttpResponse3 = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname8 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types14 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es38 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions10();
    init_Field8();
    init_Fields8();
    init_httpHandler8();
    init_httpRequest8();
    init_httpResponse8();
    init_isValidHostname8();
    init_types14();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
var getDateHeader;
var init_getDateHeader = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
    init_dist_es38();
    getDateHeader = (response) => HttpResponse3.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0;
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
var getSkewCorrectedDate;
var init_getSkewCorrectedDate = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
    getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
var isClockSkewed;
var init_isClockSkewed = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
    init_getSkewCorrectedDate();
    isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
var getUpdatedSystemClockOffset;
var init_getUpdatedSystemClockOffset = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
    init_isClockSkewed();
    getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
      const clockTimeInMs = Date.parse(clockTime);
      if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
        return clockTimeInMs - Date.now();
      }
      return currentSystemClockOffset;
    };
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
var init_utils5 = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
    init_getDateHeader();
    init_getSkewCorrectedDate();
    init_getUpdatedSystemClockOffset();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer;
var init_AwsSdkSigV4Signer = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
    init_dist_es38();
    init_utils5();
    throwSigningPropertyError = (name, property) => {
      if (!property) {
        throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
      }
      return property;
    };
    validateSigningProperties = async (signingProperties) => {
      const context = throwSigningPropertyError("context", signingProperties.context);
      const config = throwSigningPropertyError("config", signingProperties.config);
      const authScheme = context.endpointV2?.properties?.authSchemes?.[0];
      const signerFunction = throwSigningPropertyError("signer", config.signer);
      const signer = await signerFunction(authScheme);
      const signingRegion = signingProperties?.signingRegion;
      const signingRegionSet = signingProperties?.signingRegionSet;
      const signingName = signingProperties?.signingName;
      return {
        config,
        signer,
        signingRegion,
        signingRegionSet,
        signingName
      };
    };
    AwsSdkSigV4Signer = class {
      async sign(httpRequest, identity, signingProperties) {
        if (!HttpRequest7.isInstance(httpRequest)) {
          throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
        }
        const validatedProps = await validateSigningProperties(signingProperties);
        const { config, signer } = validatedProps;
        let { signingRegion, signingName } = validatedProps;
        const handlerExecutionContext = signingProperties.context;
        if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
          const [first, second2] = handlerExecutionContext.authSchemes;
          if (first?.name === "sigv4a" && second2?.name === "sigv4") {
            signingRegion = second2?.signingRegion ?? signingRegion;
            signingName = second2?.signingName ?? signingName;
          }
        }
        const signedRequest = await signer.sign(httpRequest, {
          signingDate: getSkewCorrectedDate(config.systemClockOffset),
          signingRegion,
          signingService: signingName
        });
        return signedRequest;
      }
      errorHandler(signingProperties) {
        return (error) => {
          const serverTime = error.ServerTime ?? getDateHeader(error.$response);
          if (serverTime) {
            const config = throwSigningPropertyError("config", signingProperties.config);
            const initialSystemClockOffset = config.systemClockOffset;
            config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
            const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
            if (clockSkewCorrected && error.$metadata) {
              error.$metadata.clockSkewCorrected = true;
            }
          }
          throw error;
        };
      }
      successHandler(httpResponse, signingProperties) {
        const dateHeader = getDateHeader(httpResponse);
        if (dateHeader) {
          const config = throwSigningPropertyError("config", signingProperties.config);
          config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
        }
      }
    };
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
var init_resolveAwsSdkSigV4AConfig = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
    init_dist_es35();
    init_dist_es();
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/util-hex-encoding/dist-es/index.js
function fromHex(encoded) {
  if (encoded.length % 2 !== 0) {
    throw new Error("Hex encoded strings must have an even number length");
  }
  const out = new Uint8Array(encoded.length / 2);
  for (let i3 = 0; i3 < encoded.length; i3 += 2) {
    const encodedByte = encoded.slice(i3, i3 + 2).toLowerCase();
    if (encodedByte in HEX_TO_SHORT2) {
      out[i3 / 2] = HEX_TO_SHORT2[encodedByte];
    } else {
      throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
    }
  }
  return out;
}
function toHex2(bytes) {
  let out = "";
  for (let i3 = 0; i3 < bytes.byteLength; i3++) {
    out += SHORT_TO_HEX2[bytes[i3]];
  }
  return out;
}
var SHORT_TO_HEX2, HEX_TO_SHORT2;
var init_dist_es39 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/util-hex-encoding/dist-es/index.js"() {
    SHORT_TO_HEX2 = {};
    HEX_TO_SHORT2 = {};
    for (let i3 = 0; i3 < 256; i3++) {
      let encodedByte = i3.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX2[i3] = encodedByte;
      HEX_TO_SHORT2[encodedByte] = i3;
    }
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
var fromUtf83;
var init_fromUtf8_browser3 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() {
    fromUtf83 = (input) => new TextEncoder().encode(input);
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var toUint8Array;
var init_toUint8Array3 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    init_fromUtf8_browser3();
    toUint8Array = (data) => {
      if (typeof data === "string") {
        return fromUtf83(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
var init_toUtf8_browser3 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() {
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es40 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    init_fromUtf8_browser3();
    init_toUint8Array3();
    init_toUtf8_browser3();
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/constants.js
var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL;
var init_constants6 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/constants.js"() {
    ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
    CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
    AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
    SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
    EXPIRES_QUERY_PARAM = "X-Amz-Expires";
    SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
    TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
    AUTH_HEADER = "authorization";
    AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
    DATE_HEADER = "date";
    GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
    SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
    SHA256_HEADER = "x-amz-content-sha256";
    TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
    ALWAYS_UNSIGNABLE_HEADERS = {
      authorization: true,
      "cache-control": true,
      connection: true,
      expect: true,
      from: true,
      "keep-alive": true,
      "max-forwards": true,
      pragma: true,
      referer: true,
      te: true,
      trailer: true,
      "transfer-encoding": true,
      upgrade: true,
      "user-agent": true,
      "x-amzn-trace-id": true
    };
    PROXY_HEADER_PATTERN = /^proxy-/;
    SEC_HEADER_PATTERN = /^sec-/;
    ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
    EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
    UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
    MAX_CACHE_SIZE = 50;
    KEY_TYPE_IDENTIFIER = "aws4_request";
    MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac;
var init_credentialDerivation = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() {
    init_dist_es39();
    init_dist_es40();
    init_constants6();
    signingKeyCache = {};
    cacheQueue = [];
    createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
    getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {
      const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
      const cacheKey = `${shortDate}:${region}:${service}:${toHex2(credsHash)}:${credentials.sessionToken}`;
      if (cacheKey in signingKeyCache) {
        return signingKeyCache[cacheKey];
      }
      cacheQueue.push(cacheKey);
      while (cacheQueue.length > MAX_CACHE_SIZE) {
        delete signingKeyCache[cacheQueue.shift()];
      }
      let key = `AWS4${credentials.secretAccessKey}`;
      for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
        key = await hmac(sha256Constructor, key, signable);
      }
      return signingKeyCache[cacheKey] = key;
    };
    hmac = (ctor, secret, data) => {
      const hash = new ctor(secret);
      hash.update(toUint8Array(data));
      return hash.digest();
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
var getCanonicalHeaders;
var init_getCanonicalHeaders = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() {
    init_constants6();
    getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
      const canonical = {};
      for (const headerName of Object.keys(headers).sort()) {
        if (headers[headerName] == void 0) {
          continue;
        }
        const canonicalHeaderName = headerName.toLowerCase();
        if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
          if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
            continue;
          }
        }
        canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
      }
      return canonical;
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
var getCanonicalQuery;
var init_getCanonicalQuery = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() {
    init_dist_es28();
    init_constants6();
    getCanonicalQuery = ({ query = {} }) => {
      const keys = [];
      const serialized = {};
      for (const key of Object.keys(query).sort()) {
        if (key.toLowerCase() === SIGNATURE_HEADER) {
          continue;
        }
        keys.push(key);
        const value = query[key];
        if (typeof value === "string") {
          serialized[key] = `${escapeUri(key)}=${escapeUri(value)}`;
        } else if (Array.isArray(value)) {
          serialized[key] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${escapeUri(key)}=${escapeUri(value2)}`]), []).sort().join("&");
        }
      }
      return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/is-array-buffer/dist-es/index.js
var isArrayBuffer;
var init_dist_es41 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/is-array-buffer/dist-es/index.js"() {
    isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
var getPayloadHash;
var init_getPayloadHash = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() {
    init_dist_es41();
    init_dist_es39();
    init_dist_es40();
    init_constants6();
    getPayloadHash = async ({ headers, body }, hashConstructor) => {
      for (const headerName of Object.keys(headers)) {
        if (headerName.toLowerCase() === SHA256_HEADER) {
          return headers[headerName];
        }
      }
      if (body == void 0) {
        return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
      } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {
        const hashCtor = new hashConstructor();
        hashCtor.update(toUint8Array(body));
        return toHex2(await hashCtor.digest());
      }
      return UNSIGNED_PAYLOAD;
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
function negate(bytes) {
  for (let i3 = 0; i3 < 8; i3++) {
    bytes[i3] ^= 255;
  }
  for (let i3 = 7; i3 > -1; i3--) {
    bytes[i3]++;
    if (bytes[i3] !== 0)
      break;
  }
}
var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64;
var init_HeaderFormatter = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() {
    init_dist_es39();
    init_dist_es40();
    HeaderFormatter = class {
      format(headers) {
        const chunks = [];
        for (const headerName of Object.keys(headers)) {
          const bytes = fromUtf83(headerName);
          chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
        }
        const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
        let position = 0;
        for (const chunk of chunks) {
          out.set(chunk, position);
          position += chunk.byteLength;
        }
        return out;
      }
      formatHeaderValue(header) {
        switch (header.type) {
          case "boolean":
            return Uint8Array.from([header.value ? 0 : 1]);
          case "byte":
            return Uint8Array.from([2, header.value]);
          case "short":
            const shortView = new DataView(new ArrayBuffer(3));
            shortView.setUint8(0, 3);
            shortView.setInt16(1, header.value, false);
            return new Uint8Array(shortView.buffer);
          case "integer":
            const intView = new DataView(new ArrayBuffer(5));
            intView.setUint8(0, 4);
            intView.setInt32(1, header.value, false);
            return new Uint8Array(intView.buffer);
          case "long":
            const longBytes = new Uint8Array(9);
            longBytes[0] = 5;
            longBytes.set(header.value.bytes, 1);
            return longBytes;
          case "binary":
            const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
            binView.setUint8(0, 6);
            binView.setUint16(1, header.value.byteLength, false);
            const binBytes = new Uint8Array(binView.buffer);
            binBytes.set(header.value, 3);
            return binBytes;
          case "string":
            const utf8Bytes = fromUtf83(header.value);
            const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
            strView.setUint8(0, 7);
            strView.setUint16(1, utf8Bytes.byteLength, false);
            const strBytes = new Uint8Array(strView.buffer);
            strBytes.set(utf8Bytes, 3);
            return strBytes;
          case "timestamp":
            const tsBytes = new Uint8Array(9);
            tsBytes[0] = 8;
            tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
            return tsBytes;
          case "uuid":
            if (!UUID_PATTERN.test(header.value)) {
              throw new Error(`Invalid UUID received: ${header.value}`);
            }
            const uuidBytes = new Uint8Array(17);
            uuidBytes[0] = 9;
            uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
            return uuidBytes;
        }
      }
    };
    (function(HEADER_VALUE_TYPE2) {
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp";
      HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid";
    })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
    UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
    Int64 = class {
      constructor(bytes) {
        this.bytes = bytes;
        if (bytes.byteLength !== 8) {
          throw new Error("Int64 buffers must be exactly 8 bytes");
        }
      }
      static fromNumber(number) {
        if (number > 9223372036854776e3 || number < -9223372036854776e3) {
          throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
        }
        const bytes = new Uint8Array(8);
        for (let i3 = 7, remaining = Math.abs(Math.round(number)); i3 > -1 && remaining > 0; i3--, remaining /= 256) {
          bytes[i3] = remaining;
        }
        if (number < 0) {
          negate(bytes);
        }
        return new Int64(bytes);
      }
      valueOf() {
        const bytes = this.bytes.slice(0);
        const negative = bytes[0] & 128;
        if (negative) {
          negate(bytes);
        }
        return parseInt(toHex2(bytes), 16) * (negative ? -1 : 1);
      }
      toString() {
        return String(this.valueOf());
      }
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/headerUtil.js
var hasHeader;
var init_headerUtil = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() {
    hasHeader = (soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return true;
        }
      }
      return false;
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
var moveHeadersToQuery;
var init_moveHeadersToQuery = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() {
    init_dist_es38();
    moveHeadersToQuery = (request, options = {}) => {
      const { headers, query = {} } = HttpRequest7.clone(request);
      for (const name of Object.keys(headers)) {
        const lname = name.toLowerCase();
        if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) {
          query[name] = headers[name];
          delete headers[name];
        }
      }
      return {
        ...request,
        headers,
        query
      };
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
var prepareRequest;
var init_prepareRequest = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() {
    init_dist_es38();
    init_constants6();
    prepareRequest = (request) => {
      request = HttpRequest7.clone(request);
      for (const headerName of Object.keys(request.headers)) {
        if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
          delete request.headers[headerName];
        }
      }
      return request;
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/utilDate.js
var iso8601, toDate;
var init_utilDate = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/utilDate.js"() {
    iso8601 = (time2) => toDate(time2).toISOString().replace(/\.\d{3}Z$/, "Z");
    toDate = (time2) => {
      if (typeof time2 === "number") {
        return new Date(time2 * 1e3);
      }
      if (typeof time2 === "string") {
        if (Number(time2)) {
          return new Date(Number(time2) * 1e3);
        }
        return new Date(time2);
      }
      return time2;
    };
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
var SignatureV4, formatDate, getCanonicalHeaderList;
var init_SignatureV4 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() {
    init_dist_es39();
    init_dist_es13();
    init_dist_es28();
    init_dist_es40();
    init_constants6();
    init_credentialDerivation();
    init_getCanonicalHeaders();
    init_getCanonicalQuery();
    init_getPayloadHash();
    init_HeaderFormatter();
    init_headerUtil();
    init_moveHeadersToQuery();
    init_prepareRequest();
    init_utilDate();
    SignatureV4 = class {
      constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
        this.headerFormatter = new HeaderFormatter();
        this.service = service;
        this.sha256 = sha256;
        this.uriEscapePath = uriEscapePath;
        this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
        this.regionProvider = normalizeProvider(region);
        this.credentialProvider = normalizeProvider(credentials);
      }
      async presign(originalRequest, options = {}) {
        const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, signingRegion, signingService } = options;
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion ?? await this.regionProvider();
        const { longDate, shortDate } = formatDate(signingDate);
        if (expiresIn > MAX_PRESIGNED_TTL) {
          return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
        }
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders });
        if (credentials.sessionToken) {
          request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
        }
        request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
        request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
        request.query[AMZ_DATE_QUERY_PARAM] = longDate;
        request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders);
        request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
        return request;
      }
      async sign(toSign, options) {
        if (typeof toSign === "string") {
          return this.signString(toSign, options);
        } else if (toSign.headers && toSign.payload) {
          return this.signEvent(toSign, options);
        } else if (toSign.message) {
          return this.signMessage(toSign, options);
        } else {
          return this.signRequest(toSign, options);
        }
      }
      async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) {
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate, longDate } = formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
        const hash = new this.sha256();
        hash.update(headers);
        const hashedHeaders = toHex2(await hash.digest());
        const stringToSign = [
          EVENT_ALGORITHM_IDENTIFIER,
          longDate,
          scope,
          priorSignature,
          hashedHeaders,
          hashedPayload
        ].join("\n");
        return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
      }
      async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) {
        const promise = this.signEvent({
          headers: this.headerFormatter.format(signableMessage.message.headers),
          payload: signableMessage.message.body
        }, {
          signingDate,
          signingRegion,
          signingService,
          priorSignature: signableMessage.priorSignature
        });
        return promise.then((signature) => {
          return { message: signableMessage.message, signature };
        });
      }
      async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) {
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion ?? await this.regionProvider();
        const { shortDate } = formatDate(signingDate);
        const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
        hash.update(toUint8Array(stringToSign));
        return toHex2(await hash.digest());
      }
      async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion ?? await this.regionProvider();
        const request = prepareRequest(requestToSign);
        const { longDate, shortDate } = formatDate(signingDate);
        const scope = createScope(shortDate, region, signingService ?? this.service);
        request.headers[AMZ_DATE_HEADER] = longDate;
        if (credentials.sessionToken) {
          request.headers[TOKEN_HEADER] = credentials.sessionToken;
        }
        const payloadHash = await getPayloadHash(request, this.sha256);
        if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {
          request.headers[SHA256_HEADER] = payloadHash;
        }
        const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
        const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash));
        request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
        return request;
      }
      createCanonicalRequest(request, canonicalHeaders, payloadHash) {
        const sortedHeaders = Object.keys(canonicalHeaders).sort();
        return `${request.method}
${this.getCanonicalPath(request)}
${getCanonicalQuery(request)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
      }
      async createStringToSign(longDate, credentialScope, canonicalRequest) {
        const hash = new this.sha256();
        hash.update(toUint8Array(canonicalRequest));
        const hashedRequest = await hash.digest();
        return `${ALGORITHM_IDENTIFIER}
${longDate}
${credentialScope}
${toHex2(hashedRequest)}`;
      }
      getCanonicalPath({ path }) {
        if (this.uriEscapePath) {
          const normalizedPathSegments = [];
          for (const pathSegment of path.split("/")) {
            if (pathSegment?.length === 0)
              continue;
            if (pathSegment === ".")
              continue;
            if (pathSegment === "..") {
              normalizedPathSegments.pop();
            } else {
              normalizedPathSegments.push(pathSegment);
            }
          }
          const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`;
          const doubleEncoded = escapeUri(normalizedPath);
          return doubleEncoded.replace(/%2F/g, "/");
        }
        return path;
      }
      async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
        const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
        const hash = new this.sha256(await keyPromise);
        hash.update(toUint8Array(stringToSign));
        return toHex2(await hash.digest());
      }
      getSigningKey(credentials, region, shortDate, service) {
        return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
      }
      validateResolvedCredentials(credentials) {
        if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
          throw new Error("Resolved credential object is not valid");
        }
      }
    };
    formatDate = (now3) => {
      const longDate = iso8601(now3).replace(/[\-:]/g, "");
      return {
        longDate,
        shortDate: longDate.slice(0, 8)
      };
    };
    getCanonicalHeaderList = (headers) => Object.keys(headers).sort().join(";");
  }
});

// node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/index.js
var init_dist_es42 = __esm({
  "node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-es/index.js"() {
    init_SignatureV4();
    init_getCanonicalHeaders();
    init_getCanonicalQuery();
    init_getPayloadHash();
    init_moveHeadersToQuery();
    init_prepareRequest();
    init_credentialDerivation();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
var resolveAwsSdkSigV4Config;
var init_resolveAwsSdkSigV4Config = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
    init_dist_es35();
    init_dist_es42();
    resolveAwsSdkSigV4Config = (config) => {
      let normalizedCreds;
      if (config.credentials) {
        normalizedCreds = memoizeIdentityProvider(config.credentials, isIdentityExpired, doesIdentityRequireRefresh);
      }
      if (!normalizedCreds) {
        if (config.credentialDefaultProvider) {
          normalizedCreds = normalizeProvider2(config.credentialDefaultProvider(Object.assign({}, config, {
            parentClientConfig: config
          })));
        } else {
          normalizedCreds = async () => {
            throw new Error("`credentials` is missing");
          };
        }
      }
      const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256 } = config;
      let signer;
      if (config.signer) {
        signer = normalizeProvider2(config.signer);
      } else if (config.regionInfoProvider) {
        signer = () => normalizeProvider2(config.region)().then(async (region) => [
          await config.regionInfoProvider(region, {
            useFipsEndpoint: await config.useFipsEndpoint(),
            useDualstackEndpoint: await config.useDualstackEndpoint()
          }) || {},
          region
        ]).then(([regionInfo, region]) => {
          const { signingRegion, signingService } = regionInfo;
          config.signingRegion = config.signingRegion || signingRegion || region;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: normalizedCreds,
            region: config.signingRegion,
            service: config.signingName,
            sha256,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || SignatureV4;
          return new SignerCtor(params);
        });
      } else {
        signer = async (authScheme) => {
          authScheme = Object.assign({}, {
            name: "sigv4",
            signingName: config.signingName || config.defaultSigningName,
            signingRegion: await normalizeProvider2(config.region)(),
            properties: {}
          }, authScheme);
          const signingRegion = authScheme.signingRegion;
          const signingService = authScheme.signingName;
          config.signingRegion = config.signingRegion || signingRegion;
          config.signingName = config.signingName || signingService || config.serviceId;
          const params = {
            ...config,
            credentials: normalizedCreds,
            region: config.signingRegion,
            service: config.signingName,
            sha256,
            uriEscapePath: signingEscapePath
          };
          const SignerCtor = config.signerConstructor || SignatureV4;
          return new SignerCtor(params);
        };
      }
      return {
        ...config,
        systemClockOffset,
        signingEscapePath,
        credentials: normalizedCreds,
        signer
      };
    };
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
var init_aws_sdk = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
    init_AwsSdkSigV4Signer();
    init_resolveAwsSdkSigV4AConfig();
    init_resolveAwsSdkSigV4Config();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
var init_httpAuthSchemes2 = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
    init_aws_sdk();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
var init_coercing_serializers = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
var init_awsExpectUnion = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
    init_dist_es33();
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
var collectBodyString;
var init_common = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
    init_dist_es33();
    collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body));
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
var init_parseJsonBody = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
    init_common();
    parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        try {
          return JSON.parse(encoded);
        } catch (e3) {
          if (e3?.name === "SyntaxError") {
            Object.defineProperty(e3, "$responseBodyText", {
              value: encoded
            });
          }
          throw e3;
        }
      }
      return {};
    });
    parseJsonErrorBody = async (errorBody, context) => {
      const value = await parseJsonBody(errorBody, context);
      value.message = value.message ?? value.Message;
      return value;
    };
    loadRestJsonErrorCode = (output, data) => {
      const findKey = (object, key) => Object.keys(object).find((k3) => k3.toLowerCase() === key.toLowerCase());
      const sanitizeErrorCode = (rawValue2) => {
        let cleanValue = rawValue2;
        if (typeof cleanValue === "number") {
          cleanValue = cleanValue.toString();
        }
        if (cleanValue.indexOf(",") >= 0) {
          cleanValue = cleanValue.split(",")[0];
        }
        if (cleanValue.indexOf(":") >= 0) {
          cleanValue = cleanValue.split(":")[0];
        }
        if (cleanValue.indexOf("#") >= 0) {
          cleanValue = cleanValue.split("#")[1];
        }
        return cleanValue;
      };
      const headerKey = findKey(output.headers, "x-amzn-errortype");
      if (headerKey !== void 0) {
        return sanitizeErrorCode(output.headers[headerKey]);
      }
      if (data.code !== void 0) {
        return sanitizeErrorCode(data.code);
      }
      if (data["__type"] !== void 0) {
        return sanitizeErrorCode(data["__type"]);
      }
    };
  }
});

// node_modules/fast-xml-parser/src/util.js
var require_util = __commonJS({
  "node_modules/fast-xml-parser/src/util.js"(exports) {
    "use strict";
    var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
    var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
    var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
    var regexName = new RegExp("^" + nameRegexp + "$");
    var getAllMatches = function(string, regex2) {
      const matches = [];
      let match2 = regex2.exec(string);
      while (match2) {
        const allmatches = [];
        allmatches.startIndex = regex2.lastIndex - match2[0].length;
        const len = match2.length;
        for (let index2 = 0; index2 < len; index2++) {
          allmatches.push(match2[index2]);
        }
        matches.push(allmatches);
        match2 = regex2.exec(string);
      }
      return matches;
    };
    var isName = function(string) {
      const match2 = regexName.exec(string);
      return !(match2 === null || typeof match2 === "undefined");
    };
    exports.isExist = function(v5) {
      return typeof v5 !== "undefined";
    };
    exports.isEmptyObject = function(obj) {
      return Object.keys(obj).length === 0;
    };
    exports.merge = function(target, a3, arrayMode) {
      if (a3) {
        const keys = Object.keys(a3);
        const len = keys.length;
        for (let i3 = 0; i3 < len; i3++) {
          if (arrayMode === "strict") {
            target[keys[i3]] = [a3[keys[i3]]];
          } else {
            target[keys[i3]] = a3[keys[i3]];
          }
        }
      }
    };
    exports.getValue = function(v5) {
      if (exports.isExist(v5)) {
        return v5;
      } else {
        return "";
      }
    };
    exports.isName = isName;
    exports.getAllMatches = getAllMatches;
    exports.nameRegexp = nameRegexp;
  }
});

// node_modules/fast-xml-parser/src/validator.js
var require_validator = __commonJS({
  "node_modules/fast-xml-parser/src/validator.js"(exports) {
    "use strict";
    var util2 = require_util();
    var defaultOptions4 = {
      allowBooleanAttributes: false,
      //A tag can have attributes without any value
      unpairedTags: []
    };
    exports.validate = function(xmlData, options) {
      options = Object.assign({}, defaultOptions4, options);
      const tags = [];
      let tagFound = false;
      let reachedRoot = false;
      if (xmlData[0] === "\uFEFF") {
        xmlData = xmlData.substr(1);
      }
      for (let i3 = 0; i3 < xmlData.length; i3++) {
        if (xmlData[i3] === "<" && xmlData[i3 + 1] === "?") {
          i3 += 2;
          i3 = readPI(xmlData, i3);
          if (i3.err)
            return i3;
        } else if (xmlData[i3] === "<") {
          let tagStartPos = i3;
          i3++;
          if (xmlData[i3] === "!") {
            i3 = readCommentAndCDATA(xmlData, i3);
            continue;
          } else {
            let closingTag = false;
            if (xmlData[i3] === "/") {
              closingTag = true;
              i3++;
            }
            let tagName = "";
            for (; i3 < xmlData.length && xmlData[i3] !== ">" && xmlData[i3] !== " " && xmlData[i3] !== "	" && xmlData[i3] !== "\n" && xmlData[i3] !== "\r"; i3++) {
              tagName += xmlData[i3];
            }
            tagName = tagName.trim();
            if (tagName[tagName.length - 1] === "/") {
              tagName = tagName.substring(0, tagName.length - 1);
              i3--;
            }
            if (!validateTagName(tagName)) {
              let msg;
              if (tagName.trim().length === 0) {
                msg = "Invalid space after '<'.";
              } else {
                msg = "Tag '" + tagName + "' is an invalid name.";
              }
              return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i3));
            }
            const result = readAttributeStr(xmlData, i3);
            if (result === false) {
              return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i3));
            }
            let attrStr = result.value;
            i3 = result.index;
            if (attrStr[attrStr.length - 1] === "/") {
              const attrStrStart = i3 - attrStr.length;
              attrStr = attrStr.substring(0, attrStr.length - 1);
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 === true) {
                tagFound = true;
              } else {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
              }
            } else if (closingTag) {
              if (!result.tagClosed) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i3));
              } else if (attrStr.trim().length > 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
              } else if (tags.length === 0) {
                return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
              } else {
                const otg = tags.pop();
                if (tagName !== otg.tagName) {
                  let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
                  return getErrorObject(
                    "InvalidTag",
                    "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
                    getLineNumberForPosition(xmlData, tagStartPos)
                  );
                }
                if (tags.length == 0) {
                  reachedRoot = true;
                }
              }
            } else {
              const isValid2 = validateAttributeString(attrStr, options);
              if (isValid2 !== true) {
                return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i3 - attrStr.length + isValid2.err.line));
              }
              if (reachedRoot === true) {
                return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i3));
              } else if (options.unpairedTags.indexOf(tagName) !== -1) {
              } else {
                tags.push({ tagName, tagStartPos });
              }
              tagFound = true;
            }
            for (i3++; i3 < xmlData.length; i3++) {
              if (xmlData[i3] === "<") {
                if (xmlData[i3 + 1] === "!") {
                  i3++;
                  i3 = readCommentAndCDATA(xmlData, i3);
                  continue;
                } else if (xmlData[i3 + 1] === "?") {
                  i3 = readPI(xmlData, ++i3);
                  if (i3.err)
                    return i3;
                } else {
                  break;
                }
              } else if (xmlData[i3] === "&") {
                const afterAmp = validateAmpersand(xmlData, i3);
                if (afterAmp == -1)
                  return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i3));
                i3 = afterAmp;
              } else {
                if (reachedRoot === true && !isWhiteSpace(xmlData[i3])) {
                  return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i3));
                }
              }
            }
            if (xmlData[i3] === "<") {
              i3--;
            }
          }
        } else {
          if (isWhiteSpace(xmlData[i3])) {
            continue;
          }
          return getErrorObject("InvalidChar", "char '" + xmlData[i3] + "' is not expected.", getLineNumberForPosition(xmlData, i3));
        }
      }
      if (!tagFound) {
        return getErrorObject("InvalidXml", "Start tag expected.", 1);
      } else if (tags.length == 1) {
        return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
      } else if (tags.length > 0) {
        return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t3) => t3.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
      }
      return true;
    };
    function isWhiteSpace(char) {
      return char === " " || char === "	" || char === "\n" || char === "\r";
    }
    function readPI(xmlData, i3) {
      const start = i3;
      for (; i3 < xmlData.length; i3++) {
        if (xmlData[i3] == "?" || xmlData[i3] == " ") {
          const tagname = xmlData.substr(start, i3 - start);
          if (i3 > 5 && tagname === "xml") {
            return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i3));
          } else if (xmlData[i3] == "?" && xmlData[i3 + 1] == ">") {
            i3++;
            break;
          } else {
            continue;
          }
        }
      }
      return i3;
    }
    function readCommentAndCDATA(xmlData, i3) {
      if (xmlData.length > i3 + 5 && xmlData[i3 + 1] === "-" && xmlData[i3 + 2] === "-") {
        for (i3 += 3; i3 < xmlData.length; i3++) {
          if (xmlData[i3] === "-" && xmlData[i3 + 1] === "-" && xmlData[i3 + 2] === ">") {
            i3 += 2;
            break;
          }
        }
      } else if (xmlData.length > i3 + 8 && xmlData[i3 + 1] === "D" && xmlData[i3 + 2] === "O" && xmlData[i3 + 3] === "C" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "Y" && xmlData[i3 + 6] === "P" && xmlData[i3 + 7] === "E") {
        let angleBracketsCount = 1;
        for (i3 += 8; i3 < xmlData.length; i3++) {
          if (xmlData[i3] === "<") {
            angleBracketsCount++;
          } else if (xmlData[i3] === ">") {
            angleBracketsCount--;
            if (angleBracketsCount === 0) {
              break;
            }
          }
        }
      } else if (xmlData.length > i3 + 9 && xmlData[i3 + 1] === "[" && xmlData[i3 + 2] === "C" && xmlData[i3 + 3] === "D" && xmlData[i3 + 4] === "A" && xmlData[i3 + 5] === "T" && xmlData[i3 + 6] === "A" && xmlData[i3 + 7] === "[") {
        for (i3 += 8; i3 < xmlData.length; i3++) {
          if (xmlData[i3] === "]" && xmlData[i3 + 1] === "]" && xmlData[i3 + 2] === ">") {
            i3 += 2;
            break;
          }
        }
      }
      return i3;
    }
    var doubleQuote = '"';
    var singleQuote = "'";
    function readAttributeStr(xmlData, i3) {
      let attrStr = "";
      let startChar = "";
      let tagClosed = false;
      for (; i3 < xmlData.length; i3++) {
        if (xmlData[i3] === doubleQuote || xmlData[i3] === singleQuote) {
          if (startChar === "") {
            startChar = xmlData[i3];
          } else if (startChar !== xmlData[i3]) {
          } else {
            startChar = "";
          }
        } else if (xmlData[i3] === ">") {
          if (startChar === "") {
            tagClosed = true;
            break;
          }
        }
        attrStr += xmlData[i3];
      }
      if (startChar !== "") {
        return false;
      }
      return {
        value: attrStr,
        index: i3,
        tagClosed
      };
    }
    var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
    function validateAttributeString(attrStr, options) {
      const matches = util2.getAllMatches(attrStr, validAttrStrRegxp);
      const attrNames = {};
      for (let i3 = 0; i3 < matches.length; i3++) {
        if (matches[i3][1].length === 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i3][2] + "' has no space in starting.", getPositionFromMatch(matches[i3]));
        } else if (matches[i3][3] !== void 0 && matches[i3][4] === void 0) {
          return getErrorObject("InvalidAttr", "Attribute '" + matches[i3][2] + "' is without value.", getPositionFromMatch(matches[i3]));
        } else if (matches[i3][3] === void 0 && !options.allowBooleanAttributes) {
          return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i3][2] + "' is not allowed.", getPositionFromMatch(matches[i3]));
        }
        const attrName = matches[i3][2];
        if (!validateAttrName(attrName)) {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i3]));
        }
        if (!attrNames.hasOwnProperty(attrName)) {
          attrNames[attrName] = 1;
        } else {
          return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i3]));
        }
      }
      return true;
    }
    function validateNumberAmpersand(xmlData, i3) {
      let re = /\d/;
      if (xmlData[i3] === "x") {
        i3++;
        re = /[\da-fA-F]/;
      }
      for (; i3 < xmlData.length; i3++) {
        if (xmlData[i3] === ";")
          return i3;
        if (!xmlData[i3].match(re))
          break;
      }
      return -1;
    }
    function validateAmpersand(xmlData, i3) {
      i3++;
      if (xmlData[i3] === ";")
        return -1;
      if (xmlData[i3] === "#") {
        i3++;
        return validateNumberAmpersand(xmlData, i3);
      }
      let count5 = 0;
      for (; i3 < xmlData.length; i3++, count5++) {
        if (xmlData[i3].match(/\w/) && count5 < 20)
          continue;
        if (xmlData[i3] === ";")
          break;
        return -1;
      }
      return i3;
    }
    function getErrorObject(code, message, lineNumber) {
      return {
        err: {
          code,
          msg: message,
          line: lineNumber.line || lineNumber,
          col: lineNumber.col
        }
      };
    }
    function validateAttrName(attrName) {
      return util2.isName(attrName);
    }
    function validateTagName(tagname) {
      return util2.isName(tagname);
    }
    function getLineNumberForPosition(xmlData, index2) {
      const lines = xmlData.substring(0, index2).split(/\r?\n/);
      return {
        line: lines.length,
        // column number is last line's length + 1, because column numbering starts at 1:
        col: lines[lines.length - 1].length + 1
      };
    }
    function getPositionFromMatch(match2) {
      return match2.startIndex + match2[1].length;
    }
  }
});

// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var require_OptionsBuilder = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports) {
    var defaultOptions4 = {
      preserveOrder: false,
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      removeNSPrefix: false,
      // remove NS from tag name or attribute name if true
      allowBooleanAttributes: false,
      //a tag can have attributes without any value
      //ignoreRootElement : false,
      parseTagValue: true,
      parseAttributeValue: false,
      trimValues: true,
      //Trim string values of tag and attributes
      cdataPropName: false,
      numberParseOptions: {
        hex: true,
        leadingZeros: true,
        eNotation: true
      },
      tagValueProcessor: function(tagName, val2) {
        return val2;
      },
      attributeValueProcessor: function(attrName, val2) {
        return val2;
      },
      stopNodes: [],
      //nested tags will not be parsed even for errors
      alwaysCreateTextNode: false,
      isArray: () => false,
      commentPropName: false,
      unpairedTags: [],
      processEntities: true,
      htmlEntities: false,
      ignoreDeclaration: false,
      ignorePiTags: false,
      transformTagName: false,
      transformAttributeName: false,
      updateTag: function(tagName, jPath, attrs) {
        return tagName;
      }
      // skipEmptyListItem: false
    };
    var buildOptions = function(options) {
      return Object.assign({}, defaultOptions4, options);
    };
    exports.buildOptions = buildOptions;
    exports.defaultOptions = defaultOptions4;
  }
});

// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var require_xmlNode = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports, module2) {
    "use strict";
    var XmlNode = class {
      constructor(tagname) {
        this.tagname = tagname;
        this.child = [];
        this[":@"] = {};
      }
      add(key, val2) {
        if (key === "__proto__")
          key = "#__proto__";
        this.child.push({ [key]: val2 });
      }
      addChild(node) {
        if (node.tagname === "__proto__")
          node.tagname = "#__proto__";
        if (node[":@"] && Object.keys(node[":@"]).length > 0) {
          this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
        } else {
          this.child.push({ [node.tagname]: node.child });
        }
      }
    };
    module2.exports = XmlNode;
  }
});

// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
var require_DocTypeReader = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports, module2) {
    var util2 = require_util();
    function readDocType(xmlData, i3) {
      const entities = {};
      if (xmlData[i3 + 3] === "O" && xmlData[i3 + 4] === "C" && xmlData[i3 + 5] === "T" && xmlData[i3 + 6] === "Y" && xmlData[i3 + 7] === "P" && xmlData[i3 + 8] === "E") {
        i3 = i3 + 9;
        let angleBracketsCount = 1;
        let hasBody = false, comment = false;
        let exp = "";
        for (; i3 < xmlData.length; i3++) {
          if (xmlData[i3] === "<" && !comment) {
            if (hasBody && isEntity(xmlData, i3)) {
              i3 += 7;
              [entityName, val, i3] = readEntityExp(xmlData, i3 + 1);
              if (val.indexOf("&") === -1)
                entities[validateEntityName(entityName)] = {
                  regx: RegExp(`&${entityName};`, "g"),
                  val
                };
            } else if (hasBody && isElement2(xmlData, i3))
              i3 += 8;
            else if (hasBody && isAttlist(xmlData, i3))
              i3 += 8;
            else if (hasBody && isNotation(xmlData, i3))
              i3 += 9;
            else if (isComment)
              comment = true;
            else
              throw new Error("Invalid DOCTYPE");
            angleBracketsCount++;
            exp = "";
          } else if (xmlData[i3] === ">") {
            if (comment) {
              if (xmlData[i3 - 1] === "-" && xmlData[i3 - 2] === "-") {
                comment = false;
                angleBracketsCount--;
              }
            } else {
              angleBracketsCount--;
            }
            if (angleBracketsCount === 0) {
              break;
            }
          } else if (xmlData[i3] === "[") {
            hasBody = true;
          } else {
            exp += xmlData[i3];
          }
        }
        if (angleBracketsCount !== 0) {
          throw new Error(`Unclosed DOCTYPE`);
        }
      } else {
        throw new Error(`Invalid Tag instead of DOCTYPE`);
      }
      return { entities, i: i3 };
    }
    function readEntityExp(xmlData, i3) {
      let entityName2 = "";
      for (; i3 < xmlData.length && (xmlData[i3] !== "'" && xmlData[i3] !== '"'); i3++) {
        entityName2 += xmlData[i3];
      }
      entityName2 = entityName2.trim();
      if (entityName2.indexOf(" ") !== -1)
        throw new Error("External entites are not supported");
      const startChar = xmlData[i3++];
      let val2 = "";
      for (; i3 < xmlData.length && xmlData[i3] !== startChar; i3++) {
        val2 += xmlData[i3];
      }
      return [entityName2, val2, i3];
    }
    function isComment(xmlData, i3) {
      if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "-" && xmlData[i3 + 3] === "-")
        return true;
      return false;
    }
    function isEntity(xmlData, i3) {
      if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "E" && xmlData[i3 + 3] === "N" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "I" && xmlData[i3 + 6] === "T" && xmlData[i3 + 7] === "Y")
        return true;
      return false;
    }
    function isElement2(xmlData, i3) {
      if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "E" && xmlData[i3 + 3] === "L" && xmlData[i3 + 4] === "E" && xmlData[i3 + 5] === "M" && xmlData[i3 + 6] === "E" && xmlData[i3 + 7] === "N" && xmlData[i3 + 8] === "T")
        return true;
      return false;
    }
    function isAttlist(xmlData, i3) {
      if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "A" && xmlData[i3 + 3] === "T" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "L" && xmlData[i3 + 6] === "I" && xmlData[i3 + 7] === "S" && xmlData[i3 + 8] === "T")
        return true;
      return false;
    }
    function isNotation(xmlData, i3) {
      if (xmlData[i3 + 1] === "!" && xmlData[i3 + 2] === "N" && xmlData[i3 + 3] === "O" && xmlData[i3 + 4] === "T" && xmlData[i3 + 5] === "A" && xmlData[i3 + 6] === "T" && xmlData[i3 + 7] === "I" && xmlData[i3 + 8] === "O" && xmlData[i3 + 9] === "N")
        return true;
      return false;
    }
    function validateEntityName(name) {
      if (util2.isName(name))
        return name;
      else
        throw new Error(`Invalid entity name ${name}`);
    }
    module2.exports = readDocType;
  }
});

// node_modules/strnum/strnum.js
var require_strnum = __commonJS({
  "node_modules/strnum/strnum.js"(exports, module2) {
    var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
    var numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
    if (!Number.parseInt && window.parseInt) {
      Number.parseInt = window.parseInt;
    }
    if (!Number.parseFloat && window.parseFloat) {
      Number.parseFloat = window.parseFloat;
    }
    var consider = {
      hex: true,
      leadingZeros: true,
      decimalPoint: ".",
      eNotation: true
      //skipLike: /regex/
    };
    function toNumber(str2, options = {}) {
      options = Object.assign({}, consider, options);
      if (!str2 || typeof str2 !== "string")
        return str2;
      let trimmedStr = str2.trim();
      if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr))
        return str2;
      else if (options.hex && hexRegex.test(trimmedStr)) {
        return Number.parseInt(trimmedStr, 16);
      } else {
        const match2 = numRegex.exec(trimmedStr);
        if (match2) {
          const sign = match2[1];
          const leadingZeros = match2[2];
          let numTrimmedByZeros = trimZeros(match2[3]);
          const eNotation = match2[4] || match2[6];
          if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".")
            return str2;
          else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".")
            return str2;
          else {
            const num = Number(trimmedStr);
            const numStr = "" + num;
            if (numStr.search(/[eE]/) !== -1) {
              if (options.eNotation)
                return num;
              else
                return str2;
            } else if (eNotation) {
              if (options.eNotation)
                return num;
              else
                return str2;
            } else if (trimmedStr.indexOf(".") !== -1) {
              if (numStr === "0" && numTrimmedByZeros === "")
                return num;
              else if (numStr === numTrimmedByZeros)
                return num;
              else if (sign && numStr === "-" + numTrimmedByZeros)
                return num;
              else
                return str2;
            }
            if (leadingZeros) {
              if (numTrimmedByZeros === numStr)
                return num;
              else if (sign + numTrimmedByZeros === numStr)
                return num;
              else
                return str2;
            }
            if (trimmedStr === numStr)
              return num;
            else if (trimmedStr === sign + numStr)
              return num;
            return str2;
          }
        } else {
          return str2;
        }
      }
    }
    function trimZeros(numStr) {
      if (numStr && numStr.indexOf(".") !== -1) {
        numStr = numStr.replace(/0+$/, "");
        if (numStr === ".")
          numStr = "0";
        else if (numStr[0] === ".")
          numStr = "0" + numStr;
        else if (numStr[numStr.length - 1] === ".")
          numStr = numStr.substr(0, numStr.length - 1);
        return numStr;
      }
      return numStr;
    }
    module2.exports = toNumber;
  }
});

// node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
var require_OrderedObjParser = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports, module2) {
    "use strict";
    var util2 = require_util();
    var xmlNode = require_xmlNode();
    var readDocType = require_DocTypeReader();
    var toNumber = require_strnum();
    var OrderedObjParser = class {
      constructor(options) {
        this.options = options;
        this.currentNode = null;
        this.tagsNodeStack = [];
        this.docTypeEntities = {};
        this.lastEntities = {
          "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
          "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
          "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
          "quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
        };
        this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
        this.htmlEntities = {
          "space": { regex: /&(nbsp|#160);/g, val: " " },
          // "lt" : { regex: /&(lt|#60);/g, val: "<" },
          // "gt" : { regex: /&(gt|#62);/g, val: ">" },
          // "amp" : { regex: /&(amp|#38);/g, val: "&" },
          // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
          // "apos" : { regex: /&(apos|#39);/g, val: "'" },
          "cent": { regex: /&(cent|#162);/g, val: "\xA2" },
          "pound": { regex: /&(pound|#163);/g, val: "\xA3" },
          "yen": { regex: /&(yen|#165);/g, val: "\xA5" },
          "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
          "copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
          "reg": { regex: /&(reg|#174);/g, val: "\xAE" },
          "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
          "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 10)) },
          "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_2, str2) => String.fromCharCode(Number.parseInt(str2, 16)) }
        };
        this.addExternalEntities = addExternalEntities;
        this.parseXml = parseXml;
        this.parseTextData = parseTextData;
        this.resolveNameSpace = resolveNameSpace;
        this.buildAttributesMap = buildAttributesMap;
        this.isItStopNode = isItStopNode;
        this.replaceEntitiesValue = replaceEntitiesValue;
        this.readStopNodeData = readStopNodeData;
        this.saveTextToParentTag = saveTextToParentTag;
        this.addChild = addChild;
      }
    };
    function addExternalEntities(externalEntities) {
      const entKeys = Object.keys(externalEntities);
      for (let i3 = 0; i3 < entKeys.length; i3++) {
        const ent = entKeys[i3];
        this.lastEntities[ent] = {
          regex: new RegExp("&" + ent + ";", "g"),
          val: externalEntities[ent]
        };
      }
    }
    function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
      if (val2 !== void 0) {
        if (this.options.trimValues && !dontTrim) {
          val2 = val2.trim();
        }
        if (val2.length > 0) {
          if (!escapeEntities)
            val2 = this.replaceEntitiesValue(val2);
          const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
          if (newval === null || newval === void 0) {
            return val2;
          } else if (typeof newval !== typeof val2 || newval !== val2) {
            return newval;
          } else if (this.options.trimValues) {
            return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
          } else {
            const trimmedVal = val2.trim();
            if (trimmedVal === val2) {
              return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
            } else {
              return val2;
            }
          }
        }
      }
    }
    function resolveNameSpace(tagname) {
      if (this.options.removeNSPrefix) {
        const tags = tagname.split(":");
        const prefix = tagname.charAt(0) === "/" ? "/" : "";
        if (tags[0] === "xmlns") {
          return "";
        }
        if (tags.length === 2) {
          tagname = prefix + tags[1];
        }
      }
      return tagname;
    }
    var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
    function buildAttributesMap(attrStr, jPath, tagName) {
      if (!this.options.ignoreAttributes && typeof attrStr === "string") {
        const matches = util2.getAllMatches(attrStr, attrsRegx);
        const len = matches.length;
        const attrs = {};
        for (let i3 = 0; i3 < len; i3++) {
          const attrName = this.resolveNameSpace(matches[i3][1]);
          let oldVal = matches[i3][4];
          let aName = this.options.attributeNamePrefix + attrName;
          if (attrName.length) {
            if (this.options.transformAttributeName) {
              aName = this.options.transformAttributeName(aName);
            }
            if (aName === "__proto__")
              aName = "#__proto__";
            if (oldVal !== void 0) {
              if (this.options.trimValues) {
                oldVal = oldVal.trim();
              }
              oldVal = this.replaceEntitiesValue(oldVal);
              const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
              if (newVal === null || newVal === void 0) {
                attrs[aName] = oldVal;
              } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
                attrs[aName] = newVal;
              } else {
                attrs[aName] = parseValue(
                  oldVal,
                  this.options.parseAttributeValue,
                  this.options.numberParseOptions
                );
              }
            } else if (this.options.allowBooleanAttributes) {
              attrs[aName] = true;
            }
          }
        }
        if (!Object.keys(attrs).length) {
          return;
        }
        if (this.options.attributesGroupName) {
          const attrCollection = {};
          attrCollection[this.options.attributesGroupName] = attrs;
          return attrCollection;
        }
        return attrs;
      }
    }
    var parseXml = function(xmlData) {
      xmlData = xmlData.replace(/\r\n?/g, "\n");
      const xmlObj = new xmlNode("!xml");
      let currentNode = xmlObj;
      let textData = "";
      let jPath = "";
      for (let i3 = 0; i3 < xmlData.length; i3++) {
        const ch = xmlData[i3];
        if (ch === "<") {
          if (xmlData[i3 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i3, "Closing Tag is not closed.");
            let tagName = xmlData.substring(i3 + 2, closeIndex).trim();
            if (this.options.removeNSPrefix) {
              const colonIndex = tagName.indexOf(":");
              if (colonIndex !== -1) {
                tagName = tagName.substr(colonIndex + 1);
              }
            }
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode) {
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
            }
            const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
            if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
              throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
            }
            let propIndex = 0;
            if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
              propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
              this.tagsNodeStack.pop();
            } else {
              propIndex = jPath.lastIndexOf(".");
            }
            jPath = jPath.substring(0, propIndex);
            currentNode = this.tagsNodeStack.pop();
            textData = "";
            i3 = closeIndex;
          } else if (xmlData[i3 + 1] === "?") {
            let tagData = readTagExp(xmlData, i3, false, "?>");
            if (!tagData)
              throw new Error("Pi Tag is not closed.");
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
            } else {
              const childNode = new xmlNode(tagData.tagName);
              childNode.add(this.options.textNodeName, "");
              if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
              }
              this.addChild(currentNode, childNode, jPath);
            }
            i3 = tagData.closeIndex + 1;
          } else if (xmlData.substr(i3 + 1, 3) === "!--") {
            const endIndex = findClosingIndex(xmlData, "-->", i3 + 4, "Comment is not closed.");
            if (this.options.commentPropName) {
              const comment = xmlData.substring(i3 + 4, endIndex - 2);
              textData = this.saveTextToParentTag(textData, currentNode, jPath);
              currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
            }
            i3 = endIndex;
          } else if (xmlData.substr(i3 + 1, 2) === "!D") {
            const result = readDocType(xmlData, i3);
            this.docTypeEntities = result.entities;
            i3 = result.i;
          } else if (xmlData.substr(i3 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i3, "CDATA is not closed.") - 2;
            const tagExp = xmlData.substring(i3 + 9, closeIndex);
            textData = this.saveTextToParentTag(textData, currentNode, jPath);
            let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
            if (val2 == void 0)
              val2 = "";
            if (this.options.cdataPropName) {
              currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
            } else {
              currentNode.add(this.options.textNodeName, val2);
            }
            i3 = closeIndex + 2;
          } else {
            let result = readTagExp(xmlData, i3, this.options.removeNSPrefix);
            let tagName = result.tagName;
            const rawTagName = result.rawTagName;
            let tagExp = result.tagExp;
            let attrExpPresent = result.attrExpPresent;
            let closeIndex = result.closeIndex;
            if (this.options.transformTagName) {
              tagName = this.options.transformTagName(tagName);
            }
            if (currentNode && textData) {
              if (currentNode.tagname !== "!xml") {
                textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
              }
            }
            const lastTag = currentNode;
            if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
              currentNode = this.tagsNodeStack.pop();
              jPath = jPath.substring(0, jPath.lastIndexOf("."));
            }
            if (tagName !== xmlObj.tagname) {
              jPath += jPath ? "." + tagName : tagName;
            }
            if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
              let tagContent = "";
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                i3 = result.closeIndex;
              } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
                i3 = result.closeIndex;
              } else {
                const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
                if (!result2)
                  throw new Error(`Unexpected end of ${rawTagName}`);
                i3 = result2.i;
                tagContent = result2.tagContent;
              }
              const childNode = new xmlNode(tagName);
              if (tagName !== tagExp && attrExpPresent) {
                childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
              }
              if (tagContent) {
                tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
              }
              jPath = jPath.substr(0, jPath.lastIndexOf("."));
              childNode.add(this.options.textNodeName, tagContent);
              this.addChild(currentNode, childNode, jPath);
            } else {
              if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
                if (tagName[tagName.length - 1] === "/") {
                  tagName = tagName.substr(0, tagName.length - 1);
                  jPath = jPath.substr(0, jPath.length - 1);
                  tagExp = tagName;
                } else {
                  tagExp = tagExp.substr(0, tagExp.length - 1);
                }
                if (this.options.transformTagName) {
                  tagName = this.options.transformTagName(tagName);
                }
                const childNode = new xmlNode(tagName);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                jPath = jPath.substr(0, jPath.lastIndexOf("."));
              } else {
                const childNode = new xmlNode(tagName);
                this.tagsNodeStack.push(currentNode);
                if (tagName !== tagExp && attrExpPresent) {
                  childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
                }
                this.addChild(currentNode, childNode, jPath);
                currentNode = childNode;
              }
              textData = "";
              i3 = closeIndex;
            }
          }
        } else {
          textData += xmlData[i3];
        }
      }
      return xmlObj.child;
    };
    function addChild(currentNode, childNode, jPath) {
      const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
      if (result === false) {
      } else if (typeof result === "string") {
        childNode.tagname = result;
        currentNode.addChild(childNode);
      } else {
        currentNode.addChild(childNode);
      }
    }
    var replaceEntitiesValue = function(val2) {
      if (this.options.processEntities) {
        for (let entityName2 in this.docTypeEntities) {
          const entity = this.docTypeEntities[entityName2];
          val2 = val2.replace(entity.regx, entity.val);
        }
        for (let entityName2 in this.lastEntities) {
          const entity = this.lastEntities[entityName2];
          val2 = val2.replace(entity.regex, entity.val);
        }
        if (this.options.htmlEntities) {
          for (let entityName2 in this.htmlEntities) {
            const entity = this.htmlEntities[entityName2];
            val2 = val2.replace(entity.regex, entity.val);
          }
        }
        val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
      }
      return val2;
    };
    function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
      if (textData) {
        if (isLeafNode === void 0)
          isLeafNode = Object.keys(currentNode.child).length === 0;
        textData = this.parseTextData(
          textData,
          currentNode.tagname,
          jPath,
          false,
          currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
          isLeafNode
        );
        if (textData !== void 0 && textData !== "")
          currentNode.add(this.options.textNodeName, textData);
        textData = "";
      }
      return textData;
    }
    function isItStopNode(stopNodes, jPath, currentTagName) {
      const allNodesExp = "*." + currentTagName;
      for (const stopNodePath in stopNodes) {
        const stopNodeExp = stopNodes[stopNodePath];
        if (allNodesExp === stopNodeExp || jPath === stopNodeExp)
          return true;
      }
      return false;
    }
    function tagExpWithClosingIndex(xmlData, i3, closingChar = ">") {
      let attrBoundary;
      let tagExp = "";
      for (let index2 = i3; index2 < xmlData.length; index2++) {
        let ch = xmlData[index2];
        if (attrBoundary) {
          if (ch === attrBoundary)
            attrBoundary = "";
        } else if (ch === '"' || ch === "'") {
          attrBoundary = ch;
        } else if (ch === closingChar[0]) {
          if (closingChar[1]) {
            if (xmlData[index2 + 1] === closingChar[1]) {
              return {
                data: tagExp,
                index: index2
              };
            }
          } else {
            return {
              data: tagExp,
              index: index2
            };
          }
        } else if (ch === "	") {
          ch = " ";
        }
        tagExp += ch;
      }
    }
    function findClosingIndex(xmlData, str2, i3, errMsg) {
      const closingIndex = xmlData.indexOf(str2, i3);
      if (closingIndex === -1) {
        throw new Error(errMsg);
      } else {
        return closingIndex + str2.length - 1;
      }
    }
    function readTagExp(xmlData, i3, removeNSPrefix, closingChar = ">") {
      const result = tagExpWithClosingIndex(xmlData, i3 + 1, closingChar);
      if (!result)
        return;
      let tagExp = result.data;
      const closeIndex = result.index;
      const separatorIndex = tagExp.search(/\s/);
      let tagName = tagExp;
      let attrExpPresent = true;
      if (separatorIndex !== -1) {
        tagName = tagExp.substring(0, separatorIndex);
        tagExp = tagExp.substring(separatorIndex + 1).trimStart();
      }
      const rawTagName = tagName;
      if (removeNSPrefix) {
        const colonIndex = tagName.indexOf(":");
        if (colonIndex !== -1) {
          tagName = tagName.substr(colonIndex + 1);
          attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
        }
      }
      return {
        tagName,
        tagExp,
        closeIndex,
        attrExpPresent,
        rawTagName
      };
    }
    function readStopNodeData(xmlData, tagName, i3) {
      const startIndex = i3;
      let openTagCount = 1;
      for (; i3 < xmlData.length; i3++) {
        if (xmlData[i3] === "<") {
          if (xmlData[i3 + 1] === "/") {
            const closeIndex = findClosingIndex(xmlData, ">", i3, `${tagName} is not closed`);
            let closeTagName = xmlData.substring(i3 + 2, closeIndex).trim();
            if (closeTagName === tagName) {
              openTagCount--;
              if (openTagCount === 0) {
                return {
                  tagContent: xmlData.substring(startIndex, i3),
                  i: closeIndex
                };
              }
            }
            i3 = closeIndex;
          } else if (xmlData[i3 + 1] === "?") {
            const closeIndex = findClosingIndex(xmlData, "?>", i3 + 1, "StopNode is not closed.");
            i3 = closeIndex;
          } else if (xmlData.substr(i3 + 1, 3) === "!--") {
            const closeIndex = findClosingIndex(xmlData, "-->", i3 + 3, "StopNode is not closed.");
            i3 = closeIndex;
          } else if (xmlData.substr(i3 + 1, 2) === "![") {
            const closeIndex = findClosingIndex(xmlData, "]]>", i3, "StopNode is not closed.") - 2;
            i3 = closeIndex;
          } else {
            const tagData = readTagExp(xmlData, i3, ">");
            if (tagData) {
              const openTagName = tagData && tagData.tagName;
              if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
                openTagCount++;
              }
              i3 = tagData.closeIndex;
            }
          }
        }
      }
    }
    function parseValue(val2, shouldParse, options) {
      if (shouldParse && typeof val2 === "string") {
        const newval = val2.trim();
        if (newval === "true")
          return true;
        else if (newval === "false")
          return false;
        else
          return toNumber(val2, options);
      } else {
        if (util2.isExist(val2)) {
          return val2;
        } else {
          return "";
        }
      }
    }
    module2.exports = OrderedObjParser;
  }
});

// node_modules/fast-xml-parser/src/xmlparser/node2json.js
var require_node2json = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports) {
    "use strict";
    function prettify(node, options) {
      return compress(node, options);
    }
    function compress(arr2, options, jPath) {
      let text;
      const compressedObj = {};
      for (let i3 = 0; i3 < arr2.length; i3++) {
        const tagObj = arr2[i3];
        const property = propName(tagObj);
        let newJpath = "";
        if (jPath === void 0)
          newJpath = property;
        else
          newJpath = jPath + "." + property;
        if (property === options.textNodeName) {
          if (text === void 0)
            text = tagObj[property];
          else
            text += "" + tagObj[property];
        } else if (property === void 0) {
          continue;
        } else if (tagObj[property]) {
          let val2 = compress(tagObj[property], options, newJpath);
          const isLeaf = isLeafTag(val2, options);
          if (tagObj[":@"]) {
            assignAttributes(val2, tagObj[":@"], newJpath, options);
          } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
            val2 = val2[options.textNodeName];
          } else if (Object.keys(val2).length === 0) {
            if (options.alwaysCreateTextNode)
              val2[options.textNodeName] = "";
            else
              val2 = "";
          }
          if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
            if (!Array.isArray(compressedObj[property])) {
              compressedObj[property] = [compressedObj[property]];
            }
            compressedObj[property].push(val2);
          } else {
            if (options.isArray(property, newJpath, isLeaf)) {
              compressedObj[property] = [val2];
            } else {
              compressedObj[property] = val2;
            }
          }
        }
      }
      if (typeof text === "string") {
        if (text.length > 0)
          compressedObj[options.textNodeName] = text;
      } else if (text !== void 0)
        compressedObj[options.textNodeName] = text;
      return compressedObj;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i3 = 0; i3 < keys.length; i3++) {
        const key = keys[i3];
        if (key !== ":@")
          return key;
      }
    }
    function assignAttributes(obj, attrMap, jpath, options) {
      if (attrMap) {
        const keys = Object.keys(attrMap);
        const len = keys.length;
        for (let i3 = 0; i3 < len; i3++) {
          const atrrName = keys[i3];
          if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
            obj[atrrName] = [attrMap[atrrName]];
          } else {
            obj[atrrName] = attrMap[atrrName];
          }
        }
      }
    }
    function isLeafTag(obj, options) {
      const { textNodeName } = options;
      const propCount = Object.keys(obj).length;
      if (propCount === 0) {
        return true;
      }
      if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
        return true;
      }
      return false;
    }
    exports.prettify = prettify;
  }
});

// node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
var require_XMLParser = __commonJS({
  "node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports, module2) {
    var { buildOptions } = require_OptionsBuilder();
    var OrderedObjParser = require_OrderedObjParser();
    var { prettify } = require_node2json();
    var validator2 = require_validator();
    var XMLParser2 = class {
      constructor(options) {
        this.externalEntities = {};
        this.options = buildOptions(options);
      }
      /**
       * Parse XML dats to JS object 
       * @param {string|Buffer} xmlData 
       * @param {boolean|Object} validationOption 
       */
      parse(xmlData, validationOption) {
        if (typeof xmlData === "string") {
        } else if (xmlData.toString) {
          xmlData = xmlData.toString();
        } else {
          throw new Error("XML data is accepted in String or Bytes[] form.");
        }
        if (validationOption) {
          if (validationOption === true)
            validationOption = {};
          const result = validator2.validate(xmlData, validationOption);
          if (result !== true) {
            throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
          }
        }
        const orderedObjParser = new OrderedObjParser(this.options);
        orderedObjParser.addExternalEntities(this.externalEntities);
        const orderedResult = orderedObjParser.parseXml(xmlData);
        if (this.options.preserveOrder || orderedResult === void 0)
          return orderedResult;
        else
          return prettify(orderedResult, this.options);
      }
      /**
       * Add Entity which is not by default supported by this library
       * @param {string} key 
       * @param {string} value 
       */
      addEntity(key, value) {
        if (value.indexOf("&") !== -1) {
          throw new Error("Entity value can't have '&'");
        } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
          throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
        } else if (value === "&") {
          throw new Error("An entity with value '&' is not permitted");
        } else {
          this.externalEntities[key] = value;
        }
      }
    };
    module2.exports = XMLParser2;
  }
});

// node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
var require_orderedJs2Xml = __commonJS({
  "node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports, module2) {
    var EOL = "\n";
    function toXml(jArray, options) {
      let indentation = "";
      if (options.format && options.indentBy.length > 0) {
        indentation = EOL;
      }
      return arrToStr(jArray, options, "", indentation);
    }
    function arrToStr(arr2, options, jPath, indentation) {
      let xmlStr = "";
      let isPreviousElementTag = false;
      for (let i3 = 0; i3 < arr2.length; i3++) {
        const tagObj = arr2[i3];
        const tagName = propName(tagObj);
        if (tagName === void 0)
          continue;
        let newJPath = "";
        if (jPath.length === 0)
          newJPath = tagName;
        else
          newJPath = `${jPath}.${tagName}`;
        if (tagName === options.textNodeName) {
          let tagText = tagObj[tagName];
          if (!isStopNode(newJPath, options)) {
            tagText = options.tagValueProcessor(tagName, tagText);
            tagText = replaceEntitiesValue(tagText, options);
          }
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += tagText;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.cdataPropName) {
          if (isPreviousElementTag) {
            xmlStr += indentation;
          }
          xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
          isPreviousElementTag = false;
          continue;
        } else if (tagName === options.commentPropName) {
          xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
          isPreviousElementTag = true;
          continue;
        } else if (tagName[0] === "?") {
          const attStr2 = attr_to_str(tagObj[":@"], options);
          const tempInd = tagName === "?xml" ? "" : indentation;
          let piTextNodeName = tagObj[tagName][0][options.textNodeName];
          piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
          xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
          isPreviousElementTag = true;
          continue;
        }
        let newIdentation = indentation;
        if (newIdentation !== "") {
          newIdentation += options.indentBy;
        }
        const attStr = attr_to_str(tagObj[":@"], options);
        const tagStart = indentation + `<${tagName}${attStr}`;
        const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
        if (options.unpairedTags.indexOf(tagName) !== -1) {
          if (options.suppressUnpairedNode)
            xmlStr += tagStart + ">";
          else
            xmlStr += tagStart + "/>";
        } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
          xmlStr += tagStart + "/>";
        } else if (tagValue && tagValue.endsWith(">")) {
          xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
        } else {
          xmlStr += tagStart + ">";
          if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
            xmlStr += indentation + options.indentBy + tagValue + indentation;
          } else {
            xmlStr += tagValue;
          }
          xmlStr += `</${tagName}>`;
        }
        isPreviousElementTag = true;
      }
      return xmlStr;
    }
    function propName(obj) {
      const keys = Object.keys(obj);
      for (let i3 = 0; i3 < keys.length; i3++) {
        const key = keys[i3];
        if (!obj.hasOwnProperty(key))
          continue;
        if (key !== ":@")
          return key;
      }
    }
    function attr_to_str(attrMap, options) {
      let attrStr = "";
      if (attrMap && !options.ignoreAttributes) {
        for (let attr in attrMap) {
          if (!attrMap.hasOwnProperty(attr))
            continue;
          let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
          attrVal = replaceEntitiesValue(attrVal, options);
          if (attrVal === true && options.suppressBooleanAttributes) {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
          } else {
            attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
          }
        }
      }
      return attrStr;
    }
    function isStopNode(jPath, options) {
      jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
      let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
      for (let index2 in options.stopNodes) {
        if (options.stopNodes[index2] === jPath || options.stopNodes[index2] === "*." + tagName)
          return true;
      }
      return false;
    }
    function replaceEntitiesValue(textValue, options) {
      if (textValue && textValue.length > 0 && options.processEntities) {
        for (let i3 = 0; i3 < options.entities.length; i3++) {
          const entity = options.entities[i3];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    }
    module2.exports = toXml;
  }
});

// node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
var require_json2xml = __commonJS({
  "node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports, module2) {
    "use strict";
    var buildFromOrderedJs = require_orderedJs2Xml();
    var defaultOptions4 = {
      attributeNamePrefix: "@_",
      attributesGroupName: false,
      textNodeName: "#text",
      ignoreAttributes: true,
      cdataPropName: false,
      format: false,
      indentBy: "  ",
      suppressEmptyNode: false,
      suppressUnpairedNode: true,
      suppressBooleanAttributes: true,
      tagValueProcessor: function(key, a3) {
        return a3;
      },
      attributeValueProcessor: function(attrName, a3) {
        return a3;
      },
      preserveOrder: false,
      commentPropName: false,
      unpairedTags: [],
      entities: [
        { regex: new RegExp("&", "g"), val: "&amp;" },
        //it must be on top
        { regex: new RegExp(">", "g"), val: "&gt;" },
        { regex: new RegExp("<", "g"), val: "&lt;" },
        { regex: new RegExp("'", "g"), val: "&apos;" },
        { regex: new RegExp('"', "g"), val: "&quot;" }
      ],
      processEntities: true,
      stopNodes: [],
      // transformTagName: false,
      // transformAttributeName: false,
      oneListGroup: false
    };
    function Builder(options) {
      this.options = Object.assign({}, defaultOptions4, options);
      if (this.options.ignoreAttributes || this.options.attributesGroupName) {
        this.isAttribute = function() {
          return false;
        };
      } else {
        this.attrPrefixLen = this.options.attributeNamePrefix.length;
        this.isAttribute = isAttribute;
      }
      this.processTextOrObjNode = processTextOrObjNode;
      if (this.options.format) {
        this.indentate = indentate;
        this.tagEndChar = ">\n";
        this.newLine = "\n";
      } else {
        this.indentate = function() {
          return "";
        };
        this.tagEndChar = ">";
        this.newLine = "";
      }
    }
    Builder.prototype.build = function(jObj) {
      if (this.options.preserveOrder) {
        return buildFromOrderedJs(jObj, this.options);
      } else {
        if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
          jObj = {
            [this.options.arrayNodeName]: jObj
          };
        }
        return this.j2x(jObj, 0).val;
      }
    };
    Builder.prototype.j2x = function(jObj, level) {
      let attrStr = "";
      let val2 = "";
      for (let key in jObj) {
        if (!Object.prototype.hasOwnProperty.call(jObj, key))
          continue;
        if (typeof jObj[key] === "undefined") {
          if (this.isAttribute(key)) {
            val2 += "";
          }
        } else if (jObj[key] === null) {
          if (this.isAttribute(key)) {
            val2 += "";
          } else if (key[0] === "?") {
            val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
          } else {
            val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
          }
        } else if (jObj[key] instanceof Date) {
          val2 += this.buildTextValNode(jObj[key], key, "", level);
        } else if (typeof jObj[key] !== "object") {
          const attr = this.isAttribute(key);
          if (attr) {
            attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
          } else {
            if (key === this.options.textNodeName) {
              let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
              val2 += this.replaceEntitiesValue(newval);
            } else {
              val2 += this.buildTextValNode(jObj[key], key, "", level);
            }
          }
        } else if (Array.isArray(jObj[key])) {
          const arrLen = jObj[key].length;
          let listTagVal = "";
          let listTagAttr = "";
          for (let j3 = 0; j3 < arrLen; j3++) {
            const item = jObj[key][j3];
            if (typeof item === "undefined") {
            } else if (item === null) {
              if (key[0] === "?")
                val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
              else
                val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
            } else if (typeof item === "object") {
              if (this.options.oneListGroup) {
                const result = this.j2x(item, level + 1);
                listTagVal += result.val;
                if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
                  listTagAttr += result.attrStr;
                }
              } else {
                listTagVal += this.processTextOrObjNode(item, key, level);
              }
            } else {
              if (this.options.oneListGroup) {
                let textValue = this.options.tagValueProcessor(key, item);
                textValue = this.replaceEntitiesValue(textValue);
                listTagVal += textValue;
              } else {
                listTagVal += this.buildTextValNode(item, key, "", level);
              }
            }
          }
          if (this.options.oneListGroup) {
            listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
          }
          val2 += listTagVal;
        } else {
          if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
            const Ks = Object.keys(jObj[key]);
            const L = Ks.length;
            for (let j3 = 0; j3 < L; j3++) {
              attrStr += this.buildAttrPairStr(Ks[j3], "" + jObj[key][Ks[j3]]);
            }
          } else {
            val2 += this.processTextOrObjNode(jObj[key], key, level);
          }
        }
      }
      return { attrStr, val: val2 };
    };
    Builder.prototype.buildAttrPairStr = function(attrName, val2) {
      val2 = this.options.attributeValueProcessor(attrName, "" + val2);
      val2 = this.replaceEntitiesValue(val2);
      if (this.options.suppressBooleanAttributes && val2 === "true") {
        return " " + attrName;
      } else
        return " " + attrName + '="' + val2 + '"';
    };
    function processTextOrObjNode(object, key, level) {
      const result = this.j2x(object, level + 1);
      if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
        return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
      } else {
        return this.buildObjectNode(result.val, key, result.attrStr, level);
      }
    }
    Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
      if (val2 === "") {
        if (key[0] === "?")
          return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
        else {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        }
      } else {
        let tagEndExp = "</" + key + this.tagEndChar;
        let piClosingChar = "";
        if (key[0] === "?") {
          piClosingChar = "?";
          tagEndExp = "";
        }
        if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
        } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
          return this.indentate(level) + `<!--${val2}-->` + this.newLine;
        } else {
          return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
        }
      }
    };
    Builder.prototype.closeTag = function(key) {
      let closeTag = "";
      if (this.options.unpairedTags.indexOf(key) !== -1) {
        if (!this.options.suppressUnpairedNode)
          closeTag = "/";
      } else if (this.options.suppressEmptyNode) {
        closeTag = "/";
      } else {
        closeTag = `></${key}`;
      }
      return closeTag;
    };
    Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
      if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
        return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
      } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
        return this.indentate(level) + `<!--${val2}-->` + this.newLine;
      } else if (key[0] === "?") {
        return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
      } else {
        let textValue = this.options.tagValueProcessor(key, val2);
        textValue = this.replaceEntitiesValue(textValue);
        if (textValue === "") {
          return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
        } else {
          return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
        }
      }
    };
    Builder.prototype.replaceEntitiesValue = function(textValue) {
      if (textValue && textValue.length > 0 && this.options.processEntities) {
        for (let i3 = 0; i3 < this.options.entities.length; i3++) {
          const entity = this.options.entities[i3];
          textValue = textValue.replace(entity.regex, entity.val);
        }
      }
      return textValue;
    };
    function indentate(level) {
      return this.options.indentBy.repeat(level);
    }
    function isAttribute(name) {
      if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
        return name.substr(this.attrPrefixLen);
      } else {
        return false;
      }
    }
    module2.exports = Builder;
  }
});

// node_modules/fast-xml-parser/src/fxp.js
var require_fxp = __commonJS({
  "node_modules/fast-xml-parser/src/fxp.js"(exports, module2) {
    "use strict";
    var validator2 = require_validator();
    var XMLParser2 = require_XMLParser();
    var XMLBuilder = require_json2xml();
    module2.exports = {
      XMLParser: XMLParser2,
      XMLValidator: validator2,
      XMLBuilder
    };
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
var import_fast_xml_parser, parseXmlBody, parseXmlErrorBody;
var init_parseXmlBody = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
    init_dist_es33();
    import_fast_xml_parser = __toESM(require_fxp());
    init_common();
    parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
      if (encoded.length) {
        const parser = new import_fast_xml_parser.XMLParser({
          attributeNamePrefix: "",
          htmlEntities: true,
          ignoreAttributes: false,
          ignoreDeclaration: true,
          parseTagValue: false,
          trimValues: false,
          tagValueProcessor: (_2, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0
        });
        parser.addEntity("#xD", "\r");
        parser.addEntity("#10", "\n");
        let parsedObj;
        try {
          parsedObj = parser.parse(encoded, true);
        } catch (e3) {
          if (e3 && typeof e3 === "object") {
            Object.defineProperty(e3, "$responseBodyText", {
              value: encoded
            });
          }
          throw e3;
        }
        const textNodeName = "#text";
        const key = Object.keys(parsedObj)[0];
        const parsedObjToReturn = parsedObj[key];
        if (parsedObjToReturn[textNodeName]) {
          parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
          delete parsedObjToReturn[textNodeName];
        }
        return getValueFromTextNode(parsedObjToReturn);
      }
      return {};
    });
    parseXmlErrorBody = async (errorBody, context) => {
      const value = await parseXmlBody(errorBody, context);
      if (value.Error) {
        value.Error.message = value.Error.message ?? value.Error.Message;
      }
      return value;
    };
  }
});

// node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
var init_protocols = __esm({
  "node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
    init_coercing_serializers();
    init_awsExpectUnion();
    init_parseJsonBody();
    init_parseXmlBody();
  }
});

// node_modules/@aws-sdk/core/dist-es/index.js
var init_dist_es43 = __esm({
  "node_modules/@aws-sdk/core/dist-es/index.js"() {
    init_client4();
    init_httpAuthSchemes2();
    init_protocols();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "cognito-identity",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var defaultCognitoIdentityHttpAuthSchemeParametersProvider, defaultCognitoIdentityHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
var init_httpAuthSchemeProvider = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthSchemeProvider.js"() {
    init_dist_es43();
    init_dist_es13();
    defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "GetCredentialsForIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "GetId": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "GetOpenIdToken": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        case "UnlinkIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        }
      }
      return options;
    };
    resolveHttpAuthSchemeConfig = (config) => {
      const config_0 = resolveAwsSdkSigV4Config(config);
      return {
        ...config_0
      };
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters, commonParams;
var init_EndpointParameters = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/EndpointParameters.js"() {
    resolveClientEndpointParameters = (options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        defaultSigningName: "cognito-identity"
      };
    };
    commonParams = {
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/package.json
var package_default;
var init_package = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/package.json"() {
    package_default = {
      name: "@aws-sdk/client-cognito-identity",
      description: "AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native",
      version: "3.645.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-cognito-identity",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo cognito-identity",
        "test:e2e": "ts-mocha test/**/*.ispec.ts && karma start karma.conf.js"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/client-sso-oidc": "3.645.0",
        "@aws-sdk/client-sts": "3.645.0",
        "@aws-sdk/core": "3.635.0",
        "@aws-sdk/credential-provider-node": "3.645.0",
        "@aws-sdk/middleware-host-header": "3.620.0",
        "@aws-sdk/middleware-logger": "3.609.0",
        "@aws-sdk/middleware-recursion-detection": "3.620.0",
        "@aws-sdk/middleware-user-agent": "3.645.0",
        "@aws-sdk/region-config-resolver": "3.614.0",
        "@aws-sdk/types": "3.609.0",
        "@aws-sdk/util-endpoints": "3.645.0",
        "@aws-sdk/util-user-agent-browser": "3.609.0",
        "@aws-sdk/util-user-agent-node": "3.614.0",
        "@smithy/config-resolver": "^3.0.5",
        "@smithy/core": "^2.4.0",
        "@smithy/fetch-http-handler": "^3.2.4",
        "@smithy/hash-node": "^3.0.3",
        "@smithy/invalid-dependency": "^3.0.3",
        "@smithy/middleware-content-length": "^3.0.5",
        "@smithy/middleware-endpoint": "^3.1.0",
        "@smithy/middleware-retry": "^3.0.15",
        "@smithy/middleware-serde": "^3.0.3",
        "@smithy/middleware-stack": "^3.0.3",
        "@smithy/node-config-provider": "^3.1.4",
        "@smithy/node-http-handler": "^3.1.4",
        "@smithy/protocol-http": "^4.1.0",
        "@smithy/smithy-client": "^3.2.0",
        "@smithy/types": "^3.3.0",
        "@smithy/url-parser": "^3.0.3",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.15",
        "@smithy/util-defaults-mode-node": "^3.0.15",
        "@smithy/util-endpoints": "^2.0.5",
        "@smithy/util-middleware": "^3.0.3",
        "@smithy/util-retry": "^3.0.3",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@aws-sdk/client-iam": "3.645.0",
        "@tsconfig/node16": "16.1.3",
        "@types/chai": "^4.2.11",
        "@types/mocha": "^8.0.4",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-cognito-identity",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-cognito-identity"
      }
    };
  }
});

// node_modules/@aws-crypto/sha256-browser/build/module/constants.js
var SHA_256_HASH, SHA_256_HMAC_ALGO, EMPTY_DATA_SHA_256;
var init_constants7 = __esm({
  "node_modules/@aws-crypto/sha256-browser/build/module/constants.js"() {
    SHA_256_HASH = { name: "SHA-256" };
    SHA_256_HMAC_ALGO = {
      name: "HMAC",
      hash: SHA_256_HASH
    };
    EMPTY_DATA_SHA_256 = new Uint8Array([
      227,
      176,
      196,
      66,
      152,
      252,
      28,
      20,
      154,
      251,
      244,
      200,
      153,
      111,
      185,
      36,
      39,
      174,
      65,
      228,
      100,
      155,
      147,
      76,
      164,
      149,
      153,
      27,
      120,
      82,
      184,
      85
    ]);
  }
});

// node_modules/@aws-sdk/util-locate-window/dist-es/index.js
function locateWindow() {
  if (typeof window !== "undefined") {
    return window;
  } else if (typeof self !== "undefined") {
    return self;
  }
  return fallbackWindow;
}
var fallbackWindow;
var init_dist_es44 = __esm({
  "node_modules/@aws-sdk/util-locate-window/dist-es/index.js"() {
    fallbackWindow = {};
  }
});

// node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js
var import_util3, Sha256;
var init_webCryptoSha256 = __esm({
  "node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js"() {
    import_util3 = __toESM(require_main());
    init_constants7();
    init_dist_es44();
    Sha256 = /** @class */
    function() {
      function Sha2563(secret) {
        this.toHash = new Uint8Array(0);
        this.secret = secret;
        this.reset();
      }
      Sha2563.prototype.update = function(data) {
        if ((0, import_util3.isEmptyData)(data)) {
          return;
        }
        var update2 = (0, import_util3.convertToBuffer)(data);
        var typedArray = new Uint8Array(this.toHash.byteLength + update2.byteLength);
        typedArray.set(this.toHash, 0);
        typedArray.set(update2, this.toHash.byteLength);
        this.toHash = typedArray;
      };
      Sha2563.prototype.digest = function() {
        var _this = this;
        if (this.key) {
          return this.key.then(function(key) {
            return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO, key, _this.toHash).then(function(data) {
              return new Uint8Array(data);
            });
          });
        }
        if ((0, import_util3.isEmptyData)(this.toHash)) {
          return Promise.resolve(EMPTY_DATA_SHA_256);
        }
        return Promise.resolve().then(function() {
          return locateWindow().crypto.subtle.digest(SHA_256_HASH, _this.toHash);
        }).then(function(data) {
          return Promise.resolve(new Uint8Array(data));
        });
      };
      Sha2563.prototype.reset = function() {
        var _this = this;
        this.toHash = new Uint8Array(0);
        if (this.secret && this.secret !== void 0) {
          this.key = new Promise(function(resolve, reject) {
            locateWindow().crypto.subtle.importKey("raw", (0, import_util3.convertToBuffer)(_this.secret), SHA_256_HMAC_ALGO, false, ["sign"]).then(resolve, reject);
          });
          this.key.catch(function() {
          });
        }
      };
      return Sha2563;
    }();
  }
});

// node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js
function supportsWebCrypto(window2) {
  if (supportsSecureRandom(window2) && typeof window2.crypto.subtle === "object") {
    var subtle = window2.crypto.subtle;
    return supportsSubtleCrypto(subtle);
  }
  return false;
}
function supportsSecureRandom(window2) {
  if (typeof window2 === "object" && typeof window2.crypto === "object") {
    var getRandomValues6 = window2.crypto.getRandomValues;
    return typeof getRandomValues6 === "function";
  }
  return false;
}
function supportsSubtleCrypto(subtle) {
  return subtle && subtleCryptoMethods.every(function(methodName) {
    return typeof subtle[methodName] === "function";
  });
}
var subtleCryptoMethods;
var init_supportsWebCrypto = __esm({
  "node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js"() {
    subtleCryptoMethods = [
      "decrypt",
      "digest",
      "encrypt",
      "exportKey",
      "generateKey",
      "importKey",
      "sign",
      "verify"
    ];
  }
});

// node_modules/@aws-crypto/supports-web-crypto/build/module/index.js
var init_module = __esm({
  "node_modules/@aws-crypto/supports-web-crypto/build/module/index.js"() {
    init_supportsWebCrypto();
  }
});

// node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js
var import_sha256_js, import_util4, Sha2562;
var init_crossPlatformSha256 = __esm({
  "node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js"() {
    init_webCryptoSha256();
    import_sha256_js = __toESM(require_main2());
    init_module();
    init_dist_es44();
    import_util4 = __toESM(require_main());
    Sha2562 = /** @class */
    function() {
      function Sha2563(secret) {
        if (supportsWebCrypto(locateWindow())) {
          this.hash = new Sha256(secret);
        } else {
          this.hash = new import_sha256_js.Sha256(secret);
        }
      }
      Sha2563.prototype.update = function(data, encoding) {
        this.hash.update((0, import_util4.convertToBuffer)(data));
      };
      Sha2563.prototype.digest = function() {
        return this.hash.digest();
      };
      Sha2563.prototype.reset = function() {
        this.hash.reset();
      };
      return Sha2563;
    }();
  }
});

// node_modules/@aws-crypto/sha256-browser/build/module/index.js
var init_module2 = __esm({
  "node_modules/@aws-crypto/sha256-browser/build/module/index.js"() {
    init_crossPlatformSha256();
    init_webCryptoSha256();
  }
});

// node_modules/bowser/es5.js
var require_es5 = __commonJS({
  "node_modules/bowser/es5.js"(exports, module2) {
    !function(e3, t3) {
      "object" == typeof exports && "object" == typeof module2 ? module2.exports = t3() : "function" == typeof define && define.amd ? define([], t3) : "object" == typeof exports ? exports.bowser = t3() : e3.bowser = t3();
    }(exports, function() {
      return function(e3) {
        var t3 = {};
        function r4(n4) {
          if (t3[n4])
            return t3[n4].exports;
          var i3 = t3[n4] = { i: n4, l: false, exports: {} };
          return e3[n4].call(i3.exports, i3, i3.exports, r4), i3.l = true, i3.exports;
        }
        return r4.m = e3, r4.c = t3, r4.d = function(e4, t4, n4) {
          r4.o(e4, t4) || Object.defineProperty(e4, t4, { enumerable: true, get: n4 });
        }, r4.r = function(e4) {
          "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e4, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e4, "__esModule", { value: true });
        }, r4.t = function(e4, t4) {
          if (1 & t4 && (e4 = r4(e4)), 8 & t4)
            return e4;
          if (4 & t4 && "object" == typeof e4 && e4 && e4.__esModule)
            return e4;
          var n4 = /* @__PURE__ */ Object.create(null);
          if (r4.r(n4), Object.defineProperty(n4, "default", { enumerable: true, value: e4 }), 2 & t4 && "string" != typeof e4)
            for (var i3 in e4)
              r4.d(n4, i3, function(t5) {
                return e4[t5];
              }.bind(null, i3));
          return n4;
        }, r4.n = function(e4) {
          var t4 = e4 && e4.__esModule ? function() {
            return e4.default;
          } : function() {
            return e4;
          };
          return r4.d(t4, "a", t4), t4;
        }, r4.o = function(e4, t4) {
          return Object.prototype.hasOwnProperty.call(e4, t4);
        }, r4.p = "", r4(r4.s = 90);
      }({ 17: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4 = r4(18), i3 = function() {
          function e4() {
          }
          return e4.getFirstMatch = function(e5, t4) {
            var r5 = t4.match(e5);
            return r5 && r5.length > 0 && r5[1] || "";
          }, e4.getSecondMatch = function(e5, t4) {
            var r5 = t4.match(e5);
            return r5 && r5.length > 1 && r5[2] || "";
          }, e4.matchAndReturnConst = function(e5, t4, r5) {
            if (e5.test(t4))
              return r5;
          }, e4.getWindowsVersionName = function(e5) {
            switch (e5) {
              case "NT":
                return "NT";
              case "XP":
                return "XP";
              case "NT 5.0":
                return "2000";
              case "NT 5.1":
                return "XP";
              case "NT 5.2":
                return "2003";
              case "NT 6.0":
                return "Vista";
              case "NT 6.1":
                return "7";
              case "NT 6.2":
                return "8";
              case "NT 6.3":
                return "8.1";
              case "NT 10.0":
                return "10";
              default:
                return;
            }
          }, e4.getMacOSVersionName = function(e5) {
            var t4 = e5.split(".").splice(0, 2).map(function(e6) {
              return parseInt(e6, 10) || 0;
            });
            if (t4.push(0), 10 === t4[0])
              switch (t4[1]) {
                case 5:
                  return "Leopard";
                case 6:
                  return "Snow Leopard";
                case 7:
                  return "Lion";
                case 8:
                  return "Mountain Lion";
                case 9:
                  return "Mavericks";
                case 10:
                  return "Yosemite";
                case 11:
                  return "El Capitan";
                case 12:
                  return "Sierra";
                case 13:
                  return "High Sierra";
                case 14:
                  return "Mojave";
                case 15:
                  return "Catalina";
                default:
                  return;
              }
          }, e4.getAndroidVersionName = function(e5) {
            var t4 = e5.split(".").splice(0, 2).map(function(e6) {
              return parseInt(e6, 10) || 0;
            });
            if (t4.push(0), !(1 === t4[0] && t4[1] < 5))
              return 1 === t4[0] && t4[1] < 6 ? "Cupcake" : 1 === t4[0] && t4[1] >= 6 ? "Donut" : 2 === t4[0] && t4[1] < 2 ? "Eclair" : 2 === t4[0] && 2 === t4[1] ? "Froyo" : 2 === t4[0] && t4[1] > 2 ? "Gingerbread" : 3 === t4[0] ? "Honeycomb" : 4 === t4[0] && t4[1] < 1 ? "Ice Cream Sandwich" : 4 === t4[0] && t4[1] < 4 ? "Jelly Bean" : 4 === t4[0] && t4[1] >= 4 ? "KitKat" : 5 === t4[0] ? "Lollipop" : 6 === t4[0] ? "Marshmallow" : 7 === t4[0] ? "Nougat" : 8 === t4[0] ? "Oreo" : 9 === t4[0] ? "Pie" : void 0;
          }, e4.getVersionPrecision = function(e5) {
            return e5.split(".").length;
          }, e4.compareVersions = function(t4, r5, n5) {
            void 0 === n5 && (n5 = false);
            var i4 = e4.getVersionPrecision(t4), s4 = e4.getVersionPrecision(r5), a3 = Math.max(i4, s4), o3 = 0, u3 = e4.map([t4, r5], function(t5) {
              var r6 = a3 - e4.getVersionPrecision(t5), n6 = t5 + new Array(r6 + 1).join(".0");
              return e4.map(n6.split("."), function(e5) {
                return new Array(20 - e5.length).join("0") + e5;
              }).reverse();
            });
            for (n5 && (o3 = a3 - Math.min(i4, s4)), a3 -= 1; a3 >= o3; ) {
              if (u3[0][a3] > u3[1][a3])
                return 1;
              if (u3[0][a3] === u3[1][a3]) {
                if (a3 === o3)
                  return 0;
                a3 -= 1;
              } else if (u3[0][a3] < u3[1][a3])
                return -1;
            }
          }, e4.map = function(e5, t4) {
            var r5, n5 = [];
            if (Array.prototype.map)
              return Array.prototype.map.call(e5, t4);
            for (r5 = 0; r5 < e5.length; r5 += 1)
              n5.push(t4(e5[r5]));
            return n5;
          }, e4.find = function(e5, t4) {
            var r5, n5;
            if (Array.prototype.find)
              return Array.prototype.find.call(e5, t4);
            for (r5 = 0, n5 = e5.length; r5 < n5; r5 += 1) {
              var i4 = e5[r5];
              if (t4(i4, r5))
                return i4;
            }
          }, e4.assign = function(e5) {
            for (var t4, r5, n5 = e5, i4 = arguments.length, s4 = new Array(i4 > 1 ? i4 - 1 : 0), a3 = 1; a3 < i4; a3++)
              s4[a3 - 1] = arguments[a3];
            if (Object.assign)
              return Object.assign.apply(Object, [e5].concat(s4));
            var o3 = function() {
              var e6 = s4[t4];
              "object" == typeof e6 && null !== e6 && Object.keys(e6).forEach(function(t5) {
                n5[t5] = e6[t5];
              });
            };
            for (t4 = 0, r5 = s4.length; t4 < r5; t4 += 1)
              o3();
            return e5;
          }, e4.getBrowserAlias = function(e5) {
            return n4.BROWSER_ALIASES_MAP[e5];
          }, e4.getBrowserTypeByAlias = function(e5) {
            return n4.BROWSER_MAP[e5] || "";
          }, e4;
        }();
        t3.default = i3, e3.exports = t3.default;
      }, 18: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.ENGINE_MAP = t3.OS_MAP = t3.PLATFORMS_MAP = t3.BROWSER_MAP = t3.BROWSER_ALIASES_MAP = void 0;
        t3.BROWSER_ALIASES_MAP = { "Amazon Silk": "amazon_silk", "Android Browser": "android", Bada: "bada", BlackBerry: "blackberry", Chrome: "chrome", Chromium: "chromium", Electron: "electron", Epiphany: "epiphany", Firefox: "firefox", Focus: "focus", Generic: "generic", "Google Search": "google_search", Googlebot: "googlebot", "Internet Explorer": "ie", "K-Meleon": "k_meleon", Maxthon: "maxthon", "Microsoft Edge": "edge", "MZ Browser": "mz", "NAVER Whale Browser": "naver", Opera: "opera", "Opera Coast": "opera_coast", PhantomJS: "phantomjs", Puffin: "puffin", QupZilla: "qupzilla", QQ: "qq", QQLite: "qqlite", Safari: "safari", Sailfish: "sailfish", "Samsung Internet for Android": "samsung_internet", SeaMonkey: "seamonkey", Sleipnir: "sleipnir", Swing: "swing", Tizen: "tizen", "UC Browser": "uc", Vivaldi: "vivaldi", "WebOS Browser": "webos", WeChat: "wechat", "Yandex Browser": "yandex", Roku: "roku" };
        t3.BROWSER_MAP = { amazon_silk: "Amazon Silk", android: "Android Browser", bada: "Bada", blackberry: "BlackBerry", chrome: "Chrome", chromium: "Chromium", electron: "Electron", epiphany: "Epiphany", firefox: "Firefox", focus: "Focus", generic: "Generic", googlebot: "Googlebot", google_search: "Google Search", ie: "Internet Explorer", k_meleon: "K-Meleon", maxthon: "Maxthon", edge: "Microsoft Edge", mz: "MZ Browser", naver: "NAVER Whale Browser", opera: "Opera", opera_coast: "Opera Coast", phantomjs: "PhantomJS", puffin: "Puffin", qupzilla: "QupZilla", qq: "QQ Browser", qqlite: "QQ Browser Lite", safari: "Safari", sailfish: "Sailfish", samsung_internet: "Samsung Internet for Android", seamonkey: "SeaMonkey", sleipnir: "Sleipnir", swing: "Swing", tizen: "Tizen", uc: "UC Browser", vivaldi: "Vivaldi", webos: "WebOS Browser", wechat: "WeChat", yandex: "Yandex Browser" };
        t3.PLATFORMS_MAP = { tablet: "tablet", mobile: "mobile", desktop: "desktop", tv: "tv" };
        t3.OS_MAP = { WindowsPhone: "Windows Phone", Windows: "Windows", MacOS: "macOS", iOS: "iOS", Android: "Android", WebOS: "WebOS", BlackBerry: "BlackBerry", Bada: "Bada", Tizen: "Tizen", Linux: "Linux", ChromeOS: "Chrome OS", PlayStation4: "PlayStation 4", Roku: "Roku" };
        t3.ENGINE_MAP = { EdgeHTML: "EdgeHTML", Blink: "Blink", Trident: "Trident", Presto: "Presto", Gecko: "Gecko", WebKit: "WebKit" };
      }, 90: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4, i3 = (n4 = r4(91)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
        function a3(e4, t4) {
          for (var r5 = 0; r5 < t4.length; r5++) {
            var n5 = t4[r5];
            n5.enumerable = n5.enumerable || false, n5.configurable = true, "value" in n5 && (n5.writable = true), Object.defineProperty(e4, n5.key, n5);
          }
        }
        var o3 = function() {
          function e4() {
          }
          var t4, r5, n5;
          return e4.getParser = function(e5, t5) {
            if (void 0 === t5 && (t5 = false), "string" != typeof e5)
              throw new Error("UserAgent should be a string");
            return new i3.default(e5, t5);
          }, e4.parse = function(e5) {
            return new i3.default(e5).getResult();
          }, t4 = e4, n5 = [{ key: "BROWSER_MAP", get: function() {
            return s4.BROWSER_MAP;
          } }, { key: "ENGINE_MAP", get: function() {
            return s4.ENGINE_MAP;
          } }, { key: "OS_MAP", get: function() {
            return s4.OS_MAP;
          } }, { key: "PLATFORMS_MAP", get: function() {
            return s4.PLATFORMS_MAP;
          } }], (r5 = null) && a3(t4.prototype, r5), n5 && a3(t4, n5), e4;
        }();
        t3.default = o3, e3.exports = t3.default;
      }, 91: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4 = u3(r4(92)), i3 = u3(r4(93)), s4 = u3(r4(94)), a3 = u3(r4(95)), o3 = u3(r4(17));
        function u3(e4) {
          return e4 && e4.__esModule ? e4 : { default: e4 };
        }
        var d3 = function() {
          function e4(e5, t5) {
            if (void 0 === t5 && (t5 = false), null == e5 || "" === e5)
              throw new Error("UserAgent parameter can't be empty");
            this._ua = e5, this.parsedResult = {}, true !== t5 && this.parse();
          }
          var t4 = e4.prototype;
          return t4.getUA = function() {
            return this._ua;
          }, t4.test = function(e5) {
            return e5.test(this._ua);
          }, t4.parseBrowser = function() {
            var e5 = this;
            this.parsedResult.browser = {};
            var t5 = o3.default.find(n4.default, function(t6) {
              if ("function" == typeof t6.test)
                return t6.test(e5);
              if (t6.test instanceof Array)
                return t6.test.some(function(t7) {
                  return e5.test(t7);
                });
              throw new Error("Browser's test function is not valid");
            });
            return t5 && (this.parsedResult.browser = t5.describe(this.getUA())), this.parsedResult.browser;
          }, t4.getBrowser = function() {
            return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser();
          }, t4.getBrowserName = function(e5) {
            return e5 ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || "";
          }, t4.getBrowserVersion = function() {
            return this.getBrowser().version;
          }, t4.getOS = function() {
            return this.parsedResult.os ? this.parsedResult.os : this.parseOS();
          }, t4.parseOS = function() {
            var e5 = this;
            this.parsedResult.os = {};
            var t5 = o3.default.find(i3.default, function(t6) {
              if ("function" == typeof t6.test)
                return t6.test(e5);
              if (t6.test instanceof Array)
                return t6.test.some(function(t7) {
                  return e5.test(t7);
                });
              throw new Error("Browser's test function is not valid");
            });
            return t5 && (this.parsedResult.os = t5.describe(this.getUA())), this.parsedResult.os;
          }, t4.getOSName = function(e5) {
            var t5 = this.getOS().name;
            return e5 ? String(t5).toLowerCase() || "" : t5 || "";
          }, t4.getOSVersion = function() {
            return this.getOS().version;
          }, t4.getPlatform = function() {
            return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform();
          }, t4.getPlatformType = function(e5) {
            void 0 === e5 && (e5 = false);
            var t5 = this.getPlatform().type;
            return e5 ? String(t5).toLowerCase() || "" : t5 || "";
          }, t4.parsePlatform = function() {
            var e5 = this;
            this.parsedResult.platform = {};
            var t5 = o3.default.find(s4.default, function(t6) {
              if ("function" == typeof t6.test)
                return t6.test(e5);
              if (t6.test instanceof Array)
                return t6.test.some(function(t7) {
                  return e5.test(t7);
                });
              throw new Error("Browser's test function is not valid");
            });
            return t5 && (this.parsedResult.platform = t5.describe(this.getUA())), this.parsedResult.platform;
          }, t4.getEngine = function() {
            return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine();
          }, t4.getEngineName = function(e5) {
            return e5 ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || "";
          }, t4.parseEngine = function() {
            var e5 = this;
            this.parsedResult.engine = {};
            var t5 = o3.default.find(a3.default, function(t6) {
              if ("function" == typeof t6.test)
                return t6.test(e5);
              if (t6.test instanceof Array)
                return t6.test.some(function(t7) {
                  return e5.test(t7);
                });
              throw new Error("Browser's test function is not valid");
            });
            return t5 && (this.parsedResult.engine = t5.describe(this.getUA())), this.parsedResult.engine;
          }, t4.parse = function() {
            return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(), this;
          }, t4.getResult = function() {
            return o3.default.assign({}, this.parsedResult);
          }, t4.satisfies = function(e5) {
            var t5 = this, r5 = {}, n5 = 0, i4 = {}, s5 = 0;
            if (Object.keys(e5).forEach(function(t6) {
              var a5 = e5[t6];
              "string" == typeof a5 ? (i4[t6] = a5, s5 += 1) : "object" == typeof a5 && (r5[t6] = a5, n5 += 1);
            }), n5 > 0) {
              var a4 = Object.keys(r5), u4 = o3.default.find(a4, function(e6) {
                return t5.isOS(e6);
              });
              if (u4) {
                var d4 = this.satisfies(r5[u4]);
                if (void 0 !== d4)
                  return d4;
              }
              var c4 = o3.default.find(a4, function(e6) {
                return t5.isPlatform(e6);
              });
              if (c4) {
                var f3 = this.satisfies(r5[c4]);
                if (void 0 !== f3)
                  return f3;
              }
            }
            if (s5 > 0) {
              var l4 = Object.keys(i4), h3 = o3.default.find(l4, function(e6) {
                return t5.isBrowser(e6, true);
              });
              if (void 0 !== h3)
                return this.compareVersion(i4[h3]);
            }
          }, t4.isBrowser = function(e5, t5) {
            void 0 === t5 && (t5 = false);
            var r5 = this.getBrowserName().toLowerCase(), n5 = e5.toLowerCase(), i4 = o3.default.getBrowserTypeByAlias(n5);
            return t5 && i4 && (n5 = i4.toLowerCase()), n5 === r5;
          }, t4.compareVersion = function(e5) {
            var t5 = [0], r5 = e5, n5 = false, i4 = this.getBrowserVersion();
            if ("string" == typeof i4)
              return ">" === e5[0] || "<" === e5[0] ? (r5 = e5.substr(1), "=" === e5[1] ? (n5 = true, r5 = e5.substr(2)) : t5 = [], ">" === e5[0] ? t5.push(1) : t5.push(-1)) : "=" === e5[0] ? r5 = e5.substr(1) : "~" === e5[0] && (n5 = true, r5 = e5.substr(1)), t5.indexOf(o3.default.compareVersions(i4, r5, n5)) > -1;
          }, t4.isOS = function(e5) {
            return this.getOSName(true) === String(e5).toLowerCase();
          }, t4.isPlatform = function(e5) {
            return this.getPlatformType(true) === String(e5).toLowerCase();
          }, t4.isEngine = function(e5) {
            return this.getEngineName(true) === String(e5).toLowerCase();
          }, t4.is = function(e5, t5) {
            return void 0 === t5 && (t5 = false), this.isBrowser(e5, t5) || this.isOS(e5) || this.isPlatform(e5);
          }, t4.some = function(e5) {
            var t5 = this;
            return void 0 === e5 && (e5 = []), e5.some(function(e6) {
              return t5.is(e6);
            });
          }, e4;
        }();
        t3.default = d3, e3.exports = t3.default;
      }, 92: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4, i3 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 };
        var s4 = /version\/(\d+(\.?_?\d+)+)/i, a3 = [{ test: [/googlebot/i], describe: function(e4) {
          var t4 = { name: "Googlebot" }, r5 = i3.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/opera/i], describe: function(e4) {
          var t4 = { name: "Opera" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/opr\/|opios/i], describe: function(e4) {
          var t4 = { name: "Opera" }, r5 = i3.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/SamsungBrowser/i], describe: function(e4) {
          var t4 = { name: "Samsung Internet for Android" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/Whale/i], describe: function(e4) {
          var t4 = { name: "NAVER Whale Browser" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/MZBrowser/i], describe: function(e4) {
          var t4 = { name: "MZ Browser" }, r5 = i3.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/focus/i], describe: function(e4) {
          var t4 = { name: "Focus" }, r5 = i3.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/swing/i], describe: function(e4) {
          var t4 = { name: "Swing" }, r5 = i3.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/coast/i], describe: function(e4) {
          var t4 = { name: "Opera Coast" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/opt\/\d+(?:.?_?\d+)+/i], describe: function(e4) {
          var t4 = { name: "Opera Touch" }, r5 = i3.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/yabrowser/i], describe: function(e4) {
          var t4 = { name: "Yandex Browser" }, r5 = i3.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/ucbrowser/i], describe: function(e4) {
          var t4 = { name: "UC Browser" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/Maxthon|mxios/i], describe: function(e4) {
          var t4 = { name: "Maxthon" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/epiphany/i], describe: function(e4) {
          var t4 = { name: "Epiphany" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/puffin/i], describe: function(e4) {
          var t4 = { name: "Puffin" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/sleipnir/i], describe: function(e4) {
          var t4 = { name: "Sleipnir" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/k-meleon/i], describe: function(e4) {
          var t4 = { name: "K-Meleon" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/micromessenger/i], describe: function(e4) {
          var t4 = { name: "WeChat" }, r5 = i3.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/qqbrowser/i], describe: function(e4) {
          var t4 = { name: /qqbrowserlite/i.test(e4) ? "QQ Browser Lite" : "QQ Browser" }, r5 = i3.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/msie|trident/i], describe: function(e4) {
          var t4 = { name: "Internet Explorer" }, r5 = i3.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/\sedg\//i], describe: function(e4) {
          var t4 = { name: "Microsoft Edge" }, r5 = i3.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/edg([ea]|ios)/i], describe: function(e4) {
          var t4 = { name: "Microsoft Edge" }, r5 = i3.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/vivaldi/i], describe: function(e4) {
          var t4 = { name: "Vivaldi" }, r5 = i3.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/seamonkey/i], describe: function(e4) {
          var t4 = { name: "SeaMonkey" }, r5 = i3.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/sailfish/i], describe: function(e4) {
          var t4 = { name: "Sailfish" }, r5 = i3.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/silk/i], describe: function(e4) {
          var t4 = { name: "Amazon Silk" }, r5 = i3.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/phantom/i], describe: function(e4) {
          var t4 = { name: "PhantomJS" }, r5 = i3.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/slimerjs/i], describe: function(e4) {
          var t4 = { name: "SlimerJS" }, r5 = i3.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e4) {
          var t4 = { name: "BlackBerry" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/(web|hpw)[o0]s/i], describe: function(e4) {
          var t4 = { name: "WebOS Browser" }, r5 = i3.default.getFirstMatch(s4, e4) || i3.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/bada/i], describe: function(e4) {
          var t4 = { name: "Bada" }, r5 = i3.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/tizen/i], describe: function(e4) {
          var t4 = { name: "Tizen" }, r5 = i3.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/qupzilla/i], describe: function(e4) {
          var t4 = { name: "QupZilla" }, r5 = i3.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/firefox|iceweasel|fxios/i], describe: function(e4) {
          var t4 = { name: "Firefox" }, r5 = i3.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/electron/i], describe: function(e4) {
          var t4 = { name: "Electron" }, r5 = i3.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/MiuiBrowser/i], describe: function(e4) {
          var t4 = { name: "Miui" }, r5 = i3.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/chromium/i], describe: function(e4) {
          var t4 = { name: "Chromium" }, r5 = i3.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, e4) || i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/chrome|crios|crmo/i], describe: function(e4) {
          var t4 = { name: "Chrome" }, r5 = i3.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/GSA/i], describe: function(e4) {
          var t4 = { name: "Google Search" }, r5 = i3.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: function(e4) {
          var t4 = !e4.test(/like android/i), r5 = e4.test(/android/i);
          return t4 && r5;
        }, describe: function(e4) {
          var t4 = { name: "Android Browser" }, r5 = i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/playstation 4/i], describe: function(e4) {
          var t4 = { name: "PlayStation 4" }, r5 = i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/safari|applewebkit/i], describe: function(e4) {
          var t4 = { name: "Safari" }, r5 = i3.default.getFirstMatch(s4, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/.*/i], describe: function(e4) {
          var t4 = -1 !== e4.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /;
          return { name: i3.default.getFirstMatch(t4, e4), version: i3.default.getSecondMatch(t4, e4) };
        } }];
        t3.default = a3, e3.exports = t3.default;
      }, 93: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4, i3 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
        var a3 = [{ test: [/Roku\/DVP/], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, e4);
          return { name: s4.OS_MAP.Roku, version: t4 };
        } }, { test: [/windows phone/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, e4);
          return { name: s4.OS_MAP.WindowsPhone, version: t4 };
        } }, { test: [/windows /i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, e4), r5 = i3.default.getWindowsVersionName(t4);
          return { name: s4.OS_MAP.Windows, version: t4, versionName: r5 };
        } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function(e4) {
          var t4 = { name: s4.OS_MAP.iOS }, r5 = i3.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/macintosh/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, e4).replace(/[_\s]/g, "."), r5 = i3.default.getMacOSVersionName(t4), n5 = { name: s4.OS_MAP.MacOS, version: t4 };
          return r5 && (n5.versionName = r5), n5;
        } }, { test: [/(ipod|iphone|ipad)/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, e4).replace(/[_\s]/g, ".");
          return { name: s4.OS_MAP.iOS, version: t4 };
        } }, { test: function(e4) {
          var t4 = !e4.test(/like android/i), r5 = e4.test(/android/i);
          return t4 && r5;
        }, describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, e4), r5 = i3.default.getAndroidVersionName(t4), n5 = { name: s4.OS_MAP.Android, version: t4 };
          return r5 && (n5.versionName = r5), n5;
        } }, { test: [/(web|hpw)[o0]s/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, e4), r5 = { name: s4.OS_MAP.WebOS };
          return t4 && t4.length && (r5.version = t4), r5;
        } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, e4) || i3.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, e4) || i3.default.getFirstMatch(/\bbb(\d+)/i, e4);
          return { name: s4.OS_MAP.BlackBerry, version: t4 };
        } }, { test: [/bada/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, e4);
          return { name: s4.OS_MAP.Bada, version: t4 };
        } }, { test: [/tizen/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, e4);
          return { name: s4.OS_MAP.Tizen, version: t4 };
        } }, { test: [/linux/i], describe: function() {
          return { name: s4.OS_MAP.Linux };
        } }, { test: [/CrOS/], describe: function() {
          return { name: s4.OS_MAP.ChromeOS };
        } }, { test: [/PlayStation 4/], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, e4);
          return { name: s4.OS_MAP.PlayStation4, version: t4 };
        } }];
        t3.default = a3, e3.exports = t3.default;
      }, 94: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4, i3 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
        var a3 = [{ test: [/googlebot/i], describe: function() {
          return { type: "bot", vendor: "Google" };
        } }, { test: [/huawei/i], describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/(can-l01)/i, e4) && "Nova", r5 = { type: s4.PLATFORMS_MAP.mobile, vendor: "Huawei" };
          return t4 && (r5.model = t4), r5;
        } }, { test: [/nexus\s*(?:7|8|9|10).*/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet, vendor: "Nexus" };
        } }, { test: [/ipad/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
        } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
        } }, { test: [/kftt build/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet, vendor: "Amazon", model: "Kindle Fire HD 7" };
        } }, { test: [/silk/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet, vendor: "Amazon" };
        } }, { test: [/tablet(?! pc)/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet };
        } }, { test: function(e4) {
          var t4 = e4.test(/ipod|iphone/i), r5 = e4.test(/like (ipod|iphone)/i);
          return t4 && !r5;
        }, describe: function(e4) {
          var t4 = i3.default.getFirstMatch(/(ipod|iphone)/i, e4);
          return { type: s4.PLATFORMS_MAP.mobile, vendor: "Apple", model: t4 };
        } }, { test: [/nexus\s*[0-6].*/i, /galaxy nexus/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile, vendor: "Nexus" };
        } }, { test: [/[^-]mobi/i], describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile };
        } }, { test: function(e4) {
          return "blackberry" === e4.getBrowserName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile, vendor: "BlackBerry" };
        } }, { test: function(e4) {
          return "bada" === e4.getBrowserName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile };
        } }, { test: function(e4) {
          return "windows phone" === e4.getBrowserName();
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile, vendor: "Microsoft" };
        } }, { test: function(e4) {
          var t4 = Number(String(e4.getOSVersion()).split(".")[0]);
          return "android" === e4.getOSName(true) && t4 >= 3;
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.tablet };
        } }, { test: function(e4) {
          return "android" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.mobile };
        } }, { test: function(e4) {
          return "macos" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.desktop, vendor: "Apple" };
        } }, { test: function(e4) {
          return "windows" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.desktop };
        } }, { test: function(e4) {
          return "linux" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.desktop };
        } }, { test: function(e4) {
          return "playstation 4" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.tv };
        } }, { test: function(e4) {
          return "roku" === e4.getOSName(true);
        }, describe: function() {
          return { type: s4.PLATFORMS_MAP.tv };
        } }];
        t3.default = a3, e3.exports = t3.default;
      }, 95: function(e3, t3, r4) {
        "use strict";
        t3.__esModule = true, t3.default = void 0;
        var n4, i3 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
        var a3 = [{ test: function(e4) {
          return "microsoft edge" === e4.getBrowserName(true);
        }, describe: function(e4) {
          if (/\sedg\//i.test(e4))
            return { name: s4.ENGINE_MAP.Blink };
          var t4 = i3.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, e4);
          return { name: s4.ENGINE_MAP.EdgeHTML, version: t4 };
        } }, { test: [/trident/i], describe: function(e4) {
          var t4 = { name: s4.ENGINE_MAP.Trident }, r5 = i3.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: function(e4) {
          return e4.test(/presto/i);
        }, describe: function(e4) {
          var t4 = { name: s4.ENGINE_MAP.Presto }, r5 = i3.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: function(e4) {
          var t4 = e4.test(/gecko/i), r5 = e4.test(/like gecko/i);
          return t4 && !r5;
        }, describe: function(e4) {
          var t4 = { name: s4.ENGINE_MAP.Gecko }, r5 = i3.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }, { test: [/(apple)?webkit\/537\.36/i], describe: function() {
          return { name: s4.ENGINE_MAP.Blink };
        } }, { test: [/(apple)?webkit/i], describe: function(e4) {
          var t4 = { name: s4.ENGINE_MAP.WebKit }, r5 = i3.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, e4);
          return r5 && (t4.version = r5), t4;
        } }];
        t3.default = a3, e3.exports = t3.default;
      } });
    });
  }
});

// node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js
var import_bowser, defaultUserAgent;
var init_dist_es45 = __esm({
  "node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js"() {
    import_bowser = __toESM(require_es5());
    defaultUserAgent = ({ serviceId, clientVersion }) => async () => {
      const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser.default.parse(window.navigator.userAgent) : void 0;
      const sections = [
        ["aws-sdk-js", clientVersion],
        ["ua", "2.0"],
        [`os/${parsedUA?.os?.name || "other"}`, parsedUA?.os?.version],
        ["lang/js"],
        ["md/browser", `${parsedUA?.browser?.name ?? "unknown"}_${parsedUA?.browser?.version ?? "unknown"}`]
      ];
      if (serviceId) {
        sections.push([`api/${serviceId}`, clientVersion]);
      }
      return sections;
    };
  }
});

// node_modules/@smithy/invalid-dependency/dist-es/invalidFunction.js
var init_invalidFunction = __esm({
  "node_modules/@smithy/invalid-dependency/dist-es/invalidFunction.js"() {
  }
});

// node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js
var invalidProvider;
var init_invalidProvider = __esm({
  "node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js"() {
    invalidProvider = (message) => () => Promise.reject(message);
  }
});

// node_modules/@smithy/invalid-dependency/dist-es/index.js
var init_dist_es46 = __esm({
  "node_modules/@smithy/invalid-dependency/dist-es/index.js"() {
    init_invalidFunction();
    init_invalidProvider();
  }
});

// node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js
var TEXT_ENCODER, calculateBodyLength;
var init_calculateBodyLength = __esm({
  "node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js"() {
    TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null;
    calculateBodyLength = (body) => {
      if (typeof body === "string") {
        if (TEXT_ENCODER) {
          return TEXT_ENCODER.encode(body).byteLength;
        }
        let len = body.length;
        for (let i3 = len - 1; i3 >= 0; i3--) {
          const code = body.charCodeAt(i3);
          if (code > 127 && code <= 2047)
            len++;
          else if (code > 2047 && code <= 65535)
            len += 2;
          if (code >= 56320 && code <= 57343)
            i3--;
        }
        return len;
      } else if (typeof body.byteLength === "number") {
        return body.byteLength;
      } else if (typeof body.size === "number") {
        return body.size;
      }
      throw new Error(`Body Length computation failed for ${body}`);
    };
  }
});

// node_modules/@smithy/util-body-length-browser/dist-es/index.js
var init_dist_es47 = __esm({
  "node_modules/@smithy/util-body-length-browser/dist-es/index.js"() {
    init_calculateBodyLength();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
var fromUtf84;
var init_fromUtf8_browser4 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() {
    fromUtf84 = (input) => new TextEncoder().encode(input);
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var init_toUint8Array4 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    init_fromUtf8_browser4();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
var toUtf82;
var init_toUtf8_browser4 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() {
    toUtf82 = (input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return new TextDecoder("utf-8").decode(input);
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es48 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    init_fromUtf8_browser4();
    init_toUint8Array4();
    init_toUtf8_browser4();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/ruleset.js
var s, t, u, v, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r2, _data, ruleSet;
var init_ruleset = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/ruleset.js"() {
    s = "required";
    t = "fn";
    u = "argv";
    v = "ref";
    a = true;
    b = "isSet";
    c = "booleanEquals";
    d = "error";
    e = "endpoint";
    f = "tree";
    g = "PartitionResult";
    h = { [s]: false, "type": "String" };
    i = { [s]: true, "default": false, "type": "Boolean" };
    j = { [v]: "Endpoint" };
    k = { [t]: c, [u]: [{ [v]: "UseFIPS" }, true] };
    l = { [t]: c, [u]: [{ [v]: "UseDualStack" }, true] };
    m = {};
    n = { [t]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] };
    o = { [t]: c, [u]: [true, { [t]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] };
    p = [k];
    q = [l];
    r2 = [{ [v]: "Region" }];
    _data = { version: "1.0", parameters: { Region: h, UseDualStack: i, UseFIPS: i, Endpoint: h }, rules: [{ conditions: [{ [t]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }, { conditions: [{ [t]: b, [u]: r2 }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r2, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c, [u]: [a, n] }, o], rules: [{ endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c, [u]: [n, a] }], rules: [{ endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] };
    ruleSet = _data;
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/endpointResolver.js
var defaultEndpointResolver;
var init_endpointResolver = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/endpointResolver.js"() {
    init_dist_es9();
    init_dist_es8();
    init_ruleset();
    defaultEndpointResolver = (endpointParams, context = {}) => {
      return resolveEndpoint(ruleSet, {
        endpointParams,
        logger: context.logger
      });
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.shared.js
var getRuntimeConfig;
var init_runtimeConfig_shared = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.shared.js"() {
    init_dist_es43();
    init_dist_es35();
    init_dist_es33();
    init_dist_es16();
    init_dist_es25();
    init_dist_es48();
    init_httpAuthSchemeProvider();
    init_endpointResolver();
    getRuntimeConfig = (config) => {
      return {
        apiVersion: "2014-06-30",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "Cognito Identity",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf84,
        utf8Encoder: config?.utf8Encoder ?? toUtf82
      };
    };
  }
});

// node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js
var DEFAULTS_MODE_OPTIONS;
var init_constants8 = __esm({
  "node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js"() {
    DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
  }
});

// node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js
var import_bowser2, resolveDefaultsModeConfig, isMobileBrowser;
var init_resolveDefaultsModeConfig = __esm({
  "node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js"() {
    init_dist_es();
    import_bowser2 = __toESM(require_es5());
    init_constants8();
    resolveDefaultsModeConfig = ({ defaultsMode } = {}) => memoize(async () => {
      const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
      switch (mode?.toLowerCase()) {
        case "auto":
          return Promise.resolve(isMobileBrowser() ? "mobile" : "standard");
        case "mobile":
        case "in-region":
        case "cross-region":
        case "standard":
        case "legacy":
          return Promise.resolve(mode?.toLocaleLowerCase());
        case void 0:
          return Promise.resolve("legacy");
        default:
          throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
      }
    });
    isMobileBrowser = () => {
      const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser2.default.parse(window.navigator.userAgent) : void 0;
      const platform2 = parsedUA?.platform?.type;
      return platform2 === "tablet" || platform2 === "mobile";
    };
  }
});

// node_modules/@smithy/util-defaults-mode-browser/dist-es/index.js
var init_dist_es49 = __esm({
  "node_modules/@smithy/util-defaults-mode-browser/dist-es/index.js"() {
    init_resolveDefaultsModeConfig();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.browser.js
var getRuntimeConfig2;
var init_runtimeConfig_browser = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.browser.js"() {
    init_package();
    init_module2();
    init_dist_es45();
    init_dist_es14();
    init_dist_es30();
    init_dist_es46();
    init_dist_es47();
    init_dist_es21();
    init_runtimeConfig_shared();
    init_dist_es33();
    init_dist_es49();
    getRuntimeConfig2 = (config) => {
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig(config);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "browser",
        defaultsMode,
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        credentialDefaultProvider: config?.credentialDefaultProvider ?? ((_2) => () => Promise.reject(new Error("Credential is missing"))),
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? defaultUserAgent({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
        maxAttempts: config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
        region: config?.region ?? invalidProvider("Region is missing"),
        requestHandler: FetchHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? (async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE),
        sha256: config?.sha256 ?? Sha2562,
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)),
        useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))
      };
    };
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js
var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration;
var init_extensions11 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() {
    getAwsRegionExtensionConfiguration = (runtimeConfig) => {
      let runtimeConfigRegion = async () => {
        if (runtimeConfig.region === void 0) {
          throw new Error("Region is missing from runtimeConfig");
        }
        const region = runtimeConfig.region;
        if (typeof region === "string") {
          return region;
        }
        return region();
      };
      return {
        setRegion(region) {
          runtimeConfigRegion = region;
        },
        region() {
          return runtimeConfigRegion;
        }
      };
    };
    resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
      return {
        region: awsRegionExtensionConfiguration.region()
      };
    };
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js
var init_config5 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js"() {
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js
var init_isFipsRegion2 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/isFipsRegion.js"() {
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js
var init_getRealRegion2 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/getRealRegion.js"() {
    init_isFipsRegion2();
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js
var init_resolveRegionConfig2 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() {
    init_getRealRegion2();
    init_isFipsRegion2();
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js
var init_regionConfig2 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js"() {
    init_config5();
    init_resolveRegionConfig2();
  }
});

// node_modules/@aws-sdk/region-config-resolver/dist-es/index.js
var init_dist_es50 = __esm({
  "node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() {
    init_extensions11();
    init_regionConfig2();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig;
var init_httpExtensionConfiguration9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
    getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
      let httpHandler = runtimeConfig.httpHandler;
      return {
        setHttpHandler(handler) {
          httpHandler = handler;
        },
        httpHandler() {
          return httpHandler;
        },
        updateHttpClientConfig(key, value) {
          httpHandler.updateHttpClientConfig(key, value);
        },
        httpHandlerConfigs() {
          return httpHandler.httpHandlerConfigs();
        }
      };
    };
    resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
      return {
        httpHandler: httpHandlerExtensionConfiguration.httpHandler()
      };
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions12 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration9();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery8(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest8;
var init_httpRequest9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest8 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest8({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery8(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest8.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname9 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types15 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es51 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions12();
    init_Field9();
    init_Fields9();
    init_httpHandler9();
    init_httpRequest9();
    init_httpResponse9();
    init_isValidHostname9();
    init_types15();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
var init_httpAuthExtensionConfiguration = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthExtensionConfiguration.js"() {
    getHttpAuthExtensionConfiguration = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index2 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials) {
          _credentials = credentials;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeExtensions.js
var asPartial, resolveRuntimeExtensions;
var init_runtimeExtensions = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeExtensions.js"() {
    init_dist_es50();
    init_dist_es51();
    init_dist_es33();
    init_httpAuthExtensionConfiguration();
    asPartial = (t3) => t3;
    resolveRuntimeExtensions = (runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial(getAwsRegionExtensionConfiguration(runtimeConfig)),
        ...asPartial(getDefaultExtensionConfiguration(runtimeConfig)),
        ...asPartial(getHttpHandlerExtensionConfiguration(runtimeConfig)),
        ...asPartial(getHttpAuthExtensionConfiguration(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
        ...resolveDefaultRuntimeConfig(extensionConfiguration),
        ...resolveHttpHandlerRuntimeConfig(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig(extensionConfiguration)
      };
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentityClient.js
var CognitoIdentityClient;
var init_CognitoIdentityClient = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentityClient.js"() {
    init_dist_es4();
    init_dist_es5();
    init_dist_es7();
    init_dist_es11();
    init_dist_es14();
    init_dist_es35();
    init_dist_es37();
    init_dist_es18();
    init_dist_es34();
    init_dist_es33();
    init_httpAuthSchemeProvider();
    init_EndpointParameters();
    init_runtimeConfig_browser();
    init_runtimeExtensions();
    CognitoIdentityClient = class extends Client2 {
      constructor(...[configuration2]) {
        const _config_0 = getRuntimeConfig2(configuration2 || {});
        const _config_1 = resolveClientEndpointParameters(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
        const _config_8 = resolveRuntimeExtensions(_config_7, configuration2?.extensions || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/models/CognitoIdentityServiceException.js
var CognitoIdentityServiceException;
var init_CognitoIdentityServiceException = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/CognitoIdentityServiceException.js"() {
    init_dist_es33();
    CognitoIdentityServiceException = class extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype);
      }
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/models/models_0.js
var InternalErrorException, InvalidParameterException, LimitExceededException, NotAuthorizedException, ResourceConflictException, TooManyRequestsException, ResourceNotFoundException, ExternalServiceException, InvalidIdentityPoolConfigurationException, DeveloperUserAlreadyRegisteredException, ConcurrentModificationException;
var init_models_0 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/models_0.js"() {
    init_CognitoIdentityServiceException();
    InternalErrorException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "InternalErrorException",
          $fault: "server",
          ...opts
        });
        this.name = "InternalErrorException";
        this.$fault = "server";
        Object.setPrototypeOf(this, InternalErrorException.prototype);
      }
    };
    InvalidParameterException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "InvalidParameterException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidParameterException";
        this.$fault = "client";
        Object.setPrototypeOf(this, InvalidParameterException.prototype);
      }
    };
    LimitExceededException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "LimitExceededException",
          $fault: "client",
          ...opts
        });
        this.name = "LimitExceededException";
        this.$fault = "client";
        Object.setPrototypeOf(this, LimitExceededException.prototype);
      }
    };
    NotAuthorizedException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "NotAuthorizedException",
          $fault: "client",
          ...opts
        });
        this.name = "NotAuthorizedException";
        this.$fault = "client";
        Object.setPrototypeOf(this, NotAuthorizedException.prototype);
      }
    };
    ResourceConflictException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "ResourceConflictException",
          $fault: "client",
          ...opts
        });
        this.name = "ResourceConflictException";
        this.$fault = "client";
        Object.setPrototypeOf(this, ResourceConflictException.prototype);
      }
    };
    TooManyRequestsException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "TooManyRequestsException",
          $fault: "client",
          ...opts
        });
        this.name = "TooManyRequestsException";
        this.$fault = "client";
        Object.setPrototypeOf(this, TooManyRequestsException.prototype);
      }
    };
    ResourceNotFoundException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "ResourceNotFoundException",
          $fault: "client",
          ...opts
        });
        this.name = "ResourceNotFoundException";
        this.$fault = "client";
        Object.setPrototypeOf(this, ResourceNotFoundException.prototype);
      }
    };
    ExternalServiceException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "ExternalServiceException",
          $fault: "client",
          ...opts
        });
        this.name = "ExternalServiceException";
        this.$fault = "client";
        Object.setPrototypeOf(this, ExternalServiceException.prototype);
      }
    };
    InvalidIdentityPoolConfigurationException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "InvalidIdentityPoolConfigurationException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidIdentityPoolConfigurationException";
        this.$fault = "client";
        Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype);
      }
    };
    DeveloperUserAlreadyRegisteredException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "DeveloperUserAlreadyRegisteredException",
          $fault: "client",
          ...opts
        });
        this.name = "DeveloperUserAlreadyRegisteredException";
        this.$fault = "client";
        Object.setPrototypeOf(this, DeveloperUserAlreadyRegisteredException.prototype);
      }
    };
    ConcurrentModificationException = class extends CognitoIdentityServiceException {
      constructor(opts) {
        super({
          name: "ConcurrentModificationException",
          $fault: "client",
          ...opts
        });
        this.name = "ConcurrentModificationException";
        this.$fault = "client";
        Object.setPrototypeOf(this, ConcurrentModificationException.prototype);
      }
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/protocols/Aws_json1_1.js
function sharedHeaders(operation) {
  return {
    "content-type": "application/x-amz-json-1.1",
    "x-amz-target": `AWSCognitoIdentityService.${operation}`
  };
}
var se_CreateIdentityPoolCommand, se_DeleteIdentitiesCommand, se_DeleteIdentityPoolCommand, se_DescribeIdentityCommand, se_DescribeIdentityPoolCommand, se_GetCredentialsForIdentityCommand, se_GetIdCommand, se_GetIdentityPoolRolesCommand, se_GetOpenIdTokenCommand, se_GetOpenIdTokenForDeveloperIdentityCommand, se_GetPrincipalTagAttributeMapCommand, se_ListIdentitiesCommand, se_ListIdentityPoolsCommand, se_ListTagsForResourceCommand, se_LookupDeveloperIdentityCommand, se_MergeDeveloperIdentitiesCommand, se_SetIdentityPoolRolesCommand, se_SetPrincipalTagAttributeMapCommand, se_TagResourceCommand, se_UnlinkDeveloperIdentityCommand, se_UnlinkIdentityCommand, se_UntagResourceCommand, se_UpdateIdentityPoolCommand, de_CreateIdentityPoolCommand, de_DeleteIdentitiesCommand, de_DeleteIdentityPoolCommand, de_DescribeIdentityCommand, de_DescribeIdentityPoolCommand, de_GetCredentialsForIdentityCommand, de_GetIdCommand, de_GetIdentityPoolRolesCommand, de_GetOpenIdTokenCommand, de_GetOpenIdTokenForDeveloperIdentityCommand, de_GetPrincipalTagAttributeMapCommand, de_ListIdentitiesCommand, de_ListIdentityPoolsCommand, de_ListTagsForResourceCommand, de_LookupDeveloperIdentityCommand, de_MergeDeveloperIdentitiesCommand, de_SetIdentityPoolRolesCommand, de_SetPrincipalTagAttributeMapCommand, de_TagResourceCommand, de_UnlinkDeveloperIdentityCommand, de_UnlinkIdentityCommand, de_UntagResourceCommand, de_UpdateIdentityPoolCommand, de_CommandError, de_ConcurrentModificationExceptionRes, de_DeveloperUserAlreadyRegisteredExceptionRes, de_ExternalServiceExceptionRes, de_InternalErrorExceptionRes, de_InvalidIdentityPoolConfigurationExceptionRes, de_InvalidParameterExceptionRes, de_LimitExceededExceptionRes, de_NotAuthorizedExceptionRes, de_ResourceConflictExceptionRes, de_ResourceNotFoundExceptionRes, de_TooManyRequestsExceptionRes, de_Credentials, de_GetCredentialsForIdentityResponse, de_IdentitiesList, de_IdentityDescription, de_ListIdentitiesResponse, deserializeMetadata2, throwDefaultError2, buildHttpRpcRequest;
var init_Aws_json1_1 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/protocols/Aws_json1_1.js"() {
    init_dist_es43();
    init_dist_es51();
    init_dist_es33();
    init_CognitoIdentityServiceException();
    init_models_0();
    se_CreateIdentityPoolCommand = async (input, context) => {
      const headers = sharedHeaders("CreateIdentityPool");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_DeleteIdentitiesCommand = async (input, context) => {
      const headers = sharedHeaders("DeleteIdentities");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_DeleteIdentityPoolCommand = async (input, context) => {
      const headers = sharedHeaders("DeleteIdentityPool");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_DescribeIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("DescribeIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_DescribeIdentityPoolCommand = async (input, context) => {
      const headers = sharedHeaders("DescribeIdentityPool");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetCredentialsForIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("GetCredentialsForIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetIdCommand = async (input, context) => {
      const headers = sharedHeaders("GetId");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetIdentityPoolRolesCommand = async (input, context) => {
      const headers = sharedHeaders("GetIdentityPoolRoles");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetOpenIdTokenCommand = async (input, context) => {
      const headers = sharedHeaders("GetOpenIdToken");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetOpenIdTokenForDeveloperIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("GetOpenIdTokenForDeveloperIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_GetPrincipalTagAttributeMapCommand = async (input, context) => {
      const headers = sharedHeaders("GetPrincipalTagAttributeMap");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_ListIdentitiesCommand = async (input, context) => {
      const headers = sharedHeaders("ListIdentities");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_ListIdentityPoolsCommand = async (input, context) => {
      const headers = sharedHeaders("ListIdentityPools");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_ListTagsForResourceCommand = async (input, context) => {
      const headers = sharedHeaders("ListTagsForResource");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_LookupDeveloperIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("LookupDeveloperIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_MergeDeveloperIdentitiesCommand = async (input, context) => {
      const headers = sharedHeaders("MergeDeveloperIdentities");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_SetIdentityPoolRolesCommand = async (input, context) => {
      const headers = sharedHeaders("SetIdentityPoolRoles");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_SetPrincipalTagAttributeMapCommand = async (input, context) => {
      const headers = sharedHeaders("SetPrincipalTagAttributeMap");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_TagResourceCommand = async (input, context) => {
      const headers = sharedHeaders("TagResource");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_UnlinkDeveloperIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("UnlinkDeveloperIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_UnlinkIdentityCommand = async (input, context) => {
      const headers = sharedHeaders("UnlinkIdentity");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_UntagResourceCommand = async (input, context) => {
      const headers = sharedHeaders("UntagResource");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    se_UpdateIdentityPoolCommand = async (input, context) => {
      const headers = sharedHeaders("UpdateIdentityPool");
      let body;
      body = JSON.stringify(_json(input));
      return buildHttpRpcRequest(context, headers, "/", void 0, body);
    };
    de_CreateIdentityPoolCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_DeleteIdentitiesCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_DeleteIdentityPoolCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      await collectBody(output.body, context);
      const response = {
        $metadata: deserializeMetadata2(output)
      };
      return response;
    };
    de_DescribeIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = de_IdentityDescription(data, context);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_DescribeIdentityPoolCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetCredentialsForIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = de_GetCredentialsForIdentityResponse(data, context);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetIdCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetIdentityPoolRolesCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetOpenIdTokenCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetOpenIdTokenForDeveloperIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_GetPrincipalTagAttributeMapCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_ListIdentitiesCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = de_ListIdentitiesResponse(data, context);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_ListIdentityPoolsCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_ListTagsForResourceCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_LookupDeveloperIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_MergeDeveloperIdentitiesCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_SetIdentityPoolRolesCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      await collectBody(output.body, context);
      const response = {
        $metadata: deserializeMetadata2(output)
      };
      return response;
    };
    de_SetPrincipalTagAttributeMapCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_TagResourceCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_UnlinkDeveloperIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      await collectBody(output.body, context);
      const response = {
        $metadata: deserializeMetadata2(output)
      };
      return response;
    };
    de_UnlinkIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      await collectBody(output.body, context);
      const response = {
        $metadata: deserializeMetadata2(output)
      };
      return response;
    };
    de_UntagResourceCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_UpdateIdentityPoolCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError(output, context);
      }
      const data = await parseJsonBody(output.body, context);
      let contents = {};
      contents = _json(data);
      const response = {
        $metadata: deserializeMetadata2(output),
        ...contents
      };
      return response;
    };
    de_CommandError = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseJsonErrorBody(output.body, context)
      };
      const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "InternalErrorException":
        case "com.amazonaws.cognitoidentity#InternalErrorException":
          throw await de_InternalErrorExceptionRes(parsedOutput, context);
        case "InvalidParameterException":
        case "com.amazonaws.cognitoidentity#InvalidParameterException":
          throw await de_InvalidParameterExceptionRes(parsedOutput, context);
        case "LimitExceededException":
        case "com.amazonaws.cognitoidentity#LimitExceededException":
          throw await de_LimitExceededExceptionRes(parsedOutput, context);
        case "NotAuthorizedException":
        case "com.amazonaws.cognitoidentity#NotAuthorizedException":
          throw await de_NotAuthorizedExceptionRes(parsedOutput, context);
        case "ResourceConflictException":
        case "com.amazonaws.cognitoidentity#ResourceConflictException":
          throw await de_ResourceConflictExceptionRes(parsedOutput, context);
        case "TooManyRequestsException":
        case "com.amazonaws.cognitoidentity#TooManyRequestsException":
          throw await de_TooManyRequestsExceptionRes(parsedOutput, context);
        case "ResourceNotFoundException":
        case "com.amazonaws.cognitoidentity#ResourceNotFoundException":
          throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
        case "ExternalServiceException":
        case "com.amazonaws.cognitoidentity#ExternalServiceException":
          throw await de_ExternalServiceExceptionRes(parsedOutput, context);
        case "InvalidIdentityPoolConfigurationException":
        case "com.amazonaws.cognitoidentity#InvalidIdentityPoolConfigurationException":
          throw await de_InvalidIdentityPoolConfigurationExceptionRes(parsedOutput, context);
        case "DeveloperUserAlreadyRegisteredException":
        case "com.amazonaws.cognitoidentity#DeveloperUserAlreadyRegisteredException":
          throw await de_DeveloperUserAlreadyRegisteredExceptionRes(parsedOutput, context);
        case "ConcurrentModificationException":
        case "com.amazonaws.cognitoidentity#ConcurrentModificationException":
          throw await de_ConcurrentModificationExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError2({
            output,
            parsedBody,
            errorCode
          });
      }
    };
    de_ConcurrentModificationExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new ConcurrentModificationException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_DeveloperUserAlreadyRegisteredExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new DeveloperUserAlreadyRegisteredException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_ExternalServiceExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new ExternalServiceException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InternalErrorExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new InternalErrorException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InvalidIdentityPoolConfigurationExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new InvalidIdentityPoolConfigurationException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InvalidParameterExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new InvalidParameterException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_LimitExceededExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new LimitExceededException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_NotAuthorizedExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new NotAuthorizedException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_ResourceConflictExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new ResourceConflictException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new ResourceNotFoundException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_TooManyRequestsExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = _json(body);
      const exception = new TooManyRequestsException({
        $metadata: deserializeMetadata2(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_Credentials = (output, context) => {
      return take(output, {
        AccessKeyId: expectString,
        Expiration: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))),
        SecretKey: expectString,
        SessionToken: expectString
      });
    };
    de_GetCredentialsForIdentityResponse = (output, context) => {
      return take(output, {
        Credentials: (_2) => de_Credentials(_2, context),
        IdentityId: expectString
      });
    };
    de_IdentitiesList = (output, context) => {
      const retVal = (output || []).filter((e3) => e3 != null).map((entry) => {
        return de_IdentityDescription(entry, context);
      });
      return retVal;
    };
    de_IdentityDescription = (output, context) => {
      return take(output, {
        CreationDate: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))),
        IdentityId: expectString,
        LastModifiedDate: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))),
        Logins: _json
      });
    };
    de_ListIdentitiesResponse = (output, context) => {
      return take(output, {
        Identities: (_2) => de_IdentitiesList(_2, context),
        IdentityPoolId: expectString,
        NextToken: expectString
      });
    };
    deserializeMetadata2 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
    throwDefaultError2 = withBaseException(CognitoIdentityServiceException);
    buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => {
      const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
      const contents = {
        protocol,
        hostname,
        port,
        method: "POST",
        path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path,
        headers
      };
      if (resolvedHostname !== void 0) {
        contents.hostname = resolvedHostname;
      }
      if (body !== void 0) {
        contents.body = body;
      }
      return new HttpRequest8(contents);
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/CreateIdentityPoolCommand.js
var CreateIdentityPoolCommand;
var init_CreateIdentityPoolCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/CreateIdentityPoolCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    CreateIdentityPoolCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "CreateIdentityPool", {}).n("CognitoIdentityClient", "CreateIdentityPoolCommand").f(void 0, void 0).ser(se_CreateIdentityPoolCommand).de(de_CreateIdentityPoolCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentitiesCommand.js
var DeleteIdentitiesCommand;
var init_DeleteIdentitiesCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentitiesCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    DeleteIdentitiesCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "DeleteIdentities", {}).n("CognitoIdentityClient", "DeleteIdentitiesCommand").f(void 0, void 0).ser(se_DeleteIdentitiesCommand).de(de_DeleteIdentitiesCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentityPoolCommand.js
var DeleteIdentityPoolCommand;
var init_DeleteIdentityPoolCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentityPoolCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    DeleteIdentityPoolCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "DeleteIdentityPool", {}).n("CognitoIdentityClient", "DeleteIdentityPoolCommand").f(void 0, void 0).ser(se_DeleteIdentityPoolCommand).de(de_DeleteIdentityPoolCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityCommand.js
var DescribeIdentityCommand;
var init_DescribeIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    DescribeIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "DescribeIdentity", {}).n("CognitoIdentityClient", "DescribeIdentityCommand").f(void 0, void 0).ser(se_DescribeIdentityCommand).de(de_DescribeIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityPoolCommand.js
var DescribeIdentityPoolCommand;
var init_DescribeIdentityPoolCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityPoolCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    DescribeIdentityPoolCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "DescribeIdentityPool", {}).n("CognitoIdentityClient", "DescribeIdentityPoolCommand").f(void 0, void 0).ser(se_DescribeIdentityPoolCommand).de(de_DescribeIdentityPoolCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetCredentialsForIdentityCommand.js
var GetCredentialsForIdentityCommand;
var init_GetCredentialsForIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetCredentialsForIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetCredentialsForIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetCredentialsForIdentity", {}).n("CognitoIdentityClient", "GetCredentialsForIdentityCommand").f(void 0, void 0).ser(se_GetCredentialsForIdentityCommand).de(de_GetCredentialsForIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdCommand.js
var GetIdCommand;
var init_GetIdCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetIdCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetId", {}).n("CognitoIdentityClient", "GetIdCommand").f(void 0, void 0).ser(se_GetIdCommand).de(de_GetIdCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdentityPoolRolesCommand.js
var GetIdentityPoolRolesCommand;
var init_GetIdentityPoolRolesCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdentityPoolRolesCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetIdentityPoolRolesCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetIdentityPoolRoles", {}).n("CognitoIdentityClient", "GetIdentityPoolRolesCommand").f(void 0, void 0).ser(se_GetIdentityPoolRolesCommand).de(de_GetIdentityPoolRolesCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenCommand.js
var GetOpenIdTokenCommand;
var init_GetOpenIdTokenCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetOpenIdTokenCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetOpenIdToken", {}).n("CognitoIdentityClient", "GetOpenIdTokenCommand").f(void 0, void 0).ser(se_GetOpenIdTokenCommand).de(de_GetOpenIdTokenCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenForDeveloperIdentityCommand.js
var GetOpenIdTokenForDeveloperIdentityCommand;
var init_GetOpenIdTokenForDeveloperIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenForDeveloperIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetOpenIdTokenForDeveloperIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetOpenIdTokenForDeveloperIdentity", {}).n("CognitoIdentityClient", "GetOpenIdTokenForDeveloperIdentityCommand").f(void 0, void 0).ser(se_GetOpenIdTokenForDeveloperIdentityCommand).de(de_GetOpenIdTokenForDeveloperIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetPrincipalTagAttributeMapCommand.js
var GetPrincipalTagAttributeMapCommand;
var init_GetPrincipalTagAttributeMapCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetPrincipalTagAttributeMapCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    GetPrincipalTagAttributeMapCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "GetPrincipalTagAttributeMap", {}).n("CognitoIdentityClient", "GetPrincipalTagAttributeMapCommand").f(void 0, void 0).ser(se_GetPrincipalTagAttributeMapCommand).de(de_GetPrincipalTagAttributeMapCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentitiesCommand.js
var ListIdentitiesCommand;
var init_ListIdentitiesCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentitiesCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    ListIdentitiesCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "ListIdentities", {}).n("CognitoIdentityClient", "ListIdentitiesCommand").f(void 0, void 0).ser(se_ListIdentitiesCommand).de(de_ListIdentitiesCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentityPoolsCommand.js
var ListIdentityPoolsCommand;
var init_ListIdentityPoolsCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentityPoolsCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    ListIdentityPoolsCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "ListIdentityPools", {}).n("CognitoIdentityClient", "ListIdentityPoolsCommand").f(void 0, void 0).ser(se_ListIdentityPoolsCommand).de(de_ListIdentityPoolsCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListTagsForResourceCommand.js
var ListTagsForResourceCommand;
var init_ListTagsForResourceCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListTagsForResourceCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    ListTagsForResourceCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "ListTagsForResource", {}).n("CognitoIdentityClient", "ListTagsForResourceCommand").f(void 0, void 0).ser(se_ListTagsForResourceCommand).de(de_ListTagsForResourceCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/LookupDeveloperIdentityCommand.js
var LookupDeveloperIdentityCommand;
var init_LookupDeveloperIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/LookupDeveloperIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    LookupDeveloperIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "LookupDeveloperIdentity", {}).n("CognitoIdentityClient", "LookupDeveloperIdentityCommand").f(void 0, void 0).ser(se_LookupDeveloperIdentityCommand).de(de_LookupDeveloperIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/MergeDeveloperIdentitiesCommand.js
var MergeDeveloperIdentitiesCommand;
var init_MergeDeveloperIdentitiesCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/MergeDeveloperIdentitiesCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    MergeDeveloperIdentitiesCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "MergeDeveloperIdentities", {}).n("CognitoIdentityClient", "MergeDeveloperIdentitiesCommand").f(void 0, void 0).ser(se_MergeDeveloperIdentitiesCommand).de(de_MergeDeveloperIdentitiesCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetIdentityPoolRolesCommand.js
var SetIdentityPoolRolesCommand;
var init_SetIdentityPoolRolesCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetIdentityPoolRolesCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    SetIdentityPoolRolesCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "SetIdentityPoolRoles", {}).n("CognitoIdentityClient", "SetIdentityPoolRolesCommand").f(void 0, void 0).ser(se_SetIdentityPoolRolesCommand).de(de_SetIdentityPoolRolesCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetPrincipalTagAttributeMapCommand.js
var SetPrincipalTagAttributeMapCommand;
var init_SetPrincipalTagAttributeMapCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetPrincipalTagAttributeMapCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    SetPrincipalTagAttributeMapCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "SetPrincipalTagAttributeMap", {}).n("CognitoIdentityClient", "SetPrincipalTagAttributeMapCommand").f(void 0, void 0).ser(se_SetPrincipalTagAttributeMapCommand).de(de_SetPrincipalTagAttributeMapCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/TagResourceCommand.js
var TagResourceCommand;
var init_TagResourceCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/TagResourceCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    TagResourceCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "TagResource", {}).n("CognitoIdentityClient", "TagResourceCommand").f(void 0, void 0).ser(se_TagResourceCommand).de(de_TagResourceCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkDeveloperIdentityCommand.js
var UnlinkDeveloperIdentityCommand;
var init_UnlinkDeveloperIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkDeveloperIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    UnlinkDeveloperIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "UnlinkDeveloperIdentity", {}).n("CognitoIdentityClient", "UnlinkDeveloperIdentityCommand").f(void 0, void 0).ser(se_UnlinkDeveloperIdentityCommand).de(de_UnlinkDeveloperIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkIdentityCommand.js
var UnlinkIdentityCommand;
var init_UnlinkIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    UnlinkIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "UnlinkIdentity", {}).n("CognitoIdentityClient", "UnlinkIdentityCommand").f(void 0, void 0).ser(se_UnlinkIdentityCommand).de(de_UnlinkIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UntagResourceCommand.js
var UntagResourceCommand;
var init_UntagResourceCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UntagResourceCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    UntagResourceCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "UntagResource", {}).n("CognitoIdentityClient", "UntagResourceCommand").f(void 0, void 0).ser(se_UntagResourceCommand).de(de_UntagResourceCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UpdateIdentityPoolCommand.js
var UpdateIdentityPoolCommand;
var init_UpdateIdentityPoolCommand = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UpdateIdentityPoolCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters();
    init_Aws_json1_1();
    UpdateIdentityPoolCommand = class extends Command2.classBuilder().ep({
      ...commonParams
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSCognitoIdentityService", "UpdateIdentityPool", {}).n("CognitoIdentityClient", "UpdateIdentityPoolCommand").f(void 0, void 0).ser(se_UpdateIdentityPoolCommand).de(de_UpdateIdentityPoolCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentity.js
var commands, CognitoIdentity;
var init_CognitoIdentity = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentity.js"() {
    init_dist_es33();
    init_CognitoIdentityClient();
    init_CreateIdentityPoolCommand();
    init_DeleteIdentitiesCommand();
    init_DeleteIdentityPoolCommand();
    init_DescribeIdentityCommand();
    init_DescribeIdentityPoolCommand();
    init_GetCredentialsForIdentityCommand();
    init_GetIdCommand();
    init_GetIdentityPoolRolesCommand();
    init_GetOpenIdTokenCommand();
    init_GetOpenIdTokenForDeveloperIdentityCommand();
    init_GetPrincipalTagAttributeMapCommand();
    init_ListIdentitiesCommand();
    init_ListIdentityPoolsCommand();
    init_ListTagsForResourceCommand();
    init_LookupDeveloperIdentityCommand();
    init_MergeDeveloperIdentitiesCommand();
    init_SetIdentityPoolRolesCommand();
    init_SetPrincipalTagAttributeMapCommand();
    init_TagResourceCommand();
    init_UnlinkDeveloperIdentityCommand();
    init_UnlinkIdentityCommand();
    init_UntagResourceCommand();
    init_UpdateIdentityPoolCommand();
    commands = {
      CreateIdentityPoolCommand,
      DeleteIdentitiesCommand,
      DeleteIdentityPoolCommand,
      DescribeIdentityCommand,
      DescribeIdentityPoolCommand,
      GetCredentialsForIdentityCommand,
      GetIdCommand,
      GetIdentityPoolRolesCommand,
      GetOpenIdTokenCommand,
      GetOpenIdTokenForDeveloperIdentityCommand,
      GetPrincipalTagAttributeMapCommand,
      ListIdentitiesCommand,
      ListIdentityPoolsCommand,
      ListTagsForResourceCommand,
      LookupDeveloperIdentityCommand,
      MergeDeveloperIdentitiesCommand,
      SetIdentityPoolRolesCommand,
      SetPrincipalTagAttributeMapCommand,
      TagResourceCommand,
      UnlinkDeveloperIdentityCommand,
      UnlinkIdentityCommand,
      UntagResourceCommand,
      UpdateIdentityPoolCommand
    };
    CognitoIdentity = class extends CognitoIdentityClient {
    };
    createAggregatedClient(commands, CognitoIdentity);
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/index.js
var init_commands = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/index.js"() {
    init_CreateIdentityPoolCommand();
    init_DeleteIdentitiesCommand();
    init_DeleteIdentityPoolCommand();
    init_DescribeIdentityCommand();
    init_DescribeIdentityPoolCommand();
    init_GetCredentialsForIdentityCommand();
    init_GetIdCommand();
    init_GetIdentityPoolRolesCommand();
    init_GetOpenIdTokenCommand();
    init_GetOpenIdTokenForDeveloperIdentityCommand();
    init_GetPrincipalTagAttributeMapCommand();
    init_ListIdentitiesCommand();
    init_ListIdentityPoolsCommand();
    init_ListTagsForResourceCommand();
    init_LookupDeveloperIdentityCommand();
    init_MergeDeveloperIdentitiesCommand();
    init_SetIdentityPoolRolesCommand();
    init_SetPrincipalTagAttributeMapCommand();
    init_TagResourceCommand();
    init_UnlinkDeveloperIdentityCommand();
    init_UnlinkIdentityCommand();
    init_UntagResourceCommand();
    init_UpdateIdentityPoolCommand();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/Interfaces.js
var init_Interfaces = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/Interfaces.js"() {
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/ListIdentityPoolsPaginator.js
var paginateListIdentityPools;
var init_ListIdentityPoolsPaginator = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/ListIdentityPoolsPaginator.js"() {
    init_dist_es35();
    init_CognitoIdentityClient();
    init_ListIdentityPoolsCommand();
    paginateListIdentityPools = createPaginator(CognitoIdentityClient, ListIdentityPoolsCommand, "NextToken", "NextToken", "MaxResults");
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/index.js
var init_pagination2 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/index.js"() {
    init_Interfaces();
    init_ListIdentityPoolsPaginator();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/models/index.js
var init_models = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/index.js"() {
    init_models_0();
  }
});

// node_modules/@aws-sdk/client-cognito-identity/dist-es/index.js
var init_dist_es52 = __esm({
  "node_modules/@aws-sdk/client-cognito-identity/dist-es/index.js"() {
    init_CognitoIdentityClient();
    init_CognitoIdentity();
    init_commands();
    init_pagination2();
    init_models();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/loadCognitoIdentity.js
var loadCognitoIdentity_exports = {};
__export(loadCognitoIdentity_exports, {
  CognitoIdentityClient: () => CognitoIdentityClient,
  GetCredentialsForIdentityCommand: () => GetCredentialsForIdentityCommand,
  GetIdCommand: () => GetIdCommand
});
var init_loadCognitoIdentity = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/loadCognitoIdentity.js"() {
    init_dist_es52();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js
function fromCognitoIdentity(parameters) {
  return async () => {
    parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");
    const { GetCredentialsForIdentityCommand: GetCredentialsForIdentityCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), loadCognitoIdentity_exports));
    const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken } = throwOnMissingCredentials(parameters.logger) } = await (parameters.client ?? new CognitoIdentityClient2(Object.assign({}, parameters.clientConfig ?? {}, {
      region: parameters.clientConfig?.region ?? parameters.parentClientConfig?.region
    }))).send(new GetCredentialsForIdentityCommand2({
      CustomRoleArn: parameters.customRoleArn,
      IdentityId: parameters.identityId,
      Logins: parameters.logins ? await resolveLogins(parameters.logins) : void 0
    }));
    return {
      identityId: parameters.identityId,
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretKey,
      sessionToken: SessionToken,
      expiration: Expiration
    };
  };
}
function throwOnMissingAccessKeyId(logger2) {
  throw new CredentialsProviderError("Response from Amazon Cognito contained no access key ID", { logger: logger2 });
}
function throwOnMissingCredentials(logger2) {
  throw new CredentialsProviderError("Response from Amazon Cognito contained no credentials", { logger: logger2 });
}
function throwOnMissingSecretKey(logger2) {
  throw new CredentialsProviderError("Response from Amazon Cognito contained no secret key", { logger: logger2 });
}
var init_fromCognitoIdentity = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js"() {
    init_dist_es();
    init_resolveLogins();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js
var STORE_NAME, IndexedDbStorage;
var init_IndexedDbStorage = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js"() {
    STORE_NAME = "IdentityIds";
    IndexedDbStorage = class {
      constructor(dbName = "aws:cognito-identity-ids") {
        this.dbName = dbName;
      }
      getItem(key) {
        return this.withObjectStore("readonly", (store2) => {
          const req = store2.get(key);
          return new Promise((resolve) => {
            req.onerror = () => resolve(null);
            req.onsuccess = () => resolve(req.result ? req.result.value : null);
          });
        }).catch(() => null);
      }
      removeItem(key) {
        return this.withObjectStore("readwrite", (store2) => {
          const req = store2.delete(key);
          return new Promise((resolve, reject) => {
            req.onerror = () => reject(req.error);
            req.onsuccess = () => resolve();
          });
        });
      }
      setItem(id, value) {
        return this.withObjectStore("readwrite", (store2) => {
          const req = store2.put({ id, value });
          return new Promise((resolve, reject) => {
            req.onerror = () => reject(req.error);
            req.onsuccess = () => resolve();
          });
        });
      }
      getDb() {
        const openDbRequest = self.indexedDB.open(this.dbName, 1);
        return new Promise((resolve, reject) => {
          openDbRequest.onsuccess = () => {
            resolve(openDbRequest.result);
          };
          openDbRequest.onerror = () => {
            reject(openDbRequest.error);
          };
          openDbRequest.onblocked = () => {
            reject(new Error("Unable to access DB"));
          };
          openDbRequest.onupgradeneeded = () => {
            const db = openDbRequest.result;
            db.onerror = () => {
              reject(new Error("Failed to create object store"));
            };
            db.createObjectStore(STORE_NAME, { keyPath: "id" });
          };
        });
      }
      withObjectStore(mode, action) {
        return this.getDb().then((db) => {
          const tx = db.transaction(STORE_NAME, mode);
          tx.oncomplete = () => db.close();
          return new Promise((resolve, reject) => {
            tx.onerror = () => reject(tx.error);
            resolve(action(tx.objectStore(STORE_NAME)));
          }).catch((err) => {
            db.close();
            throw err;
          });
        });
      }
    };
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js
var InMemoryStorage;
var init_InMemoryStorage = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js"() {
    InMemoryStorage = class {
      constructor(store2 = {}) {
        this.store = store2;
      }
      getItem(key) {
        if (key in this.store) {
          return this.store[key];
        }
        return null;
      }
      removeItem(key) {
        delete this.store[key];
      }
      setItem(key, value) {
        this.store[key] = value;
      }
    };
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js
function localStorage() {
  if (typeof self === "object" && self.indexedDB) {
    return new IndexedDbStorage();
  }
  if (typeof window === "object" && window.localStorage) {
    return window.localStorage;
  }
  return inMemoryStorage;
}
var inMemoryStorage;
var init_localStorage = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js"() {
    init_IndexedDbStorage();
    init_InMemoryStorage();
    inMemoryStorage = new InMemoryStorage();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js
function fromCognitoIdentityPool({ accountId, cache: cache2 = localStorage(), client: client2, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? "ANONYMOUS" : void 0, logger: logger2, parentClientConfig }) {
  logger2?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity");
  const cacheKey = userIdentifier ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}` : void 0;
  let provider = async () => {
    const { GetIdCommand: GetIdCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), loadCognitoIdentity_exports));
    const _client = client2 ?? new CognitoIdentityClient2(Object.assign({}, clientConfig ?? {}, { region: clientConfig?.region ?? parentClientConfig?.region }));
    let identityId = cacheKey && await cache2.getItem(cacheKey);
    if (!identityId) {
      const { IdentityId = throwOnMissingId(logger2) } = await _client.send(new GetIdCommand2({
        AccountId: accountId,
        IdentityPoolId: identityPoolId,
        Logins: logins ? await resolveLogins(logins) : void 0
      }));
      identityId = IdentityId;
      if (cacheKey) {
        Promise.resolve(cache2.setItem(cacheKey, identityId)).catch(() => {
        });
      }
    }
    provider = fromCognitoIdentity({
      client: _client,
      customRoleArn,
      logins,
      identityId
    });
    return provider();
  };
  return () => provider().catch(async (err) => {
    if (cacheKey) {
      Promise.resolve(cache2.removeItem(cacheKey)).catch(() => {
      });
    }
    throw err;
  });
}
function throwOnMissingId(logger2) {
  throw new CredentialsProviderError("Response from Amazon Cognito contained no identity ID", { logger: logger2 });
}
var init_fromCognitoIdentityPool = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js"() {
    init_dist_es();
    init_fromCognitoIdentity();
    init_localStorage();
    init_resolveLogins();
  }
});

// node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/index.js
var init_dist_es53 = __esm({
  "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/index.js"() {
    init_CognitoProviderParameters();
    init_Logins();
    init_Storage();
    init_fromCognitoIdentity();
    init_fromCognitoIdentityPool();
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js
var fromCognitoIdentity2;
var init_fromCognitoIdentity2 = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentity.js"() {
    init_dist_es53();
    fromCognitoIdentity2 = (options) => fromCognitoIdentity({
      ...options
    });
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js
var fromCognitoIdentityPool2;
var init_fromCognitoIdentityPool2 = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/fromCognitoIdentityPool.js"() {
    init_dist_es53();
    fromCognitoIdentityPool2 = (options) => fromCognitoIdentityPool({
      ...options
    });
  }
});

// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js
var ECS_CONTAINER_HOST, EKS_CONTAINER_HOST_IPv4, EKS_CONTAINER_HOST_IPv6, checkUrl;
var init_checkUrl = __esm({
  "node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js"() {
    init_dist_es();
    ECS_CONTAINER_HOST = "169.254.170.2";
    EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
    EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
    checkUrl = (url, logger2) => {
      if (url.protocol === "https:") {
        return;
      }
      if (url.hostname === ECS_CONTAINER_HOST || url.hostname === EKS_CONTAINER_HOST_IPv4 || url.hostname === EKS_CONTAINER_HOST_IPv6) {
        return;
      }
      if (url.hostname.includes("[")) {
        if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
          return;
        }
      } else {
        if (url.hostname === "localhost") {
          return;
        }
        const ipComponents = url.hostname.split(".");
        const inRange = (component) => {
          const num = parseInt(component, 10);
          return 0 <= num && num <= 255;
        };
        if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
          return;
        }
      }
      throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
  - loopback CIDR 127.0.0.0/8 or [::1/128]
  - ECS container host 169.254.170.2
  - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger2 });
    };
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var init_httpExtensionConfiguration10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions13 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration10();
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery9(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest9;
var init_httpRequest10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest9 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest9({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery9(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest9.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname10 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types16 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es54 = __esm({
  "node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions13();
    init_Field10();
    init_Fields10();
    init_httpHandler10();
    init_httpRequest10();
    init_httpResponse10();
    init_isValidHostname10();
    init_types16();
  }
});

// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js
function createGetRequest(url) {
  return new HttpRequest9({
    protocol: url.protocol,
    hostname: url.hostname,
    port: Number(url.port),
    path: url.pathname,
    query: Array.from(url.searchParams.entries()).reduce((acc, [k3, v5]) => {
      acc[k3] = v5;
      return acc;
    }, {}),
    fragment: url.hash
  });
}
async function getCredentials(response, logger2) {
  const stream = sdkStreamMixin(response.body);
  const str2 = await stream.transformToString();
  if (response.statusCode === 200) {
    const parsed = JSON.parse(str2);
    if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
      throw new CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger2 });
    }
    return {
      accessKeyId: parsed.AccessKeyId,
      secretAccessKey: parsed.SecretAccessKey,
      sessionToken: parsed.Token,
      expiration: parseRfc3339DateTime(parsed.Expiration)
    };
  }
  if (response.statusCode >= 400 && response.statusCode < 500) {
    let parsedBody = {};
    try {
      parsedBody = JSON.parse(str2);
    } catch (e3) {
    }
    throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 }), {
      Code: parsedBody.Code,
      Message: parsedBody.Message
    });
  }
  throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger2 });
}
var init_requestHelpers = __esm({
  "node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js"() {
    init_dist_es();
    init_dist_es54();
    init_dist_es33();
    init_dist_es32();
  }
});

// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js
var retryWrapper;
var init_retry_wrapper = __esm({
  "node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js"() {
    retryWrapper = (toRetry, maxRetries, delayMs) => {
      return async () => {
        for (let i3 = 0; i3 < maxRetries; ++i3) {
          try {
            return await toRetry();
          } catch (e3) {
            await new Promise((resolve) => setTimeout(resolve, delayMs));
          }
        }
        return await toRetry();
      };
    };
  }
});

// node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.browser.js
var fromHttp;
var init_fromHttp_browser = __esm({
  "node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.browser.js"() {
    init_dist_es30();
    init_dist_es();
    init_checkUrl();
    init_requestHelpers();
    init_retry_wrapper();
    fromHttp = (options = {}) => {
      options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");
      let host;
      const full = options.credentialsFullUri;
      if (full) {
        host = full;
      } else {
        throw new CredentialsProviderError("No HTTP credential provider host provided.", { logger: options.logger });
      }
      const url = new URL(host);
      checkUrl(url, options.logger);
      const requestHandler = new FetchHttpHandler();
      return retryWrapper(async () => {
        const request = createGetRequest(url);
        if (options.authorizationToken) {
          request.headers.Authorization = options.authorizationToken;
        }
        const result = await requestHandler.handle(request);
        return getCredentials(result.response);
      }, options.maxRetries ?? 3, options.timeout ?? 1e3);
    };
  }
});

// node_modules/@aws-sdk/credential-provider-http/dist-es/index.browser.js
var init_index_browser = __esm({
  "node_modules/@aws-sdk/credential-provider-http/dist-es/index.browser.js"() {
    init_fromHttp_browser();
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthSchemeProvider.js
function createAwsAuthSigv4HttpAuthOption2(authParameters) {
  return {
    schemeId: "aws.auth#sigv4",
    signingProperties: {
      name: "sts",
      region: authParameters.region
    },
    propertiesExtractor: (config, context) => ({
      signingProperties: {
        config,
        context
      }
    })
  };
}
function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
  return {
    schemeId: "smithy.api#noAuth"
  };
}
var defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig2;
var init_httpAuthSchemeProvider2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthSchemeProvider.js"() {
    init_dist_es43();
    init_dist_es13();
    init_STSClient();
    defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
      return {
        operation: getSmithyContext(context).operation,
        region: await normalizeProvider(config.region)() || (() => {
          throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
        })()
      };
    };
    defaultSTSHttpAuthSchemeProvider = (authParameters) => {
      const options = [];
      switch (authParameters.operation) {
        case "AssumeRoleWithSAML": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        case "AssumeRoleWithWebIdentity": {
          options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
          break;
        }
        default: {
          options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
        }
      }
      return options;
    };
    resolveStsAuthConfig = (input) => ({
      ...input,
      stsClientCtor: STSClient
    });
    resolveHttpAuthSchemeConfig2 = (config) => {
      const config_0 = resolveStsAuthConfig(config);
      const config_1 = resolveAwsSdkSigV4Config(config_0);
      return {
        ...config_1
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/endpoint/EndpointParameters.js
var resolveClientEndpointParameters2, commonParams2;
var init_EndpointParameters2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/endpoint/EndpointParameters.js"() {
    resolveClientEndpointParameters2 = (options) => {
      return {
        ...options,
        useDualstackEndpoint: options.useDualstackEndpoint ?? false,
        useFipsEndpoint: options.useFipsEndpoint ?? false,
        useGlobalEndpoint: options.useGlobalEndpoint ?? false,
        defaultSigningName: "sts"
      };
    };
    commonParams2 = {
      UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
      UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
      Endpoint: { type: "builtInParams", name: "endpoint" },
      Region: { type: "builtInParams", name: "region" },
      UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
    };
  }
});

// node_modules/@aws-sdk/client-sts/package.json
var package_default2;
var init_package2 = __esm({
  "node_modules/@aws-sdk/client-sts/package.json"() {
    package_default2 = {
      name: "@aws-sdk/client-sts",
      description: "AWS SDK for JavaScript Sts Client for Node.js, Browser and React Native",
      version: "3.645.0",
      scripts: {
        build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
        "build:cjs": "node ../../scripts/compilation/inline client-sts",
        "build:es": "tsc -p tsconfig.es.json",
        "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
        "build:types": "rimraf ./dist-types tsconfig.types.tsbuildinfo && tsc -p tsconfig.types.json",
        "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
        clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
        "extract:docs": "api-extractor run --local",
        "generate:client": "node ../../scripts/generate-clients/single-service --solo sts",
        test: "yarn test:unit",
        "test:unit": "jest"
      },
      main: "./dist-cjs/index.js",
      types: "./dist-types/index.d.ts",
      module: "./dist-es/index.js",
      sideEffects: false,
      dependencies: {
        "@aws-crypto/sha256-browser": "5.2.0",
        "@aws-crypto/sha256-js": "5.2.0",
        "@aws-sdk/client-sso-oidc": "3.645.0",
        "@aws-sdk/core": "3.635.0",
        "@aws-sdk/credential-provider-node": "3.645.0",
        "@aws-sdk/middleware-host-header": "3.620.0",
        "@aws-sdk/middleware-logger": "3.609.0",
        "@aws-sdk/middleware-recursion-detection": "3.620.0",
        "@aws-sdk/middleware-user-agent": "3.645.0",
        "@aws-sdk/region-config-resolver": "3.614.0",
        "@aws-sdk/types": "3.609.0",
        "@aws-sdk/util-endpoints": "3.645.0",
        "@aws-sdk/util-user-agent-browser": "3.609.0",
        "@aws-sdk/util-user-agent-node": "3.614.0",
        "@smithy/config-resolver": "^3.0.5",
        "@smithy/core": "^2.4.0",
        "@smithy/fetch-http-handler": "^3.2.4",
        "@smithy/hash-node": "^3.0.3",
        "@smithy/invalid-dependency": "^3.0.3",
        "@smithy/middleware-content-length": "^3.0.5",
        "@smithy/middleware-endpoint": "^3.1.0",
        "@smithy/middleware-retry": "^3.0.15",
        "@smithy/middleware-serde": "^3.0.3",
        "@smithy/middleware-stack": "^3.0.3",
        "@smithy/node-config-provider": "^3.1.4",
        "@smithy/node-http-handler": "^3.1.4",
        "@smithy/protocol-http": "^4.1.0",
        "@smithy/smithy-client": "^3.2.0",
        "@smithy/types": "^3.3.0",
        "@smithy/url-parser": "^3.0.3",
        "@smithy/util-base64": "^3.0.0",
        "@smithy/util-body-length-browser": "^3.0.0",
        "@smithy/util-body-length-node": "^3.0.0",
        "@smithy/util-defaults-mode-browser": "^3.0.15",
        "@smithy/util-defaults-mode-node": "^3.0.15",
        "@smithy/util-endpoints": "^2.0.5",
        "@smithy/util-middleware": "^3.0.3",
        "@smithy/util-retry": "^3.0.3",
        "@smithy/util-utf8": "^3.0.0",
        tslib: "^2.6.2"
      },
      devDependencies: {
        "@tsconfig/node16": "16.1.3",
        "@types/node": "^16.18.96",
        concurrently: "7.0.0",
        "downlevel-dts": "0.10.1",
        rimraf: "3.0.2",
        typescript: "~4.9.5"
      },
      engines: {
        node: ">=16.0.0"
      },
      typesVersions: {
        "<4.0": {
          "dist-types/*": [
            "dist-types/ts3.4/*"
          ]
        }
      },
      files: [
        "dist-*/**"
      ],
      author: {
        name: "AWS SDK for JavaScript Team",
        url: "https://aws.amazon.com/javascript/"
      },
      license: "Apache-2.0",
      browser: {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
      },
      "react-native": {
        "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
      },
      homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sts",
      repository: {
        type: "git",
        url: "https://github.com/aws/aws-sdk-js-v3.git",
        directory: "clients/client-sts"
      }
    };
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
var fromUtf85;
var init_fromUtf8_browser5 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() {
    fromUtf85 = (input) => new TextEncoder().encode(input);
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
var init_toUint8Array5 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() {
    init_fromUtf8_browser5();
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
var toUtf83;
var init_toUtf8_browser5 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() {
    toUtf83 = (input) => {
      if (typeof input === "string") {
        return input;
      }
      if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
        throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
      }
      return new TextDecoder("utf-8").decode(input);
    };
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/index.js
var init_dist_es55 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-utf8/dist-es/index.js"() {
    init_fromUtf8_browser5();
    init_toUint8Array5();
    init_toUtf8_browser5();
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/endpoint/ruleset.js
var F, G, H, I, J, a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2, q2, r3, s2, t2, u2, v2, w, x, y, z2, A, B, C, D, E, _data2, ruleSet2;
var init_ruleset2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/endpoint/ruleset.js"() {
    F = "required";
    G = "type";
    H = "fn";
    I = "argv";
    J = "ref";
    a2 = false;
    b2 = true;
    c2 = "booleanEquals";
    d2 = "stringEquals";
    e2 = "sigv4";
    f2 = "sts";
    g2 = "us-east-1";
    h2 = "endpoint";
    i2 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
    j2 = "tree";
    k2 = "error";
    l2 = "getAttr";
    m2 = { [F]: false, [G]: "String" };
    n2 = { [F]: true, "default": false, [G]: "Boolean" };
    o2 = { [J]: "Endpoint" };
    p2 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
    q2 = { [J]: "Region" };
    r3 = { [H]: "aws.partition", [I]: [q2], "assign": "PartitionResult" };
    s2 = { [J]: "UseFIPS" };
    t2 = { [J]: "UseDualStack" };
    u2 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e2, "signingName": f2, "signingRegion": g2 }] }, "headers": {} };
    v2 = {};
    w = { "conditions": [{ [H]: d2, [I]: [q2, "aws-global"] }], [h2]: u2, [G]: h2 };
    x = { [H]: c2, [I]: [s2, true] };
    y = { [H]: c2, [I]: [t2, true] };
    z2 = { [H]: l2, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
    A = { [J]: "PartitionResult" };
    B = { [H]: c2, [I]: [true, { [H]: l2, [I]: [A, "supportsDualStack"] }] };
    C = [{ [H]: "isSet", [I]: [o2] }];
    D = [x];
    E = [y];
    _data2 = { version: "1.0", parameters: { Region: m2, UseDualStack: n2, UseFIPS: n2, Endpoint: m2, UseGlobalEndpoint: n2 }, rules: [{ conditions: [{ [H]: c2, [I]: [{ [J]: "UseGlobalEndpoint" }, b2] }, { [H]: "not", [I]: C }, p2, r3, { [H]: c2, [I]: [s2, a2] }, { [H]: c2, [I]: [t2, a2] }], rules: [{ conditions: [{ [H]: d2, [I]: [q2, "ap-northeast-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-south-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-2"] }], endpoint: u2, [G]: h2 }, w, { conditions: [{ [H]: d2, [I]: [q2, "ca-central-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-central-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-north-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-2"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-3"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "sa-east-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, g2] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "us-east-2"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-1"] }], endpoint: u2, [G]: h2 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-2"] }], endpoint: u2, [G]: h2 }, { endpoint: { url: i2, properties: { authSchemes: [{ name: e2, signingName: f2, signingRegion: "{Region}" }] }, headers: v2 }, [G]: h2 }], [G]: j2 }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k2 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k2 }, { endpoint: { url: o2, properties: v2, headers: v2 }, [G]: h2 }], [G]: j2 }, { conditions: [p2], rules: [{ conditions: [r3], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c2, [I]: [b2, z2] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h2 }], [G]: j2 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k2 }], [G]: j2 }, { conditions: D, rules: [{ conditions: [{ [H]: c2, [I]: [z2, b2] }], rules: [{ conditions: [{ [H]: d2, [I]: [{ [H]: l2, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v2, headers: v2 }, [G]: h2 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v2, headers: v2 }, [G]: h2 }], [G]: j2 }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k2 }], [G]: j2 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h2 }], [G]: j2 }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k2 }], [G]: j2 }, w, { endpoint: { url: i2, properties: v2, headers: v2 }, [G]: h2 }], [G]: j2 }], [G]: j2 }, { error: "Invalid Configuration: Missing Region", [G]: k2 }] };
    ruleSet2 = _data2;
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/endpoint/endpointResolver.js
var defaultEndpointResolver2;
var init_endpointResolver2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/endpoint/endpointResolver.js"() {
    init_dist_es9();
    init_dist_es8();
    init_ruleset2();
    defaultEndpointResolver2 = (endpointParams, context = {}) => {
      return resolveEndpoint(ruleSet2, {
        endpointParams,
        logger: context.logger
      });
    };
    customEndpointFunctions.aws = awsEndpointFunctions;
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.shared.js
var getRuntimeConfig3;
var init_runtimeConfig_shared2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.shared.js"() {
    init_dist_es43();
    init_dist_es35();
    init_dist_es33();
    init_dist_es16();
    init_dist_es25();
    init_dist_es55();
    init_httpAuthSchemeProvider2();
    init_endpointResolver2();
    getRuntimeConfig3 = (config) => {
      return {
        apiVersion: "2011-06-15",
        base64Decoder: config?.base64Decoder ?? fromBase64,
        base64Encoder: config?.base64Encoder ?? toBase64,
        disableHostPrefix: config?.disableHostPrefix ?? false,
        endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2,
        extensions: config?.extensions ?? [],
        httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,
        httpAuthSchemes: config?.httpAuthSchemes ?? [
          {
            schemeId: "aws.auth#sigv4",
            identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
            signer: new AwsSdkSigV4Signer()
          },
          {
            schemeId: "smithy.api#noAuth",
            identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
            signer: new NoAuthSigner()
          }
        ],
        logger: config?.logger ?? new NoOpLogger(),
        serviceId: config?.serviceId ?? "STS",
        urlParser: config?.urlParser ?? parseUrl,
        utf8Decoder: config?.utf8Decoder ?? fromUtf85,
        utf8Encoder: config?.utf8Encoder ?? toUtf83
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.browser.js
var getRuntimeConfig4;
var init_runtimeConfig_browser2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/runtimeConfig.browser.js"() {
    init_package2();
    init_module2();
    init_dist_es45();
    init_dist_es14();
    init_dist_es30();
    init_dist_es46();
    init_dist_es47();
    init_dist_es21();
    init_runtimeConfig_shared2();
    init_dist_es33();
    init_dist_es49();
    getRuntimeConfig4 = (config) => {
      const defaultsMode = resolveDefaultsModeConfig(config);
      const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
      const clientSharedValues = getRuntimeConfig3(config);
      return {
        ...clientSharedValues,
        ...config,
        runtime: "browser",
        defaultsMode,
        bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
        credentialDefaultProvider: config?.credentialDefaultProvider ?? ((_2) => () => Promise.reject(new Error("Credential is missing"))),
        defaultUserAgentProvider: config?.defaultUserAgentProvider ?? defaultUserAgent({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
        maxAttempts: config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
        region: config?.region ?? invalidProvider("Region is missing"),
        requestHandler: FetchHttpHandler.create(config?.requestHandler ?? defaultConfigProvider),
        retryMode: config?.retryMode ?? (async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE),
        sha256: config?.sha256 ?? Sha2562,
        streamCollector: config?.streamCollector ?? streamCollector,
        useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)),
        useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
var getHttpHandlerExtensionConfiguration2, resolveHttpHandlerRuntimeConfig2;
var init_httpExtensionConfiguration11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() {
    getHttpHandlerExtensionConfiguration2 = (runtimeConfig) => {
      let httpHandler = runtimeConfig.httpHandler;
      return {
        setHttpHandler(handler) {
          httpHandler = handler;
        },
        httpHandler() {
          return httpHandler;
        },
        updateHttpClientConfig(key, value) {
          httpHandler.updateHttpClientConfig(key, value);
        },
        httpHandlerConfigs() {
          return httpHandler.httpHandlerConfigs();
        }
      };
    };
    resolveHttpHandlerRuntimeConfig2 = (httpHandlerExtensionConfiguration) => {
      return {
        httpHandler: httpHandlerExtensionConfiguration.httpHandler()
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/index.js
var init_extensions14 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() {
    init_httpExtensionConfiguration11();
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/Field.js
var init_Field11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/Field.js"() {
    init_dist_es2();
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/Fields.js
var init_Fields11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/Fields.js"() {
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpHandler.js
var init_httpHandler11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() {
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpRequest.js
function cloneQuery10(query) {
  return Object.keys(query).reduce((carry, paramName) => {
    const param = query[paramName];
    return {
      ...carry,
      [paramName]: Array.isArray(param) ? [...param] : param
    };
  }, {});
}
var HttpRequest10;
var init_httpRequest11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() {
    HttpRequest10 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static clone(request) {
        const cloned = new HttpRequest10({
          ...request,
          headers: { ...request.headers }
        });
        if (cloned.query) {
          cloned.query = cloneQuery10(cloned.query);
        }
        return cloned;
      }
      static isInstance(request) {
        if (!request) {
          return false;
        }
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        return HttpRequest10.clone(this);
      }
    };
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpResponse.js
var init_httpResponse11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() {
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js
var init_isValidHostname11 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() {
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/types.js
var init_types17 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/types.js"() {
  }
});

// node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/index.js
var init_dist_es56 = __esm({
  "node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-es/index.js"() {
    init_extensions14();
    init_Field11();
    init_Fields11();
    init_httpHandler11();
    init_httpRequest11();
    init_httpResponse11();
    init_isValidHostname11();
    init_types17();
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthExtensionConfiguration.js
var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
var init_httpAuthExtensionConfiguration2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/auth/httpAuthExtensionConfiguration.js"() {
    getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
      const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
      let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
      let _credentials = runtimeConfig.credentials;
      return {
        setHttpAuthScheme(httpAuthScheme) {
          const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
          if (index2 === -1) {
            _httpAuthSchemes.push(httpAuthScheme);
          } else {
            _httpAuthSchemes.splice(index2, 1, httpAuthScheme);
          }
        },
        httpAuthSchemes() {
          return _httpAuthSchemes;
        },
        setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
          _httpAuthSchemeProvider = httpAuthSchemeProvider;
        },
        httpAuthSchemeProvider() {
          return _httpAuthSchemeProvider;
        },
        setCredentials(credentials) {
          _credentials = credentials;
        },
        credentials() {
          return _credentials;
        }
      };
    };
    resolveHttpAuthRuntimeConfig2 = (config) => {
      return {
        httpAuthSchemes: config.httpAuthSchemes(),
        httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
        credentials: config.credentials()
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/runtimeExtensions.js
var asPartial2, resolveRuntimeExtensions2;
var init_runtimeExtensions2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/runtimeExtensions.js"() {
    init_dist_es50();
    init_dist_es56();
    init_dist_es33();
    init_httpAuthExtensionConfiguration2();
    asPartial2 = (t3) => t3;
    resolveRuntimeExtensions2 = (runtimeConfig, extensions) => {
      const extensionConfiguration = {
        ...asPartial2(getAwsRegionExtensionConfiguration(runtimeConfig)),
        ...asPartial2(getDefaultExtensionConfiguration(runtimeConfig)),
        ...asPartial2(getHttpHandlerExtensionConfiguration2(runtimeConfig)),
        ...asPartial2(getHttpAuthExtensionConfiguration2(runtimeConfig))
      };
      extensions.forEach((extension) => extension.configure(extensionConfiguration));
      return {
        ...runtimeConfig,
        ...resolveAwsRegionExtensionConfiguration(extensionConfiguration),
        ...resolveDefaultRuntimeConfig(extensionConfiguration),
        ...resolveHttpHandlerRuntimeConfig2(extensionConfiguration),
        ...resolveHttpAuthRuntimeConfig2(extensionConfiguration)
      };
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/STSClient.js
var STSClient;
var init_STSClient = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/STSClient.js"() {
    init_dist_es4();
    init_dist_es5();
    init_dist_es7();
    init_dist_es11();
    init_dist_es14();
    init_dist_es35();
    init_dist_es37();
    init_dist_es18();
    init_dist_es34();
    init_dist_es33();
    init_httpAuthSchemeProvider2();
    init_EndpointParameters2();
    init_runtimeConfig_browser2();
    init_runtimeExtensions2();
    STSClient = class extends Client2 {
      constructor(...[configuration2]) {
        const _config_0 = getRuntimeConfig4(configuration2 || {});
        const _config_1 = resolveClientEndpointParameters2(_config_0);
        const _config_2 = resolveUserAgentConfig(_config_1);
        const _config_3 = resolveRetryConfig(_config_2);
        const _config_4 = resolveRegionConfig(_config_3);
        const _config_5 = resolveHostHeaderConfig(_config_4);
        const _config_6 = resolveEndpointConfig(_config_5);
        const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
        const _config_8 = resolveRuntimeExtensions2(_config_7, configuration2?.extensions || []);
        super(_config_8);
        this.config = _config_8;
        this.middlewareStack.use(getUserAgentPlugin(this.config));
        this.middlewareStack.use(getRetryPlugin(this.config));
        this.middlewareStack.use(getContentLengthPlugin(this.config));
        this.middlewareStack.use(getHostHeaderPlugin(this.config));
        this.middlewareStack.use(getLoggerPlugin(this.config));
        this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
        this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
          httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
          identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
            "aws.auth#sigv4": config.credentials
          })
        }));
        this.middlewareStack.use(getHttpSigningPlugin(this.config));
      }
      destroy() {
        super.destroy();
      }
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/models/STSServiceException.js
var STSServiceException;
var init_STSServiceException = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/models/STSServiceException.js"() {
    init_dist_es33();
    STSServiceException = class extends ServiceException {
      constructor(options) {
        super(options);
        Object.setPrototypeOf(this, STSServiceException.prototype);
      }
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/models/models_0.js
var ExpiredTokenException, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException, InvalidAuthorizationMessageException, CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, GetFederationTokenResponseFilterSensitiveLog, GetSessionTokenResponseFilterSensitiveLog;
var init_models_02 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/models/models_0.js"() {
    init_dist_es33();
    init_STSServiceException();
    ExpiredTokenException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "ExpiredTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "ExpiredTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, ExpiredTokenException.prototype);
      }
    };
    MalformedPolicyDocumentException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "MalformedPolicyDocumentException",
          $fault: "client",
          ...opts
        });
        this.name = "MalformedPolicyDocumentException";
        this.$fault = "client";
        Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype);
      }
    };
    PackedPolicyTooLargeException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "PackedPolicyTooLargeException",
          $fault: "client",
          ...opts
        });
        this.name = "PackedPolicyTooLargeException";
        this.$fault = "client";
        Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype);
      }
    };
    RegionDisabledException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "RegionDisabledException",
          $fault: "client",
          ...opts
        });
        this.name = "RegionDisabledException";
        this.$fault = "client";
        Object.setPrototypeOf(this, RegionDisabledException.prototype);
      }
    };
    IDPRejectedClaimException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "IDPRejectedClaimException",
          $fault: "client",
          ...opts
        });
        this.name = "IDPRejectedClaimException";
        this.$fault = "client";
        Object.setPrototypeOf(this, IDPRejectedClaimException.prototype);
      }
    };
    InvalidIdentityTokenException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "InvalidIdentityTokenException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidIdentityTokenException";
        this.$fault = "client";
        Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype);
      }
    };
    IDPCommunicationErrorException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "IDPCommunicationErrorException",
          $fault: "client",
          ...opts
        });
        this.name = "IDPCommunicationErrorException";
        this.$fault = "client";
        Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype);
      }
    };
    InvalidAuthorizationMessageException = class extends STSServiceException {
      constructor(opts) {
        super({
          name: "InvalidAuthorizationMessageException",
          $fault: "client",
          ...opts
        });
        this.name = "InvalidAuthorizationMessageException";
        this.$fault = "client";
        Object.setPrototypeOf(this, InvalidAuthorizationMessageException.prototype);
      }
    };
    CredentialsFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.SecretAccessKey && { SecretAccessKey: SENSITIVE_STRING }
    });
    AssumeRoleResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    AssumeRoleWithSAMLRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.SAMLAssertion && { SAMLAssertion: SENSITIVE_STRING }
    });
    AssumeRoleWithSAMLResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.WebIdentityToken && { WebIdentityToken: SENSITIVE_STRING }
    });
    AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    GetFederationTokenResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
    GetSessionTokenResponseFilterSensitiveLog = (obj) => ({
      ...obj,
      ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
    });
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/protocols/Aws_query.js
var se_AssumeRoleCommand, se_AssumeRoleWithSAMLCommand, se_AssumeRoleWithWebIdentityCommand, se_DecodeAuthorizationMessageCommand, se_GetAccessKeyInfoCommand, se_GetCallerIdentityCommand, se_GetFederationTokenCommand, se_GetSessionTokenCommand, de_AssumeRoleCommand, de_AssumeRoleWithSAMLCommand, de_AssumeRoleWithWebIdentityCommand, de_DecodeAuthorizationMessageCommand, de_GetAccessKeyInfoCommand, de_GetCallerIdentityCommand, de_GetFederationTokenCommand, de_GetSessionTokenCommand, de_CommandError2, de_ExpiredTokenExceptionRes, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidAuthorizationMessageExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithSAMLRequest, se_AssumeRoleWithWebIdentityRequest, se_DecodeAuthorizationMessageRequest, se_GetAccessKeyInfoRequest, se_GetCallerIdentityRequest, se_GetFederationTokenRequest, se_GetSessionTokenRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithSAMLResponse, de_AssumeRoleWithWebIdentityResponse, de_Credentials2, de_DecodeAuthorizationMessageResponse, de_ExpiredTokenException, de_FederatedUser, de_GetAccessKeyInfoResponse, de_GetCallerIdentityResponse, de_GetFederationTokenResponse, de_GetSessionTokenResponse, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidAuthorizationMessageException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata3, throwDefaultError3, buildHttpRpcRequest2, SHARED_HEADERS, _, _A, _AKI, _AR, _ARI, _ARU, _ARWSAML, _ARWWI, _Ac, _Ar, _Au, _C, _CA, _DAM, _DM, _DS, _E, _EI, _EM, _FU, _FUI, _GAKI, _GCI, _GFT, _GST, _I, _K, _N, _NQ, _P, _PA, _PAr, _PAro, _PC, _PI, _PPS, _Pr, _RA, _RSN, _S, _SAK, _SAMLA, _SFWIT, _SI, _SN, _ST, _STe, _T, _TC, _TTK, _UI, _V, _Va, _WIT, _a, _m, buildFormUrlencodedString, loadQueryErrorCode;
var init_Aws_query = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/protocols/Aws_query.js"() {
    init_dist_es43();
    init_dist_es56();
    init_dist_es33();
    init_models_02();
    init_STSServiceException();
    se_AssumeRoleCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleRequest(input, context),
        [_A]: _AR,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_AssumeRoleWithSAMLCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleWithSAMLRequest(input, context),
        [_A]: _ARWSAML,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_AssumeRoleWithWebIdentityCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_AssumeRoleWithWebIdentityRequest(input, context),
        [_A]: _ARWWI,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_DecodeAuthorizationMessageCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_DecodeAuthorizationMessageRequest(input, context),
        [_A]: _DAM,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_GetAccessKeyInfoCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetAccessKeyInfoRequest(input, context),
        [_A]: _GAKI,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_GetCallerIdentityCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetCallerIdentityRequest(input, context),
        [_A]: _GCI,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_GetFederationTokenCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetFederationTokenRequest(input, context),
        [_A]: _GFT,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    se_GetSessionTokenCommand = async (input, context) => {
      const headers = SHARED_HEADERS;
      let body;
      body = buildFormUrlencodedString({
        ...se_GetSessionTokenRequest(input, context),
        [_A]: _GST,
        [_V]: _
      });
      return buildHttpRpcRequest2(context, headers, "/", void 0, body);
    };
    de_AssumeRoleCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_AssumeRoleWithSAMLCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithSAMLResponse(data.AssumeRoleWithSAMLResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_AssumeRoleWithWebIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_DecodeAuthorizationMessageCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_DecodeAuthorizationMessageResponse(data.DecodeAuthorizationMessageResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_GetAccessKeyInfoCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_GetAccessKeyInfoResponse(data.GetAccessKeyInfoResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_GetCallerIdentityCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_GetCallerIdentityResponse(data.GetCallerIdentityResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_GetFederationTokenCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_GetFederationTokenResponse(data.GetFederationTokenResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_GetSessionTokenCommand = async (output, context) => {
      if (output.statusCode >= 300) {
        return de_CommandError2(output, context);
      }
      const data = await parseXmlBody(output.body, context);
      let contents = {};
      contents = de_GetSessionTokenResponse(data.GetSessionTokenResult, context);
      const response = {
        $metadata: deserializeMetadata3(output),
        ...contents
      };
      return response;
    };
    de_CommandError2 = async (output, context) => {
      const parsedOutput = {
        ...output,
        body: await parseXmlErrorBody(output.body, context)
      };
      const errorCode = loadQueryErrorCode(output, parsedOutput.body);
      switch (errorCode) {
        case "ExpiredTokenException":
        case "com.amazonaws.sts#ExpiredTokenException":
          throw await de_ExpiredTokenExceptionRes(parsedOutput, context);
        case "MalformedPolicyDocument":
        case "com.amazonaws.sts#MalformedPolicyDocumentException":
          throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context);
        case "PackedPolicyTooLarge":
        case "com.amazonaws.sts#PackedPolicyTooLargeException":
          throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context);
        case "RegionDisabledException":
        case "com.amazonaws.sts#RegionDisabledException":
          throw await de_RegionDisabledExceptionRes(parsedOutput, context);
        case "IDPRejectedClaim":
        case "com.amazonaws.sts#IDPRejectedClaimException":
          throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context);
        case "InvalidIdentityToken":
        case "com.amazonaws.sts#InvalidIdentityTokenException":
          throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context);
        case "IDPCommunicationError":
        case "com.amazonaws.sts#IDPCommunicationErrorException":
          throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
        case "InvalidAuthorizationMessageException":
        case "com.amazonaws.sts#InvalidAuthorizationMessageException":
          throw await de_InvalidAuthorizationMessageExceptionRes(parsedOutput, context);
        default:
          const parsedBody = parsedOutput.body;
          return throwDefaultError3({
            output,
            parsedBody: parsedBody.Error,
            errorCode
          });
      }
    };
    de_ExpiredTokenExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_ExpiredTokenException(body.Error, context);
      const exception = new ExpiredTokenException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPCommunicationErrorException(body.Error, context);
      const exception = new IDPCommunicationErrorException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_IDPRejectedClaimException(body.Error, context);
      const exception = new IDPRejectedClaimException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InvalidAuthorizationMessageExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidAuthorizationMessageException(body.Error, context);
      const exception = new InvalidAuthorizationMessageException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_InvalidIdentityTokenException(body.Error, context);
      const exception = new InvalidIdentityTokenException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
      const exception = new MalformedPolicyDocumentException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
      const exception = new PackedPolicyTooLargeException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    de_RegionDisabledExceptionRes = async (parsedOutput, context) => {
      const body = parsedOutput.body;
      const deserialized = de_RegionDisabledException(body.Error, context);
      const exception = new RegionDisabledException({
        $metadata: deserializeMetadata3(parsedOutput),
        ...deserialized
      });
      return decorateServiceException(exception, body);
    };
    se_AssumeRoleRequest = (input, context) => {
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_T] != null) {
        const memberEntries = se_tagListType(input[_T], context);
        if (input[_T]?.length === 0) {
          entries.Tags = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `Tags.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_TTK] != null) {
        const memberEntries = se_tagKeyListType(input[_TTK], context);
        if (input[_TTK]?.length === 0) {
          entries.TransitiveTagKeys = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `TransitiveTagKeys.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_EI] != null) {
        entries[_EI] = input[_EI];
      }
      if (input[_SN] != null) {
        entries[_SN] = input[_SN];
      }
      if (input[_TC] != null) {
        entries[_TC] = input[_TC];
      }
      if (input[_SI] != null) {
        entries[_SI] = input[_SI];
      }
      if (input[_PC] != null) {
        const memberEntries = se_ProvidedContextsListType(input[_PC], context);
        if (input[_PC]?.length === 0) {
          entries.ProvidedContexts = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `ProvidedContexts.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    };
    se_AssumeRoleWithSAMLRequest = (input, context) => {
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_PAr] != null) {
        entries[_PAr] = input[_PAr];
      }
      if (input[_SAMLA] != null) {
        entries[_SAMLA] = input[_SAMLA];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      return entries;
    };
    se_AssumeRoleWithWebIdentityRequest = (input, context) => {
      const entries = {};
      if (input[_RA] != null) {
        entries[_RA] = input[_RA];
      }
      if (input[_RSN] != null) {
        entries[_RSN] = input[_RSN];
      }
      if (input[_WIT] != null) {
        entries[_WIT] = input[_WIT];
      }
      if (input[_PI] != null) {
        entries[_PI] = input[_PI];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      return entries;
    };
    se_DecodeAuthorizationMessageRequest = (input, context) => {
      const entries = {};
      if (input[_EM] != null) {
        entries[_EM] = input[_EM];
      }
      return entries;
    };
    se_GetAccessKeyInfoRequest = (input, context) => {
      const entries = {};
      if (input[_AKI] != null) {
        entries[_AKI] = input[_AKI];
      }
      return entries;
    };
    se_GetCallerIdentityRequest = (input, context) => {
      const entries = {};
      return entries;
    };
    se_GetFederationTokenRequest = (input, context) => {
      const entries = {};
      if (input[_N] != null) {
        entries[_N] = input[_N];
      }
      if (input[_P] != null) {
        entries[_P] = input[_P];
      }
      if (input[_PA] != null) {
        const memberEntries = se_policyDescriptorListType(input[_PA], context);
        if (input[_PA]?.length === 0) {
          entries.PolicyArns = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `PolicyArns.${key}`;
          entries[loc] = value;
        });
      }
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_T] != null) {
        const memberEntries = se_tagListType(input[_T], context);
        if (input[_T]?.length === 0) {
          entries.Tags = [];
        }
        Object.entries(memberEntries).forEach(([key, value]) => {
          const loc = `Tags.${key}`;
          entries[loc] = value;
        });
      }
      return entries;
    };
    se_GetSessionTokenRequest = (input, context) => {
      const entries = {};
      if (input[_DS] != null) {
        entries[_DS] = input[_DS];
      }
      if (input[_SN] != null) {
        entries[_SN] = input[_SN];
      }
      if (input[_TC] != null) {
        entries[_TC] = input[_TC];
      }
      return entries;
    };
    se_policyDescriptorListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_PolicyDescriptorType(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_PolicyDescriptorType = (input, context) => {
      const entries = {};
      if (input[_a] != null) {
        entries[_a] = input[_a];
      }
      return entries;
    };
    se_ProvidedContext = (input, context) => {
      const entries = {};
      if (input[_PAro] != null) {
        entries[_PAro] = input[_PAro];
      }
      if (input[_CA] != null) {
        entries[_CA] = input[_CA];
      }
      return entries;
    };
    se_ProvidedContextsListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_ProvidedContext(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    se_Tag = (input, context) => {
      const entries = {};
      if (input[_K] != null) {
        entries[_K] = input[_K];
      }
      if (input[_Va] != null) {
        entries[_Va] = input[_Va];
      }
      return entries;
    };
    se_tagKeyListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        entries[`member.${counter}`] = entry;
        counter++;
      }
      return entries;
    };
    se_tagListType = (input, context) => {
      const entries = {};
      let counter = 1;
      for (const entry of input) {
        if (entry === null) {
          continue;
        }
        const memberEntries = se_Tag(entry, context);
        Object.entries(memberEntries).forEach(([key, value]) => {
          entries[`member.${counter}.${key}`] = value;
        });
        counter++;
      }
      return entries;
    };
    de_AssumedRoleUser = (output, context) => {
      const contents = {};
      if (output[_ARI] != null) {
        contents[_ARI] = expectString(output[_ARI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = expectString(output[_Ar]);
      }
      return contents;
    };
    de_AssumeRoleResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials2(output[_C], context);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      if (output[_SI] != null) {
        contents[_SI] = expectString(output[_SI]);
      }
      return contents;
    };
    de_AssumeRoleWithSAMLResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials2(output[_C], context);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      if (output[_S] != null) {
        contents[_S] = expectString(output[_S]);
      }
      if (output[_ST] != null) {
        contents[_ST] = expectString(output[_ST]);
      }
      if (output[_I] != null) {
        contents[_I] = expectString(output[_I]);
      }
      if (output[_Au] != null) {
        contents[_Au] = expectString(output[_Au]);
      }
      if (output[_NQ] != null) {
        contents[_NQ] = expectString(output[_NQ]);
      }
      if (output[_SI] != null) {
        contents[_SI] = expectString(output[_SI]);
      }
      return contents;
    };
    de_AssumeRoleWithWebIdentityResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials2(output[_C], context);
      }
      if (output[_SFWIT] != null) {
        contents[_SFWIT] = expectString(output[_SFWIT]);
      }
      if (output[_ARU] != null) {
        contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      if (output[_Pr] != null) {
        contents[_Pr] = expectString(output[_Pr]);
      }
      if (output[_Au] != null) {
        contents[_Au] = expectString(output[_Au]);
      }
      if (output[_SI] != null) {
        contents[_SI] = expectString(output[_SI]);
      }
      return contents;
    };
    de_Credentials2 = (output, context) => {
      const contents = {};
      if (output[_AKI] != null) {
        contents[_AKI] = expectString(output[_AKI]);
      }
      if (output[_SAK] != null) {
        contents[_SAK] = expectString(output[_SAK]);
      }
      if (output[_STe] != null) {
        contents[_STe] = expectString(output[_STe]);
      }
      if (output[_E] != null) {
        contents[_E] = expectNonNull(parseRfc3339DateTimeWithOffset(output[_E]));
      }
      return contents;
    };
    de_DecodeAuthorizationMessageResponse = (output, context) => {
      const contents = {};
      if (output[_DM] != null) {
        contents[_DM] = expectString(output[_DM]);
      }
      return contents;
    };
    de_ExpiredTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_FederatedUser = (output, context) => {
      const contents = {};
      if (output[_FUI] != null) {
        contents[_FUI] = expectString(output[_FUI]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = expectString(output[_Ar]);
      }
      return contents;
    };
    de_GetAccessKeyInfoResponse = (output, context) => {
      const contents = {};
      if (output[_Ac] != null) {
        contents[_Ac] = expectString(output[_Ac]);
      }
      return contents;
    };
    de_GetCallerIdentityResponse = (output, context) => {
      const contents = {};
      if (output[_UI] != null) {
        contents[_UI] = expectString(output[_UI]);
      }
      if (output[_Ac] != null) {
        contents[_Ac] = expectString(output[_Ac]);
      }
      if (output[_Ar] != null) {
        contents[_Ar] = expectString(output[_Ar]);
      }
      return contents;
    };
    de_GetFederationTokenResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials2(output[_C], context);
      }
      if (output[_FU] != null) {
        contents[_FU] = de_FederatedUser(output[_FU], context);
      }
      if (output[_PPS] != null) {
        contents[_PPS] = strictParseInt32(output[_PPS]);
      }
      return contents;
    };
    de_GetSessionTokenResponse = (output, context) => {
      const contents = {};
      if (output[_C] != null) {
        contents[_C] = de_Credentials2(output[_C], context);
      }
      return contents;
    };
    de_IDPCommunicationErrorException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_IDPRejectedClaimException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_InvalidAuthorizationMessageException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_InvalidIdentityTokenException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_MalformedPolicyDocumentException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_PackedPolicyTooLargeException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    de_RegionDisabledException = (output, context) => {
      const contents = {};
      if (output[_m] != null) {
        contents[_m] = expectString(output[_m]);
      }
      return contents;
    };
    deserializeMetadata3 = (output) => ({
      httpStatusCode: output.statusCode,
      requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
      extendedRequestId: output.headers["x-amz-id-2"],
      cfId: output.headers["x-amz-cf-id"]
    });
    throwDefaultError3 = withBaseException(STSServiceException);
    buildHttpRpcRequest2 = async (context, headers, path, resolvedHostname, body) => {
      const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
      const contents = {
        protocol,
        hostname,
        port,
        method: "POST",
        path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path,
        headers
      };
      if (resolvedHostname !== void 0) {
        contents.hostname = resolvedHostname;
      }
      if (body !== void 0) {
        contents.body = body;
      }
      return new HttpRequest10(contents);
    };
    SHARED_HEADERS = {
      "content-type": "application/x-www-form-urlencoded"
    };
    _ = "2011-06-15";
    _A = "Action";
    _AKI = "AccessKeyId";
    _AR = "AssumeRole";
    _ARI = "AssumedRoleId";
    _ARU = "AssumedRoleUser";
    _ARWSAML = "AssumeRoleWithSAML";
    _ARWWI = "AssumeRoleWithWebIdentity";
    _Ac = "Account";
    _Ar = "Arn";
    _Au = "Audience";
    _C = "Credentials";
    _CA = "ContextAssertion";
    _DAM = "DecodeAuthorizationMessage";
    _DM = "DecodedMessage";
    _DS = "DurationSeconds";
    _E = "Expiration";
    _EI = "ExternalId";
    _EM = "EncodedMessage";
    _FU = "FederatedUser";
    _FUI = "FederatedUserId";
    _GAKI = "GetAccessKeyInfo";
    _GCI = "GetCallerIdentity";
    _GFT = "GetFederationToken";
    _GST = "GetSessionToken";
    _I = "Issuer";
    _K = "Key";
    _N = "Name";
    _NQ = "NameQualifier";
    _P = "Policy";
    _PA = "PolicyArns";
    _PAr = "PrincipalArn";
    _PAro = "ProviderArn";
    _PC = "ProvidedContexts";
    _PI = "ProviderId";
    _PPS = "PackedPolicySize";
    _Pr = "Provider";
    _RA = "RoleArn";
    _RSN = "RoleSessionName";
    _S = "Subject";
    _SAK = "SecretAccessKey";
    _SAMLA = "SAMLAssertion";
    _SFWIT = "SubjectFromWebIdentityToken";
    _SI = "SourceIdentity";
    _SN = "SerialNumber";
    _ST = "SubjectType";
    _STe = "SessionToken";
    _T = "Tags";
    _TC = "TokenCode";
    _TTK = "TransitiveTagKeys";
    _UI = "UserId";
    _V = "Version";
    _Va = "Value";
    _WIT = "WebIdentityToken";
    _a = "arn";
    _m = "message";
    buildFormUrlencodedString = (formEntries) => Object.entries(formEntries).map(([key, value]) => extendedEncodeURIComponent(key) + "=" + extendedEncodeURIComponent(value)).join("&");
    loadQueryErrorCode = (output, data) => {
      if (data.Error?.Code !== void 0) {
        return data.Error.Code;
      }
      if (output.statusCode == 404) {
        return "NotFound";
      }
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleCommand.js
var AssumeRoleCommand;
var init_AssumeRoleCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    AssumeRoleCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithSAMLCommand.js
var AssumeRoleWithSAMLCommand;
var init_AssumeRoleWithSAMLCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithSAMLCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    AssumeRoleWithSAMLCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}).n("STSClient", "AssumeRoleWithSAMLCommand").f(AssumeRoleWithSAMLRequestFilterSensitiveLog, AssumeRoleWithSAMLResponseFilterSensitiveLog).ser(se_AssumeRoleWithSAMLCommand).de(de_AssumeRoleWithSAMLCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithWebIdentityCommand.js
var AssumeRoleWithWebIdentityCommand;
var init_AssumeRoleWithWebIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/AssumeRoleWithWebIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    AssumeRoleWithWebIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/DecodeAuthorizationMessageCommand.js
var DecodeAuthorizationMessageCommand;
var init_DecodeAuthorizationMessageCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/DecodeAuthorizationMessageCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_Aws_query();
    DecodeAuthorizationMessageCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}).n("STSClient", "DecodeAuthorizationMessageCommand").f(void 0, void 0).ser(se_DecodeAuthorizationMessageCommand).de(de_DecodeAuthorizationMessageCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/GetAccessKeyInfoCommand.js
var GetAccessKeyInfoCommand;
var init_GetAccessKeyInfoCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/GetAccessKeyInfoCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_Aws_query();
    GetAccessKeyInfoCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}).n("STSClient", "GetAccessKeyInfoCommand").f(void 0, void 0).ser(se_GetAccessKeyInfoCommand).de(de_GetAccessKeyInfoCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/GetCallerIdentityCommand.js
var GetCallerIdentityCommand;
var init_GetCallerIdentityCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/GetCallerIdentityCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_Aws_query();
    GetCallerIdentityCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}).n("STSClient", "GetCallerIdentityCommand").f(void 0, void 0).ser(se_GetCallerIdentityCommand).de(de_GetCallerIdentityCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/GetFederationTokenCommand.js
var GetFederationTokenCommand;
var init_GetFederationTokenCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/GetFederationTokenCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    GetFederationTokenCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}).n("STSClient", "GetFederationTokenCommand").f(void 0, GetFederationTokenResponseFilterSensitiveLog).ser(se_GetFederationTokenCommand).de(de_GetFederationTokenCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/GetSessionTokenCommand.js
var GetSessionTokenCommand;
var init_GetSessionTokenCommand = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/GetSessionTokenCommand.js"() {
    init_dist_es18();
    init_dist_es17();
    init_dist_es33();
    init_EndpointParameters2();
    init_models_02();
    init_Aws_query();
    GetSessionTokenCommand = class extends Command2.classBuilder().ep({
      ...commonParams2
    }).m(function(Command3, cs, config, o3) {
      return [
        getSerdePlugin(config, this.serialize, this.deserialize),
        getEndpointPlugin(config, Command3.getEndpointParameterInstructions())
      ];
    }).s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}).n("STSClient", "GetSessionTokenCommand").f(void 0, GetSessionTokenResponseFilterSensitiveLog).ser(se_GetSessionTokenCommand).de(de_GetSessionTokenCommand).build() {
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/STS.js
var commands2, STS;
var init_STS = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/STS.js"() {
    init_dist_es33();
    init_AssumeRoleCommand();
    init_AssumeRoleWithSAMLCommand();
    init_AssumeRoleWithWebIdentityCommand();
    init_DecodeAuthorizationMessageCommand();
    init_GetAccessKeyInfoCommand();
    init_GetCallerIdentityCommand();
    init_GetFederationTokenCommand();
    init_GetSessionTokenCommand();
    init_STSClient();
    commands2 = {
      AssumeRoleCommand,
      AssumeRoleWithSAMLCommand,
      AssumeRoleWithWebIdentityCommand,
      DecodeAuthorizationMessageCommand,
      GetAccessKeyInfoCommand,
      GetCallerIdentityCommand,
      GetFederationTokenCommand,
      GetSessionTokenCommand
    };
    STS = class extends STSClient {
    };
    createAggregatedClient(commands2, STS);
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/commands/index.js
var init_commands2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/commands/index.js"() {
    init_AssumeRoleCommand();
    init_AssumeRoleWithSAMLCommand();
    init_AssumeRoleWithWebIdentityCommand();
    init_DecodeAuthorizationMessageCommand();
    init_GetAccessKeyInfoCommand();
    init_GetCallerIdentityCommand();
    init_GetFederationTokenCommand();
    init_GetSessionTokenCommand();
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/models/index.js
var init_models2 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/models/index.js"() {
    init_models_02();
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/defaultStsRoleAssumers.js
var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
var init_defaultStsRoleAssumers = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/defaultStsRoleAssumers.js"() {
    init_AssumeRoleCommand();
    init_AssumeRoleWithWebIdentityCommand();
    ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
    getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
      if (typeof assumedRoleUser?.Arn === "string") {
        const arnComponents = assumedRoleUser.Arn.split(":");
        if (arnComponents.length > 4 && arnComponents[4] !== "") {
          return arnComponents[4];
        }
      }
      return void 0;
    };
    resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
      const region = typeof _region === "function" ? await _region() : _region;
      const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
      credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
      return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
    };
    getDefaultRoleAssumer = (stsOptions, stsClientCtor) => {
      let stsClient;
      let closureSourceCreds;
      return async (sourceCreds, params) => {
        closureSourceCreds = sourceCreds;
        if (!stsClient) {
          const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new stsClientCtor({
            credentialDefaultProvider: () => async () => closureSourceCreds,
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger2
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        return {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
      };
    };
    getDefaultRoleAssumerWithWebIdentity = (stsOptions, stsClientCtor) => {
      let stsClient;
      return async (params) => {
        if (!stsClient) {
          const { logger: logger2 = stsOptions?.parentClientConfig?.logger, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
          const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
          const isCompatibleRequestHandler = !isH2(requestHandler);
          stsClient = new stsClientCtor({
            region: resolvedRegion,
            requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
            logger: logger2
          });
        }
        const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
        }
        const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
        return {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
          ...accountId && { accountId }
        };
      };
    };
    isH2 = (requestHandler) => {
      return requestHandler?.metadata?.handlerProtocol === "h2";
    };
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/defaultRoleAssumers.js
var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
var init_defaultRoleAssumers = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/defaultRoleAssumers.js"() {
    init_defaultStsRoleAssumers();
    init_STSClient();
    getCustomizableStsClientCtor = (baseCtor, customizations) => {
      if (!customizations)
        return baseCtor;
      else
        return class CustomizableSTSClient extends baseCtor {
          constructor(config) {
            super(config);
            for (const customization of customizations) {
              this.middlewareStack.use(customization);
            }
          }
        };
    };
    getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
    decorateDefaultCredentialProvider = (provider) => (input) => provider({
      roleAssumer: getDefaultRoleAssumer2(input),
      roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
      ...input
    });
  }
});

// node_modules/@aws-sdk/client-sts/dist-es/index.js
var dist_es_exports = {};
__export(dist_es_exports, {
  $Command: () => Command2,
  AssumeRoleCommand: () => AssumeRoleCommand,
  AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
  AssumeRoleWithSAMLCommand: () => AssumeRoleWithSAMLCommand,
  AssumeRoleWithSAMLRequestFilterSensitiveLog: () => AssumeRoleWithSAMLRequestFilterSensitiveLog,
  AssumeRoleWithSAMLResponseFilterSensitiveLog: () => AssumeRoleWithSAMLResponseFilterSensitiveLog,
  AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
  AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
  AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
  CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
  DecodeAuthorizationMessageCommand: () => DecodeAuthorizationMessageCommand,
  ExpiredTokenException: () => ExpiredTokenException,
  GetAccessKeyInfoCommand: () => GetAccessKeyInfoCommand,
  GetCallerIdentityCommand: () => GetCallerIdentityCommand,
  GetFederationTokenCommand: () => GetFederationTokenCommand,
  GetFederationTokenResponseFilterSensitiveLog: () => GetFederationTokenResponseFilterSensitiveLog,
  GetSessionTokenCommand: () => GetSessionTokenCommand,
  GetSessionTokenResponseFilterSensitiveLog: () => GetSessionTokenResponseFilterSensitiveLog,
  IDPCommunicationErrorException: () => IDPCommunicationErrorException,
  IDPRejectedClaimException: () => IDPRejectedClaimException,
  InvalidAuthorizationMessageException: () => InvalidAuthorizationMessageException,
  InvalidIdentityTokenException: () => InvalidIdentityTokenException,
  MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
  PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
  RegionDisabledException: () => RegionDisabledException,
  STS: () => STS,
  STSClient: () => STSClient,
  STSServiceException: () => STSServiceException,
  __Client: () => Client2,
  decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
  getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
  getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
});
var init_dist_es57 = __esm({
  "node_modules/@aws-sdk/client-sts/dist-es/index.js"() {
    init_STSClient();
    init_STS();
    init_commands2();
    init_models2();
    init_defaultRoleAssumers();
    init_STSServiceException();
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/loadSts.js
var loadSts_exports = {};
__export(loadSts_exports, {
  AssumeRoleCommand: () => AssumeRoleCommand,
  STSClient: () => STSClient
});
var init_loadSts = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/loadSts.js"() {
    init_dist_es57();
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js
var fromTemporaryCredentials;
var init_fromTemporaryCredentials = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/fromTemporaryCredentials.js"() {
    init_dist_es();
    fromTemporaryCredentials = (options) => {
      let stsClient;
      return async () => {
        options.logger?.debug("@aws-sdk/credential-providers - fromTemporaryCredentials (STS)");
        const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? "aws-sdk-js-" + Date.now() };
        if (params?.SerialNumber) {
          if (!options.mfaCodeProvider) {
            throw new CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, {
              tryNextLink: false,
              logger: options.logger
            });
          }
          params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber);
        }
        const { AssumeRoleCommand: AssumeRoleCommand2, STSClient: STSClient2 } = await Promise.resolve().then(() => (init_loadSts(), loadSts_exports));
        if (!stsClient)
          stsClient = new STSClient2({ ...options.clientConfig, credentials: options.masterCredentials });
        if (options.clientPlugins) {
          for (const plugin of options.clientPlugins) {
            stsClient.middlewareStack.use(plugin);
          }
        }
        const { Credentials } = await stsClient.send(new AssumeRoleCommand2(params));
        if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
          throw new CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, {
            logger: options.logger
          });
        }
        return {
          accessKeyId: Credentials.AccessKeyId,
          secretAccessKey: Credentials.SecretAccessKey,
          sessionToken: Credentials.SessionToken,
          expiration: Credentials.Expiration,
          credentialScope: Credentials.CredentialScope
        };
      };
    };
  }
});

// (disabled):node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile
var init_fromTokenFile = __esm({
  "(disabled):node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile"() {
  }
});

// node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js
var fromWebToken;
var init_fromWebToken = __esm({
  "node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js"() {
    fromWebToken = (init) => async () => {
      init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
      const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;
      let { roleAssumerWithWebIdentity } = init;
      if (!roleAssumerWithWebIdentity) {
        const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => (init_dist_es57(), dist_es_exports));
        roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
          ...init.clientConfig,
          credentialProviderLogger: init.logger,
          parentClientConfig: init.parentClientConfig
        }, init.clientPlugins);
      }
      return roleAssumerWithWebIdentity({
        RoleArn: roleArn,
        RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
        WebIdentityToken: webIdentityToken,
        ProviderId: providerId,
        PolicyArns: policyArns,
        Policy: policy,
        DurationSeconds: durationSeconds
      });
    };
  }
});

// node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js
var init_dist_es58 = __esm({
  "node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js"() {
    init_fromTokenFile();
    init_fromWebToken();
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js
var fromWebToken2;
var init_fromWebToken2 = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/fromWebToken.js"() {
    init_dist_es58();
    fromWebToken2 = (init) => fromWebToken({
      ...init
    });
  }
});

// node_modules/@aws-sdk/credential-providers/dist-es/index.browser.js
var index_browser_exports = {};
__export(index_browser_exports, {
  fromCognitoIdentity: () => fromCognitoIdentity2,
  fromCognitoIdentityPool: () => fromCognitoIdentityPool2,
  fromHttp: () => fromHttp,
  fromTemporaryCredentials: () => fromTemporaryCredentials,
  fromWebToken: () => fromWebToken2
});
var init_index_browser2 = __esm({
  "node_modules/@aws-sdk/credential-providers/dist-es/index.browser.js"() {
    init_fromCognitoIdentity2();
    init_fromCognitoIdentityPool2();
    init_index_browser();
    init_fromTemporaryCredentials();
    init_fromWebToken2();
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports2 = {};
__export(tslib_es6_exports2, {
  __addDisposableResource: () => __addDisposableResource2,
  __assign: () => __assign2,
  __asyncDelegator: () => __asyncDelegator2,
  __asyncGenerator: () => __asyncGenerator2,
  __asyncValues: () => __asyncValues2,
  __await: () => __await2,
  __awaiter: () => __awaiter2,
  __classPrivateFieldGet: () => __classPrivateFieldGet3,
  __classPrivateFieldIn: () => __classPrivateFieldIn2,
  __classPrivateFieldSet: () => __classPrivateFieldSet3,
  __createBinding: () => __createBinding2,
  __decorate: () => __decorate2,
  __disposeResources: () => __disposeResources2,
  __esDecorate: () => __esDecorate2,
  __exportStar: () => __exportStar2,
  __extends: () => __extends2,
  __generator: () => __generator2,
  __importDefault: () => __importDefault2,
  __importStar: () => __importStar2,
  __makeTemplateObject: () => __makeTemplateObject2,
  __metadata: () => __metadata2,
  __param: () => __param2,
  __propKey: () => __propKey2,
  __read: () => __read2,
  __rest: () => __rest2,
  __runInitializers: () => __runInitializers2,
  __setFunctionName: () => __setFunctionName2,
  __spread: () => __spread2,
  __spreadArray: () => __spreadArray2,
  __spreadArrays: () => __spreadArrays2,
  __values: () => __values3,
  default: () => tslib_es6_default2
});
function __extends2(d3, b3) {
  if (typeof b3 !== "function" && b3 !== null)
    throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
  extendStatics2(d3, b3);
  function __() {
    this.constructor = d3;
  }
  d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
}
function __rest2(s4, e3) {
  var t3 = {};
  for (var p3 in s4)
    if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
      t3[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
      if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
        t3[p3[i3]] = s4[p3[i3]];
    }
  return t3;
}
function __decorate2(decorators, target, key, desc) {
  var c4 = arguments.length, r4 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r4 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d3 = decorators[i3])
        r4 = (c4 < 3 ? d3(r4) : c4 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  return c4 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
}
function __param2(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate2(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f3) {
    if (f3 !== void 0 && typeof f3 !== "function")
      throw new TypeError("Function expected");
    return f3;
  }
  var kind4 = contextIn.kind, key = kind4 === "getter" ? "get" : kind4 === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i3 = decorators.length - 1; i3 >= 0; i3--) {
    var context = {};
    for (var p3 in contextIn)
      context[p3] = p3 === "access" ? {} : contextIn[p3];
    for (var p3 in contextIn.access)
      context.access[p3] = contextIn.access[p3];
    context.addInitializer = function(f3) {
      if (done)
        throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f3 || null));
    };
    var result = (0, decorators[i3])(kind4 === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind4 === "accessor") {
      if (result === void 0)
        continue;
      if (result === null || typeof result !== "object")
        throw new TypeError("Object expected");
      if (_2 = accept(result.get))
        descriptor.get = _2;
      if (_2 = accept(result.set))
        descriptor.set = _2;
      if (_2 = accept(result.init))
        initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind4 === "field")
        initializers.unshift(_2);
      else
        descriptor[key] = _2;
    }
  }
  if (target)
    Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers2(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i3 = 0; i3 < initializers.length; i3++) {
    value = useValue ? initializers[i3].call(thisArg, value) : initializers[i3].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey2(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName2(f3, name, prefix) {
  if (typeof name === "symbol")
    name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f3, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata2(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter2(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e3) {
        reject(e3);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e3) {
        reject(e3);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator2(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t3[0] & 1)
      throw t3[1];
    return t3[1];
  }, trys: [], ops: [] }, f3, y2, t3, g4 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g4.next = verb(0), g4["throw"] = verb(1), g4["return"] = verb(2), typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
    return this;
  }), g4;
  function verb(n4) {
    return function(v5) {
      return step([n4, v5]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
      try {
        if (f3 = 1, y2 && (t3 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t3 = y2["return"]) && t3.call(y2), 0) : y2.next) && !(t3 = t3.call(y2, op[1])).done)
          return t3;
        if (y2 = 0, t3)
          op = [op[0] & 2, t3.value];
        switch (op[0]) {
          case 0:
          case 1:
            t3 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y2 = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t3 = _2.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t3[1]) {
              _2.label = t3[1];
              t3 = op;
              break;
            }
            if (t3 && _2.label < t3[2]) {
              _2.label = t3[2];
              _2.ops.push(op);
              break;
            }
            if (t3[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e3) {
        op = [6, e3];
        y2 = 0;
      } finally {
        f3 = t3 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar2(m3, o3) {
  for (var p3 in m3)
    if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3))
      __createBinding2(o3, m3, p3);
}
function __values3(o3) {
  var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o3[s4], i3 = 0;
  if (m3)
    return m3.call(o3);
  if (o3 && typeof o3.length === "number")
    return {
      next: function() {
        if (o3 && i3 >= o3.length)
          o3 = void 0;
        return { value: o3 && o3[i3++], done: !o3 };
      }
    };
  throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read2(o3, n4) {
  var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
  if (!m3)
    return o3;
  var i3 = m3.call(o3), r4, ar = [], e3;
  try {
    while ((n4 === void 0 || n4-- > 0) && !(r4 = i3.next()).done)
      ar.push(r4.value);
  } catch (error) {
    e3 = { error };
  } finally {
    try {
      if (r4 && !r4.done && (m3 = i3["return"]))
        m3.call(i3);
    } finally {
      if (e3)
        throw e3.error;
    }
  }
  return ar;
}
function __spread2() {
  for (var ar = [], i3 = 0; i3 < arguments.length; i3++)
    ar = ar.concat(__read2(arguments[i3]));
  return ar;
}
function __spreadArrays2() {
  for (var s4 = 0, i3 = 0, il = arguments.length; i3 < il; i3++)
    s4 += arguments[i3].length;
  for (var r4 = Array(s4), k3 = 0, i3 = 0; i3 < il; i3++)
    for (var a3 = arguments[i3], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
      r4[k3] = a3[j3];
  return r4;
}
function __spreadArray2(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i3 = 0, l4 = from.length, ar; i3 < l4; i3++) {
      if (ar || !(i3 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i3);
        ar[i3] = from[i3];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await2(v5) {
  return this instanceof __await2 ? (this.v = v5, this) : new __await2(v5);
}
function __asyncGenerator2(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
  return i3 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function awaitReturn(f3) {
    return function(v5) {
      return Promise.resolve(v5).then(f3, reject);
    };
  }
  function verb(n4, f3) {
    if (g4[n4]) {
      i3[n4] = function(v5) {
        return new Promise(function(a3, b3) {
          q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
        });
      };
      if (f3)
        i3[n4] = f3(i3[n4]);
    }
  }
  function resume(n4, v5) {
    try {
      step(g4[n4](v5));
    } catch (e3) {
      settle(q3[0][3], e3);
    }
  }
  function step(r4) {
    r4.value instanceof __await2 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v5) {
    if (f3(v5), q3.shift(), q3.length)
      resume(q3[0][0], q3[0][1]);
  }
}
function __asyncDelegator2(o3) {
  var i3, p3;
  return i3 = {}, verb("next"), verb("throw", function(e3) {
    throw e3;
  }), verb("return"), i3[Symbol.iterator] = function() {
    return this;
  }, i3;
  function verb(n4, f3) {
    i3[n4] = o3[n4] ? function(v5) {
      return (p3 = !p3) ? { value: __await2(o3[n4](v5)), done: false } : f3 ? f3(v5) : v5;
    } : f3;
  }
}
function __asyncValues2(o3) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i3;
  return m3 ? m3.call(o3) : (o3 = typeof __values3 === "function" ? __values3(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3);
  function verb(n4) {
    i3[n4] = o3[n4] && function(v5) {
      return new Promise(function(resolve, reject) {
        v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
      });
    };
  }
  function settle(resolve, reject, d3, v5) {
    Promise.resolve(v5).then(function(v6) {
      resolve({ value: v6, done: d3 });
    }, reject);
  }
}
function __makeTemplateObject2(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar2(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k3 in mod)
      if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
        __createBinding2(result, mod, k3);
  }
  __setModuleDefault2(result, mod);
  return result;
}
function __importDefault2(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet3(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet3(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn2(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function")
    throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource2(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function")
      throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose)
        throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose)
        throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async)
        inner = dispose;
    }
    if (typeof dispose !== "function")
      throw new TypeError("Object not disposable.");
    if (inner)
      dispose = function() {
        try {
          inner.call(this);
        } catch (e3) {
          return Promise.reject(e3);
        }
      };
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}
function __disposeResources2(env) {
  function fail(e3) {
    env.error = env.hasError ? new _SuppressedError2(e3, env.error, "An error was suppressed during disposal.") : e3;
    env.hasError = true;
  }
  var r4, s4 = 0;
  function next() {
    while (r4 = env.stack.pop()) {
      try {
        if (!r4.async && s4 === 1)
          return s4 = 0, env.stack.push(r4), Promise.resolve().then(next);
        if (r4.dispose) {
          var result = r4.dispose.call(r4.value);
          if (r4.async)
            return s4 |= 2, Promise.resolve(result).then(next, function(e3) {
              fail(e3);
              return next();
            });
        } else
          s4 |= 1;
      } catch (e3) {
        fail(e3);
      }
    }
    if (s4 === 1)
      return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError)
      throw env.error;
  }
  return next();
}
var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2;
var init_tslib_es62 = __esm({
  "node_modules/@aws-sdk/protocol-http/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics2 = function(d3, b3) {
      extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
        d4.__proto__ = b4;
      } || function(d4, b4) {
        for (var p3 in b4)
          if (Object.prototype.hasOwnProperty.call(b4, p3))
            d4[p3] = b4[p3];
      };
      return extendStatics2(d3, b3);
    };
    __assign2 = function() {
      __assign2 = Object.assign || function __assign6(t3) {
        for (var s4, i3 = 1, n4 = arguments.length; i3 < n4; i3++) {
          s4 = arguments[i3];
          for (var p3 in s4)
            if (Object.prototype.hasOwnProperty.call(s4, p3))
              t3[p3] = s4[p3];
        }
        return t3;
      };
      return __assign2.apply(this, arguments);
    };
    __createBinding2 = Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    };
    __setModuleDefault2 = Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    };
    _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e3 = new Error(message);
      return e3.name = "SuppressedError", e3.error = error, e3.suppressed = suppressed, e3;
    };
    tslib_es6_default2 = {
      __extends: __extends2,
      __assign: __assign2,
      __rest: __rest2,
      __decorate: __decorate2,
      __param: __param2,
      __metadata: __metadata2,
      __awaiter: __awaiter2,
      __generator: __generator2,
      __createBinding: __createBinding2,
      __exportStar: __exportStar2,
      __values: __values3,
      __read: __read2,
      __spread: __spread2,
      __spreadArrays: __spreadArrays2,
      __spreadArray: __spreadArray2,
      __await: __await2,
      __asyncGenerator: __asyncGenerator2,
      __asyncDelegator: __asyncDelegator2,
      __asyncValues: __asyncValues2,
      __makeTemplateObject: __makeTemplateObject2,
      __importStar: __importStar2,
      __importDefault: __importDefault2,
      __classPrivateFieldGet: __classPrivateFieldGet3,
      __classPrivateFieldSet: __classPrivateFieldSet3,
      __classPrivateFieldIn: __classPrivateFieldIn2,
      __addDisposableResource: __addDisposableResource2,
      __disposeResources: __disposeResources2
    };
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/abort.js
var require_abort = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/abort.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/auth.js
var require_auth = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/auth.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HttpAuthLocation = void 0;
    var HttpAuthLocation2;
    (function(HttpAuthLocation3) {
      HttpAuthLocation3["HEADER"] = "header";
      HttpAuthLocation3["QUERY"] = "query";
    })(HttpAuthLocation2 = exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/blob/blob-payload-input-types.js
var require_blob_payload_input_types = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/blob/blob-payload-input-types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/checksum.js
var require_checksum = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/checksum.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/client.js
var require_client9 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/client.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/command.js
var require_command = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/command.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/config.js
var require_config = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/config.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/manager.js
var require_manager = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/manager.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/pool.js
var require_pool = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/pool.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/index.js
var require_connection = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/connection/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_config(), exports);
    tslib_1.__exportStar(require_manager(), exports);
    tslib_1.__exportStar(require_pool(), exports);
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/crypto.js
var require_crypto = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/crypto.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/encode.js
var require_encode = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/encode.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoint.js
var require_endpoint = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoint.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EndpointURLScheme = void 0;
    var EndpointURLScheme2;
    (function(EndpointURLScheme3) {
      EndpointURLScheme3["HTTP"] = "http";
      EndpointURLScheme3["HTTPS"] = "https";
    })(EndpointURLScheme2 = exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/EndpointRuleObject.js
var require_EndpointRuleObject = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/EndpointRuleObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/ErrorRuleObject.js
var require_ErrorRuleObject = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/ErrorRuleObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/RuleSetObject.js
var require_RuleSetObject = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/RuleSetObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/shared.js
var require_shared = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/shared.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/TreeRuleObject.js
var require_TreeRuleObject = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/TreeRuleObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/index.js
var require_endpoints = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/endpoints/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_EndpointRuleObject(), exports);
    tslib_1.__exportStar(require_ErrorRuleObject(), exports);
    tslib_1.__exportStar(require_RuleSetObject(), exports);
    tslib_1.__exportStar(require_shared(), exports);
    tslib_1.__exportStar(require_TreeRuleObject(), exports);
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/eventStream.js
var require_eventStream = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/eventStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/http.js
var require_http = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/http.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FieldPosition = void 0;
    var FieldPosition2;
    (function(FieldPosition3) {
      FieldPosition3[FieldPosition3["HEADER"] = 0] = "HEADER";
      FieldPosition3[FieldPosition3["TRAILER"] = 1] = "TRAILER";
    })(FieldPosition2 = exports.FieldPosition || (exports.FieldPosition = {}));
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/awsCredentialIdentity.js
var require_awsCredentialIdentity = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/awsCredentialIdentity.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/identity.js
var require_identity = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/identity.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/index.js
var require_identity2 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/identity/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_awsCredentialIdentity(), exports);
    tslib_1.__exportStar(require_identity(), exports);
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/logger.js
var require_logger = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/logger.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/middleware.js
var require_middleware = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/middleware.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/pagination.js
var require_pagination = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/pagination.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/profile.js
var require_profile = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/profile.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/response.js
var require_response = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/response.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/retry.js
var require_retry3 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/retry.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/serde.js
var require_serde = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/serde.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/shapes.js
var require_shapes = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/shapes.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/signature.js
var require_signature = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/signature.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/stream.js
var require_stream = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/stream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-common-types.js
var require_streaming_blob_common_types = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-common-types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-payload-input-types.js
var require_streaming_blob_payload_input_types = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-payload-input-types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-payload-output-types.js
var require_streaming_blob_payload_output_types = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/streaming-payload/streaming-blob-payload-output-types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transfer.js
var require_transfer = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transfer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RequestHandlerProtocol = void 0;
    var RequestHandlerProtocol2;
    (function(RequestHandlerProtocol3) {
      RequestHandlerProtocol3["HTTP_0_9"] = "http/0.9";
      RequestHandlerProtocol3["HTTP_1_0"] = "http/1.0";
      RequestHandlerProtocol3["TDS_8_0"] = "tds/8.0";
    })(RequestHandlerProtocol2 = exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transform/client-payload-blob-type-narrow.js
var require_client_payload_blob_type_narrow = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transform/client-payload-blob-type-narrow.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transform/type-transform.js
var require_type_transform = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/transform/type-transform.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/uri.js
var require_uri = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/uri.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/util.js
var require_util2 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/util.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/waiter.js
var require_waiter = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/waiter.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/index.js
var require_dist_cjs4 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_abort(), exports);
    tslib_1.__exportStar(require_auth(), exports);
    tslib_1.__exportStar(require_blob_payload_input_types(), exports);
    tslib_1.__exportStar(require_checksum(), exports);
    tslib_1.__exportStar(require_client9(), exports);
    tslib_1.__exportStar(require_command(), exports);
    tslib_1.__exportStar(require_connection(), exports);
    tslib_1.__exportStar(require_crypto(), exports);
    tslib_1.__exportStar(require_encode(), exports);
    tslib_1.__exportStar(require_endpoint(), exports);
    tslib_1.__exportStar(require_endpoints(), exports);
    tslib_1.__exportStar(require_eventStream(), exports);
    tslib_1.__exportStar(require_http(), exports);
    tslib_1.__exportStar(require_identity2(), exports);
    tslib_1.__exportStar(require_logger(), exports);
    tslib_1.__exportStar(require_middleware(), exports);
    tslib_1.__exportStar(require_pagination(), exports);
    tslib_1.__exportStar(require_profile(), exports);
    tslib_1.__exportStar(require_response(), exports);
    tslib_1.__exportStar(require_retry3(), exports);
    tslib_1.__exportStar(require_serde(), exports);
    tslib_1.__exportStar(require_shapes(), exports);
    tslib_1.__exportStar(require_signature(), exports);
    tslib_1.__exportStar(require_stream(), exports);
    tslib_1.__exportStar(require_streaming_blob_common_types(), exports);
    tslib_1.__exportStar(require_streaming_blob_payload_input_types(), exports);
    tslib_1.__exportStar(require_streaming_blob_payload_output_types(), exports);
    tslib_1.__exportStar(require_transfer(), exports);
    tslib_1.__exportStar(require_client_payload_blob_type_narrow(), exports);
    tslib_1.__exportStar(require_type_transform(), exports);
    tslib_1.__exportStar(require_uri(), exports);
    tslib_1.__exportStar(require_util2(), exports);
    tslib_1.__exportStar(require_waiter(), exports);
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/Field.js
var require_Field = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/Field.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Field = void 0;
    var types_1 = require_dist_cjs4();
    var Field = class {
      constructor({ name, kind: kind4 = types_1.FieldPosition.HEADER, values = [] }) {
        this.name = name;
        this.kind = kind4;
        this.values = values;
      }
      add(value) {
        this.values.push(value);
      }
      set(values) {
        this.values = values;
      }
      remove(value) {
        this.values = this.values.filter((v5) => v5 !== value);
      }
      toString() {
        return this.values.map((v5) => v5.includes(",") || v5.includes(" ") ? `"${v5}"` : v5).join(", ");
      }
      get() {
        return this.values;
      }
    };
    exports.Field = Field;
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/Fields.js
var require_Fields = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/Fields.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Fields = void 0;
    var Fields = class {
      constructor({ fields = [], encoding = "utf-8" }) {
        this.entries = {};
        fields.forEach(this.setField.bind(this));
        this.encoding = encoding;
      }
      setField(field) {
        this.entries[field.name.toLowerCase()] = field;
      }
      getField(name) {
        return this.entries[name.toLowerCase()];
      }
      removeField(name) {
        delete this.entries[name.toLowerCase()];
      }
      getByType(kind4) {
        return Object.values(this.entries).filter((field) => field.kind === kind4);
      }
    };
    exports.Fields = Fields;
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpHandler.js
var require_httpHandler = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpHandler.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpRequest.js
var require_httpRequest = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpRequest.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HttpRequest = void 0;
    var HttpRequest11 = class {
      constructor(options) {
        this.method = options.method || "GET";
        this.hostname = options.hostname || "localhost";
        this.port = options.port;
        this.query = options.query || {};
        this.headers = options.headers || {};
        this.body = options.body;
        this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
        this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
        this.username = options.username;
        this.password = options.password;
        this.fragment = options.fragment;
      }
      static isInstance(request) {
        if (!request)
          return false;
        const req = request;
        return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
      }
      clone() {
        const cloned = new HttpRequest11({
          ...this,
          headers: { ...this.headers }
        });
        if (cloned.query)
          cloned.query = cloneQuery11(cloned.query);
        return cloned;
      }
    };
    exports.HttpRequest = HttpRequest11;
    function cloneQuery11(query) {
      return Object.keys(query).reduce((carry, paramName) => {
        const param = query[paramName];
        return {
          ...carry,
          [paramName]: Array.isArray(param) ? [...param] : param
        };
      }, {});
    }
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpResponse.js
var require_httpResponse = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/httpResponse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HttpResponse = void 0;
    var HttpResponse4 = class {
      constructor(options) {
        this.statusCode = options.statusCode;
        this.reason = options.reason;
        this.headers = options.headers || {};
        this.body = options.body;
      }
      static isInstance(response) {
        if (!response)
          return false;
        const resp = response;
        return typeof resp.statusCode === "number" && typeof resp.headers === "object";
      }
    };
    exports.HttpResponse = HttpResponse4;
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/isValidHostname.js
var require_isValidHostname = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/isValidHostname.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isValidHostname = void 0;
    function isValidHostname(hostname) {
      const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
      return hostPattern.test(hostname);
    }
    exports.isValidHostname = isValidHostname;
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/types.js
var require_types6 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/index.js
var require_dist_cjs5 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_Field(), exports);
    tslib_1.__exportStar(require_Fields(), exports);
    tslib_1.__exportStar(require_httpHandler(), exports);
    tslib_1.__exportStar(require_httpRequest(), exports);
    tslib_1.__exportStar(require_httpResponse(), exports);
    tslib_1.__exportStar(require_isValidHostname(), exports);
    tslib_1.__exportStar(require_types6(), exports);
  }
});

// node_modules/@aws-sdk/protocol-http/dist-cjs/index.js
var require_dist_cjs6 = __commonJS({
  "node_modules/@aws-sdk/protocol-http/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2));
    tslib_1.__exportStar(require_dist_cjs5(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports3 = {};
__export(tslib_es6_exports3, {
  __addDisposableResource: () => __addDisposableResource3,
  __assign: () => __assign3,
  __asyncDelegator: () => __asyncDelegator3,
  __asyncGenerator: () => __asyncGenerator3,
  __asyncValues: () => __asyncValues3,
  __await: () => __await3,
  __awaiter: () => __awaiter3,
  __classPrivateFieldGet: () => __classPrivateFieldGet4,
  __classPrivateFieldIn: () => __classPrivateFieldIn3,
  __classPrivateFieldSet: () => __classPrivateFieldSet4,
  __createBinding: () => __createBinding3,
  __decorate: () => __decorate3,
  __disposeResources: () => __disposeResources3,
  __esDecorate: () => __esDecorate3,
  __exportStar: () => __exportStar3,
  __extends: () => __extends3,
  __generator: () => __generator3,
  __importDefault: () => __importDefault3,
  __importStar: () => __importStar3,
  __makeTemplateObject: () => __makeTemplateObject3,
  __metadata: () => __metadata3,
  __param: () => __param3,
  __propKey: () => __propKey3,
  __read: () => __read3,
  __rest: () => __rest3,
  __runInitializers: () => __runInitializers3,
  __setFunctionName: () => __setFunctionName3,
  __spread: () => __spread3,
  __spreadArray: () => __spreadArray3,
  __spreadArrays: () => __spreadArrays3,
  __values: () => __values4,
  default: () => tslib_es6_default3
});
function __extends3(d3, b3) {
  if (typeof b3 !== "function" && b3 !== null)
    throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
  extendStatics3(d3, b3);
  function __() {
    this.constructor = d3;
  }
  d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
}
function __rest3(s4, e3) {
  var t3 = {};
  for (var p3 in s4)
    if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
      t3[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
      if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
        t3[p3[i3]] = s4[p3[i3]];
    }
  return t3;
}
function __decorate3(decorators, target, key, desc) {
  var c4 = arguments.length, r4 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r4 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d3 = decorators[i3])
        r4 = (c4 < 3 ? d3(r4) : c4 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  return c4 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
}
function __param3(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate3(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f3) {
    if (f3 !== void 0 && typeof f3 !== "function")
      throw new TypeError("Function expected");
    return f3;
  }
  var kind4 = contextIn.kind, key = kind4 === "getter" ? "get" : kind4 === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _2, done = false;
  for (var i3 = decorators.length - 1; i3 >= 0; i3--) {
    var context = {};
    for (var p3 in contextIn)
      context[p3] = p3 === "access" ? {} : contextIn[p3];
    for (var p3 in contextIn.access)
      context.access[p3] = contextIn.access[p3];
    context.addInitializer = function(f3) {
      if (done)
        throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f3 || null));
    };
    var result = (0, decorators[i3])(kind4 === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind4 === "accessor") {
      if (result === void 0)
        continue;
      if (result === null || typeof result !== "object")
        throw new TypeError("Object expected");
      if (_2 = accept(result.get))
        descriptor.get = _2;
      if (_2 = accept(result.set))
        descriptor.set = _2;
      if (_2 = accept(result.init))
        initializers.unshift(_2);
    } else if (_2 = accept(result)) {
      if (kind4 === "field")
        initializers.unshift(_2);
      else
        descriptor[key] = _2;
    }
  }
  if (target)
    Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers3(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i3 = 0; i3 < initializers.length; i3++) {
    value = useValue ? initializers[i3].call(thisArg, value) : initializers[i3].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey3(x2) {
  return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName3(f3, name, prefix) {
  if (typeof name === "symbol")
    name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f3, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata3(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter3(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e3) {
        reject(e3);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e3) {
        reject(e3);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator3(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t3[0] & 1)
      throw t3[1];
    return t3[1];
  }, trys: [], ops: [] }, f3, y2, t3, g4 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g4.next = verb(0), g4["throw"] = verb(1), g4["return"] = verb(2), typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
    return this;
  }), g4;
  function verb(n4) {
    return function(v5) {
      return step([n4, v5]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
      try {
        if (f3 = 1, y2 && (t3 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t3 = y2["return"]) && t3.call(y2), 0) : y2.next) && !(t3 = t3.call(y2, op[1])).done)
          return t3;
        if (y2 = 0, t3)
          op = [op[0] & 2, t3.value];
        switch (op[0]) {
          case 0:
          case 1:
            t3 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y2 = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t3 = _2.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t3[1]) {
              _2.label = t3[1];
              t3 = op;
              break;
            }
            if (t3 && _2.label < t3[2]) {
              _2.label = t3[2];
              _2.ops.push(op);
              break;
            }
            if (t3[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e3) {
        op = [6, e3];
        y2 = 0;
      } finally {
        f3 = t3 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar3(m3, o3) {
  for (var p3 in m3)
    if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3))
      __createBinding3(o3, m3, p3);
}
function __values4(o3) {
  var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o3[s4], i3 = 0;
  if (m3)
    return m3.call(o3);
  if (o3 && typeof o3.length === "number")
    return {
      next: function() {
        if (o3 && i3 >= o3.length)
          o3 = void 0;
        return { value: o3 && o3[i3++], done: !o3 };
      }
    };
  throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read3(o3, n4) {
  var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
  if (!m3)
    return o3;
  var i3 = m3.call(o3), r4, ar = [], e3;
  try {
    while ((n4 === void 0 || n4-- > 0) && !(r4 = i3.next()).done)
      ar.push(r4.value);
  } catch (error) {
    e3 = { error };
  } finally {
    try {
      if (r4 && !r4.done && (m3 = i3["return"]))
        m3.call(i3);
    } finally {
      if (e3)
        throw e3.error;
    }
  }
  return ar;
}
function __spread3() {
  for (var ar = [], i3 = 0; i3 < arguments.length; i3++)
    ar = ar.concat(__read3(arguments[i3]));
  return ar;
}
function __spreadArrays3() {
  for (var s4 = 0, i3 = 0, il = arguments.length; i3 < il; i3++)
    s4 += arguments[i3].length;
  for (var r4 = Array(s4), k3 = 0, i3 = 0; i3 < il; i3++)
    for (var a3 = arguments[i3], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
      r4[k3] = a3[j3];
  return r4;
}
function __spreadArray3(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i3 = 0, l4 = from.length, ar; i3 < l4; i3++) {
      if (ar || !(i3 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i3);
        ar[i3] = from[i3];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await3(v5) {
  return this instanceof __await3 ? (this.v = v5, this) : new __await3(v5);
}
function __asyncGenerator3(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
  return i3 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function awaitReturn(f3) {
    return function(v5) {
      return Promise.resolve(v5).then(f3, reject);
    };
  }
  function verb(n4, f3) {
    if (g4[n4]) {
      i3[n4] = function(v5) {
        return new Promise(function(a3, b3) {
          q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
        });
      };
      if (f3)
        i3[n4] = f3(i3[n4]);
    }
  }
  function resume(n4, v5) {
    try {
      step(g4[n4](v5));
    } catch (e3) {
      settle(q3[0][3], e3);
    }
  }
  function step(r4) {
    r4.value instanceof __await3 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v5) {
    if (f3(v5), q3.shift(), q3.length)
      resume(q3[0][0], q3[0][1]);
  }
}
function __asyncDelegator3(o3) {
  var i3, p3;
  return i3 = {}, verb("next"), verb("throw", function(e3) {
    throw e3;
  }), verb("return"), i3[Symbol.iterator] = function() {
    return this;
  }, i3;
  function verb(n4, f3) {
    i3[n4] = o3[n4] ? function(v5) {
      return (p3 = !p3) ? { value: __await3(o3[n4](v5)), done: false } : f3 ? f3(v5) : v5;
    } : f3;
  }
}
function __asyncValues3(o3) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i3;
  return m3 ? m3.call(o3) : (o3 = typeof __values4 === "function" ? __values4(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3);
  function verb(n4) {
    i3[n4] = o3[n4] && function(v5) {
      return new Promise(function(resolve, reject) {
        v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
      });
    };
  }
  function settle(resolve, reject, d3, v5) {
    Promise.resolve(v5).then(function(v6) {
      resolve({ value: v6, done: d3 });
    }, reject);
  }
}
function __makeTemplateObject3(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar3(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k3 in mod)
      if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
        __createBinding3(result, mod, k3);
  }
  __setModuleDefault3(result, mod);
  return result;
}
function __importDefault3(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet4(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
}
function __classPrivateFieldSet4(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn3(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function")
    throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource3(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function")
      throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose)
        throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose)
        throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async)
        inner = dispose;
    }
    if (typeof dispose !== "function")
      throw new TypeError("Object not disposable.");
    if (inner)
      dispose = function() {
        try {
          inner.call(this);
        } catch (e3) {
          return Promise.reject(e3);
        }
      };
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}
function __disposeResources3(env) {
  function fail(e3) {
    env.error = env.hasError ? new _SuppressedError3(e3, env.error, "An error was suppressed during disposal.") : e3;
    env.hasError = true;
  }
  var r4, s4 = 0;
  function next() {
    while (r4 = env.stack.pop()) {
      try {
        if (!r4.async && s4 === 1)
          return s4 = 0, env.stack.push(r4), Promise.resolve().then(next);
        if (r4.dispose) {
          var result = r4.dispose.call(r4.value);
          if (r4.async)
            return s4 |= 2, Promise.resolve(result).then(next, function(e3) {
              fail(e3);
              return next();
            });
        } else
          s4 |= 1;
      } catch (e3) {
        fail(e3);
      }
    }
    if (s4 === 1)
      return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError)
      throw env.error;
  }
  return next();
}
var extendStatics3, __assign3, __createBinding3, __setModuleDefault3, _SuppressedError3, tslib_es6_default3;
var init_tslib_es63 = __esm({
  "node_modules/@aws-sdk/signature-v4/node_modules/tslib/tslib.es6.mjs"() {
    extendStatics3 = function(d3, b3) {
      extendStatics3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
        d4.__proto__ = b4;
      } || function(d4, b4) {
        for (var p3 in b4)
          if (Object.prototype.hasOwnProperty.call(b4, p3))
            d4[p3] = b4[p3];
      };
      return extendStatics3(d3, b3);
    };
    __assign3 = function() {
      __assign3 = Object.assign || function __assign6(t3) {
        for (var s4, i3 = 1, n4 = arguments.length; i3 < n4; i3++) {
          s4 = arguments[i3];
          for (var p3 in s4)
            if (Object.prototype.hasOwnProperty.call(s4, p3))
              t3[p3] = s4[p3];
        }
        return t3;
      };
      return __assign3.apply(this, arguments);
    };
    __createBinding3 = Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    };
    __setModuleDefault3 = Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    };
    _SuppressedError3 = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e3 = new Error(message);
      return e3.name = "SuppressedError", e3.error = error, e3.suppressed = suppressed, e3;
    };
    tslib_es6_default3 = {
      __extends: __extends3,
      __assign: __assign3,
      __rest: __rest3,
      __decorate: __decorate3,
      __param: __param3,
      __metadata: __metadata3,
      __awaiter: __awaiter3,
      __generator: __generator3,
      __createBinding: __createBinding3,
      __exportStar: __exportStar3,
      __values: __values4,
      __read: __read3,
      __spread: __spread3,
      __spreadArrays: __spreadArrays3,
      __spreadArray: __spreadArray3,
      __await: __await3,
      __asyncGenerator: __asyncGenerator3,
      __asyncDelegator: __asyncDelegator3,
      __asyncValues: __asyncValues3,
      __makeTemplateObject: __makeTemplateObject3,
      __importStar: __importStar3,
      __importDefault: __importDefault3,
      __classPrivateFieldGet: __classPrivateFieldGet4,
      __classPrivateFieldSet: __classPrivateFieldSet4,
      __classPrivateFieldIn: __classPrivateFieldIn3,
      __addDisposableResource: __addDisposableResource3,
      __disposeResources: __disposeResources3
    };
  }
});

// node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.es6.js
var tslib_es6_exports4 = {};
__export(tslib_es6_exports4, {
  __assign: () => __assign4,
  __asyncDelegator: () => __asyncDelegator4,
  __asyncGenerator: () => __asyncGenerator4,
  __asyncValues: () => __asyncValues4,
  __await: () => __await4,
  __awaiter: () => __awaiter4,
  __classPrivateFieldGet: () => __classPrivateFieldGet5,
  __classPrivateFieldSet: () => __classPrivateFieldSet5,
  __createBinding: () => __createBinding4,
  __decorate: () => __decorate4,
  __exportStar: () => __exportStar4,
  __extends: () => __extends4,
  __generator: () => __generator4,
  __importDefault: () => __importDefault4,
  __importStar: () => __importStar4,
  __makeTemplateObject: () => __makeTemplateObject4,
  __metadata: () => __metadata4,
  __param: () => __param4,
  __read: () => __read4,
  __rest: () => __rest4,
  __spread: () => __spread4,
  __spreadArrays: () => __spreadArrays4,
  __values: () => __values5
});
function __extends4(d3, b3) {
  extendStatics4(d3, b3);
  function __() {
    this.constructor = d3;
  }
  d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
}
function __rest4(s4, e3) {
  var t3 = {};
  for (var p3 in s4)
    if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
      t3[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
      if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
        t3[p3[i3]] = s4[p3[i3]];
    }
  return t3;
}
function __decorate4(decorators, target, key, desc) {
  var c4 = arguments.length, r4 = c4 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r4 = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i3 = decorators.length - 1; i3 >= 0; i3--)
      if (d3 = decorators[i3])
        r4 = (c4 < 3 ? d3(r4) : c4 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  return c4 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
}
function __param4(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __metadata4(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter4(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e3) {
        reject(e3);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e3) {
        reject(e3);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator4(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t3[0] & 1)
      throw t3[1];
    return t3[1];
  }, trys: [], ops: [] }, f3, y2, t3, g4;
  return g4 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() {
    return this;
  }), g4;
  function verb(n4) {
    return function(v5) {
      return step([n4, v5]);
    };
  }
  function step(op) {
    if (f3)
      throw new TypeError("Generator is already executing.");
    while (_2)
      try {
        if (f3 = 1, y2 && (t3 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t3 = y2["return"]) && t3.call(y2), 0) : y2.next) && !(t3 = t3.call(y2, op[1])).done)
          return t3;
        if (y2 = 0, t3)
          op = [op[0] & 2, t3.value];
        switch (op[0]) {
          case 0:
          case 1:
            t3 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y2 = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t3 = _2.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t3[1]) {
              _2.label = t3[1];
              t3 = op;
              break;
            }
            if (t3 && _2.label < t3[2]) {
              _2.label = t3[2];
              _2.ops.push(op);
              break;
            }
            if (t3[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e3) {
        op = [6, e3];
        y2 = 0;
      } finally {
        f3 = t3 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __createBinding4(o3, m3, k3, k22) {
  if (k22 === void 0)
    k22 = k3;
  o3[k22] = m3[k3];
}
function __exportStar4(m3, exports) {
  for (var p3 in m3)
    if (p3 !== "default" && !exports.hasOwnProperty(p3))
      exports[p3] = m3[p3];
}
function __values5(o3) {
  var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o3[s4], i3 = 0;
  if (m3)
    return m3.call(o3);
  if (o3 && typeof o3.length === "number")
    return {
      next: function() {
        if (o3 && i3 >= o3.length)
          o3 = void 0;
        return { value: o3 && o3[i3++], done: !o3 };
      }
    };
  throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read4(o3, n4) {
  var m3 = typeof Symbol === "function" && o3[Symbol.iterator];
  if (!m3)
    return o3;
  var i3 = m3.call(o3), r4, ar = [], e3;
  try {
    while ((n4 === void 0 || n4-- > 0) && !(r4 = i3.next()).done)
      ar.push(r4.value);
  } catch (error) {
    e3 = { error };
  } finally {
    try {
      if (r4 && !r4.done && (m3 = i3["return"]))
        m3.call(i3);
    } finally {
      if (e3)
        throw e3.error;
    }
  }
  return ar;
}
function __spread4() {
  for (var ar = [], i3 = 0; i3 < arguments.length; i3++)
    ar = ar.concat(__read4(arguments[i3]));
  return ar;
}
function __spreadArrays4() {
  for (var s4 = 0, i3 = 0, il = arguments.length; i3 < il; i3++)
    s4 += arguments[i3].length;
  for (var r4 = Array(s4), k3 = 0, i3 = 0; i3 < il; i3++)
    for (var a3 = arguments[i3], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
      r4[k3] = a3[j3];
  return r4;
}
function __await4(v5) {
  return this instanceof __await4 ? (this.v = v5, this) : new __await4(v5);
}
function __asyncGenerator4(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
  return i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function verb(n4) {
    if (g4[n4])
      i3[n4] = function(v5) {
        return new Promise(function(a3, b3) {
          q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
        });
      };
  }
  function resume(n4, v5) {
    try {
      step(g4[n4](v5));
    } catch (e3) {
      settle(q3[0][3], e3);
    }
  }
  function step(r4) {
    r4.value instanceof __await4 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v5) {
    if (f3(v5), q3.shift(), q3.length)
      resume(q3[0][0], q3[0][1]);
  }
}
function __asyncDelegator4(o3) {
  var i3, p3;
  return i3 = {}, verb("next"), verb("throw", function(e3) {
    throw e3;
  }), verb("return"), i3[Symbol.iterator] = function() {
    return this;
  }, i3;
  function verb(n4, f3) {
    i3[n4] = o3[n4] ? function(v5) {
      return (p3 = !p3) ? { value: __await4(o3[n4](v5)), done: n4 === "return" } : f3 ? f3(v5) : v5;
    } : f3;
  }
}
function __asyncValues4(o3) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i3;
  return m3 ? m3.call(o3) : (o3 = typeof __values5 === "function" ? __values5(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3);
  function verb(n4) {
    i3[n4] = o3[n4] && function(v5) {
      return new Promise(function(resolve, reject) {
        v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
      });
    };
  }
  function settle(resolve, reject, d3, v5) {
    Promise.resolve(v5).then(function(v6) {
      resolve({ value: v6, done: d3 });
    }, reject);
  }
}
function __makeTemplateObject4(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar4(mod) {
  if (mod && mod.__esModule)
    return mod;
  var result = {};
  if (mod != null) {
    for (var k3 in mod)
      if (Object.hasOwnProperty.call(mod, k3))
        result[k3] = mod[k3];
  }
  result.default = mod;
  return result;
}
function __importDefault4(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet5(receiver, privateMap) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to get private field on non-instance");
  }
  return privateMap.get(receiver);
}
function __classPrivateFieldSet5(receiver, privateMap, value) {
  if (!privateMap.has(receiver)) {
    throw new TypeError("attempted to set private field on non-instance");
  }
  privateMap.set(receiver, value);
  return value;
}
var extendStatics4, __assign4;
var init_tslib_es64 = __esm({
  "node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.es6.js"() {
    extendStatics4 = function(d3, b3) {
      extendStatics4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
        d4.__proto__ = b4;
      } || function(d4, b4) {
        for (var p3 in b4)
          if (b4.hasOwnProperty(p3))
            d4[p3] = b4[p3];
      };
      return extendStatics4(d3, b3);
    };
    __assign4 = function() {
      __assign4 = Object.assign || function __assign6(t3) {
        for (var s4, i3 = 1, n4 = arguments.length; i3 < n4; i3++) {
          s4 = arguments[i3];
          for (var p3 in s4)
            if (Object.prototype.hasOwnProperty.call(s4, p3))
              t3[p3] = s4[p3];
        }
        return t3;
      };
      return __assign4.apply(this, arguments);
    };
  }
});

// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js
var require_pureJs = __commonJS({
  "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUtf8 = exports.fromUtf8 = void 0;
    var fromUtf86 = (input) => {
      const bytes = [];
      for (let i3 = 0, len = input.length; i3 < len; i3++) {
        const value = input.charCodeAt(i3);
        if (value < 128) {
          bytes.push(value);
        } else if (value < 2048) {
          bytes.push(value >> 6 | 192, value & 63 | 128);
        } else if (i3 + 1 < input.length && (value & 64512) === 55296 && (input.charCodeAt(i3 + 1) & 64512) === 56320) {
          const surrogatePair = 65536 + ((value & 1023) << 10) + (input.charCodeAt(++i3) & 1023);
          bytes.push(surrogatePair >> 18 | 240, surrogatePair >> 12 & 63 | 128, surrogatePair >> 6 & 63 | 128, surrogatePair & 63 | 128);
        } else {
          bytes.push(value >> 12 | 224, value >> 6 & 63 | 128, value & 63 | 128);
        }
      }
      return Uint8Array.from(bytes);
    };
    exports.fromUtf8 = fromUtf86;
    var toUtf84 = (input) => {
      let decoded = "";
      for (let i3 = 0, len = input.length; i3 < len; i3++) {
        const byte = input[i3];
        if (byte < 128) {
          decoded += String.fromCharCode(byte);
        } else if (192 <= byte && byte < 224) {
          const nextByte = input[++i3];
          decoded += String.fromCharCode((byte & 31) << 6 | nextByte & 63);
        } else if (240 <= byte && byte < 365) {
          const surrogatePair = [byte, input[++i3], input[++i3], input[++i3]];
          const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%");
          decoded += decodeURIComponent(encoded);
        } else {
          decoded += String.fromCharCode((byte & 15) << 12 | (input[++i3] & 63) << 6 | input[++i3] & 63);
        }
      }
      return decoded;
    };
    exports.toUtf8 = toUtf84;
  }
});

// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js
var require_whatwgEncodingApi = __commonJS({
  "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUtf8 = exports.fromUtf8 = void 0;
    function fromUtf86(input) {
      return new TextEncoder().encode(input);
    }
    exports.fromUtf8 = fromUtf86;
    function toUtf84(input) {
      return new TextDecoder("utf-8").decode(input);
    }
    exports.toUtf8 = toUtf84;
  }
});

// node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js
var require_dist_cjs7 = __commonJS({
  "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUtf8 = exports.fromUtf8 = void 0;
    var pureJs_1 = require_pureJs();
    var whatwgEncodingApi_1 = require_whatwgEncodingApi();
    var fromUtf86 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input);
    exports.fromUtf8 = fromUtf86;
    var toUtf84 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input);
    exports.toUtf8 = toUtf84;
  }
});

// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js
var require_convertToBuffer2 = __commonJS({
  "node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.convertToBuffer = void 0;
    var util_utf8_browser_1 = require_dist_cjs7();
    var fromUtf86 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
      return Buffer.from(input, "utf8");
    } : util_utf8_browser_1.fromUtf8;
    function convertToBuffer3(data) {
      if (data instanceof Uint8Array)
        return data;
      if (typeof data === "string") {
        return fromUtf86(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    }
    exports.convertToBuffer = convertToBuffer3;
  }
});

// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js
var require_isEmptyData2 = __commonJS({
  "node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isEmptyData = void 0;
    function isEmptyData2(data) {
      if (typeof data === "string") {
        return data.length === 0;
      }
      return data.byteLength === 0;
    }
    exports.isEmptyData = isEmptyData2;
  }
});

// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js
var require_numToUint82 = __commonJS({
  "node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.numToUint8 = void 0;
    function numToUint8(num) {
      return new Uint8Array([
        (num & 4278190080) >> 24,
        (num & 16711680) >> 16,
        (num & 65280) >> 8,
        num & 255
      ]);
    }
    exports.numToUint8 = numToUint8;
  }
});

// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js
var require_uint32ArrayFrom2 = __commonJS({
  "node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.uint32ArrayFrom = void 0;
    function uint32ArrayFrom(a_lookUpTable) {
      if (!Uint32Array.from) {
        var return_array = new Uint32Array(a_lookUpTable.length);
        var a_index = 0;
        while (a_index < a_lookUpTable.length) {
          return_array[a_index] = a_lookUpTable[a_index];
          a_index += 1;
        }
        return return_array;
      }
      return Uint32Array.from(a_lookUpTable);
    }
    exports.uint32ArrayFrom = uint32ArrayFrom;
  }
});

// node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js
var require_build = __commonJS({
  "node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0;
    var convertToBuffer_1 = require_convertToBuffer2();
    Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() {
      return convertToBuffer_1.convertToBuffer;
    } });
    var isEmptyData_1 = require_isEmptyData2();
    Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() {
      return isEmptyData_1.isEmptyData;
    } });
    var numToUint8_1 = require_numToUint82();
    Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() {
      return numToUint8_1.numToUint8;
    } });
    var uint32ArrayFrom_1 = require_uint32ArrayFrom2();
    Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() {
      return uint32ArrayFrom_1.uint32ArrayFrom;
    } });
  }
});

// node_modules/@aws-crypto/crc32/build/aws_crc32.js
var require_aws_crc32 = __commonJS({
  "node_modules/@aws-crypto/crc32/build/aws_crc32.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AwsCrc32 = void 0;
    var tslib_1 = (init_tslib_es64(), __toCommonJS(tslib_es6_exports4));
    var util_1 = require_build();
    var index_1 = require_build2();
    var AwsCrc32 = (
      /** @class */
      function() {
        function AwsCrc322() {
          this.crc32 = new index_1.Crc32();
        }
        AwsCrc322.prototype.update = function(toHash) {
          if ((0, util_1.isEmptyData)(toHash))
            return;
          this.crc32.update((0, util_1.convertToBuffer)(toHash));
        };
        AwsCrc322.prototype.digest = function() {
          return tslib_1.__awaiter(this, void 0, void 0, function() {
            return tslib_1.__generator(this, function(_a5) {
              return [2, (0, util_1.numToUint8)(this.crc32.digest())];
            });
          });
        };
        AwsCrc322.prototype.reset = function() {
          this.crc32 = new index_1.Crc32();
        };
        return AwsCrc322;
      }()
    );
    exports.AwsCrc32 = AwsCrc32;
  }
});

// node_modules/@aws-crypto/crc32/build/index.js
var require_build2 = __commonJS({
  "node_modules/@aws-crypto/crc32/build/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0;
    var tslib_1 = (init_tslib_es64(), __toCommonJS(tslib_es6_exports4));
    var util_1 = require_build();
    function crc32(data) {
      return new Crc32().update(data).digest();
    }
    exports.crc32 = crc32;
    var Crc32 = (
      /** @class */
      function() {
        function Crc322() {
          this.checksum = 4294967295;
        }
        Crc322.prototype.update = function(data) {
          var e_1, _a5;
          try {
            for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
              var byte = data_1_1.value;
              this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255];
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (data_1_1 && !data_1_1.done && (_a5 = data_1.return))
                _a5.call(data_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
          return this;
        };
        Crc322.prototype.digest = function() {
          return (this.checksum ^ 4294967295) >>> 0;
        };
        return Crc322;
      }()
    );
    exports.Crc32 = Crc32;
    var a_lookUpTable = [
      0,
      1996959894,
      3993919788,
      2567524794,
      124634137,
      1886057615,
      3915621685,
      2657392035,
      249268274,
      2044508324,
      3772115230,
      2547177864,
      162941995,
      2125561021,
      3887607047,
      2428444049,
      498536548,
      1789927666,
      4089016648,
      2227061214,
      450548861,
      1843258603,
      4107580753,
      2211677639,
      325883990,
      1684777152,
      4251122042,
      2321926636,
      335633487,
      1661365465,
      4195302755,
      2366115317,
      997073096,
      1281953886,
      3579855332,
      2724688242,
      1006888145,
      1258607687,
      3524101629,
      2768942443,
      901097722,
      1119000684,
      3686517206,
      2898065728,
      853044451,
      1172266101,
      3705015759,
      2882616665,
      651767980,
      1373503546,
      3369554304,
      3218104598,
      565507253,
      1454621731,
      3485111705,
      3099436303,
      671266974,
      1594198024,
      3322730930,
      2970347812,
      795835527,
      1483230225,
      3244367275,
      3060149565,
      1994146192,
      31158534,
      2563907772,
      4023717930,
      1907459465,
      112637215,
      2680153253,
      3904427059,
      2013776290,
      251722036,
      2517215374,
      3775830040,
      2137656763,
      141376813,
      2439277719,
      3865271297,
      1802195444,
      476864866,
      2238001368,
      4066508878,
      1812370925,
      453092731,
      2181625025,
      4111451223,
      1706088902,
      314042704,
      2344532202,
      4240017532,
      1658658271,
      366619977,
      2362670323,
      4224994405,
      1303535960,
      984961486,
      2747007092,
      3569037538,
      1256170817,
      1037604311,
      2765210733,
      3554079995,
      1131014506,
      879679996,
      2909243462,
      3663771856,
      1141124467,
      855842277,
      2852801631,
      3708648649,
      1342533948,
      654459306,
      3188396048,
      3373015174,
      1466479909,
      544179635,
      3110523913,
      3462522015,
      1591671054,
      702138776,
      2966460450,
      3352799412,
      1504918807,
      783551873,
      3082640443,
      3233442989,
      3988292384,
      2596254646,
      62317068,
      1957810842,
      3939845945,
      2647816111,
      81470997,
      1943803523,
      3814918930,
      2489596804,
      225274430,
      2053790376,
      3826175755,
      2466906013,
      167816743,
      2097651377,
      4027552580,
      2265490386,
      503444072,
      1762050814,
      4150417245,
      2154129355,
      426522225,
      1852507879,
      4275313526,
      2312317920,
      282753626,
      1742555852,
      4189708143,
      2394877945,
      397917763,
      1622183637,
      3604390888,
      2714866558,
      953729732,
      1340076626,
      3518719985,
      2797360999,
      1068828381,
      1219638859,
      3624741850,
      2936675148,
      906185462,
      1090812512,
      3747672003,
      2825379669,
      829329135,
      1181335161,
      3412177804,
      3160834842,
      628085408,
      1382605366,
      3423369109,
      3138078467,
      570562233,
      1426400815,
      3317316542,
      2998733608,
      733239954,
      1555261956,
      3268935591,
      3050360625,
      752459403,
      1541320221,
      2607071920,
      3965973030,
      1969922972,
      40735498,
      2617837225,
      3943577151,
      1913087877,
      83908371,
      2512341634,
      3803740692,
      2075208622,
      213261112,
      2463272603,
      3855990285,
      2094854071,
      198958881,
      2262029012,
      4057260610,
      1759359992,
      534414190,
      2176718541,
      4139329115,
      1873836001,
      414664567,
      2282248934,
      4279200368,
      1711684554,
      285281116,
      2405801727,
      4167216745,
      1634467795,
      376229701,
      2685067896,
      3608007406,
      1308918612,
      956543938,
      2808555105,
      3495958263,
      1231636301,
      1047427035,
      2932959818,
      3654703836,
      1088359270,
      936918e3,
      2847714899,
      3736837829,
      1202900863,
      817233897,
      3183342108,
      3401237130,
      1404277552,
      615818150,
      3134207493,
      3453421203,
      1423857449,
      601450431,
      3009837614,
      3294710456,
      1567103746,
      711928724,
      3020668471,
      3272380065,
      1510334235,
      755167117
    ];
    var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable);
    var aws_crc32_1 = require_aws_crc32();
    Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function() {
      return aws_crc32_1.AwsCrc32;
    } });
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
var require_dist_cjs8 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toHex = exports.fromHex = void 0;
    var SHORT_TO_HEX3 = {};
    var HEX_TO_SHORT3 = {};
    for (let i3 = 0; i3 < 256; i3++) {
      let encodedByte = i3.toString(16).toLowerCase();
      if (encodedByte.length === 1) {
        encodedByte = `0${encodedByte}`;
      }
      SHORT_TO_HEX3[i3] = encodedByte;
      HEX_TO_SHORT3[encodedByte] = i3;
    }
    function fromHex2(encoded) {
      if (encoded.length % 2 !== 0) {
        throw new Error("Hex encoded strings must have an even number length");
      }
      const out = new Uint8Array(encoded.length / 2);
      for (let i3 = 0; i3 < encoded.length; i3 += 2) {
        const encodedByte = encoded.slice(i3, i3 + 2).toLowerCase();
        if (encodedByte in HEX_TO_SHORT3) {
          out[i3 / 2] = HEX_TO_SHORT3[encodedByte];
        } else {
          throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
        }
      }
      return out;
    }
    exports.fromHex = fromHex2;
    function toHex3(bytes) {
      let out = "";
      for (let i3 = 0; i3 < bytes.byteLength; i3++) {
        out += SHORT_TO_HEX3[bytes[i3]];
      }
      return out;
    }
    exports.toHex = toHex3;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/Int64.js
var require_Int64 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/Int64.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Int64 = void 0;
    var util_hex_encoding_1 = require_dist_cjs8();
    var Int642 = class {
      constructor(bytes) {
        this.bytes = bytes;
        if (bytes.byteLength !== 8) {
          throw new Error("Int64 buffers must be exactly 8 bytes");
        }
      }
      static fromNumber(number) {
        if (number > 9223372036854776e3 || number < -9223372036854776e3) {
          throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);
        }
        const bytes = new Uint8Array(8);
        for (let i3 = 7, remaining = Math.abs(Math.round(number)); i3 > -1 && remaining > 0; i3--, remaining /= 256) {
          bytes[i3] = remaining;
        }
        if (number < 0) {
          negate2(bytes);
        }
        return new Int642(bytes);
      }
      valueOf() {
        const bytes = this.bytes.slice(0);
        const negative = bytes[0] & 128;
        if (negative) {
          negate2(bytes);
        }
        return parseInt((0, util_hex_encoding_1.toHex)(bytes), 16) * (negative ? -1 : 1);
      }
      toString() {
        return String(this.valueOf());
      }
    };
    exports.Int64 = Int642;
    function negate2(bytes) {
      for (let i3 = 0; i3 < 8; i3++) {
        bytes[i3] ^= 255;
      }
      for (let i3 = 7; i3 > -1; i3--) {
        bytes[i3]++;
        if (bytes[i3] !== 0)
          break;
      }
    }
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/HeaderMarshaller.js
var require_HeaderMarshaller = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/HeaderMarshaller.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.HeaderMarshaller = void 0;
    var util_hex_encoding_1 = require_dist_cjs8();
    var Int64_1 = require_Int64();
    var HeaderMarshaller = class {
      constructor(toUtf84, fromUtf86) {
        this.toUtf8 = toUtf84;
        this.fromUtf8 = fromUtf86;
      }
      format(headers) {
        const chunks = [];
        for (const headerName of Object.keys(headers)) {
          const bytes = this.fromUtf8(headerName);
          chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
        }
        const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
        let position = 0;
        for (const chunk of chunks) {
          out.set(chunk, position);
          position += chunk.byteLength;
        }
        return out;
      }
      formatHeaderValue(header) {
        switch (header.type) {
          case "boolean":
            return Uint8Array.from([header.value ? 0 : 1]);
          case "byte":
            return Uint8Array.from([2, header.value]);
          case "short":
            const shortView = new DataView(new ArrayBuffer(3));
            shortView.setUint8(0, 3);
            shortView.setInt16(1, header.value, false);
            return new Uint8Array(shortView.buffer);
          case "integer":
            const intView = new DataView(new ArrayBuffer(5));
            intView.setUint8(0, 4);
            intView.setInt32(1, header.value, false);
            return new Uint8Array(intView.buffer);
          case "long":
            const longBytes = new Uint8Array(9);
            longBytes[0] = 5;
            longBytes.set(header.value.bytes, 1);
            return longBytes;
          case "binary":
            const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
            binView.setUint8(0, 6);
            binView.setUint16(1, header.value.byteLength, false);
            const binBytes = new Uint8Array(binView.buffer);
            binBytes.set(header.value, 3);
            return binBytes;
          case "string":
            const utf8Bytes = this.fromUtf8(header.value);
            const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
            strView.setUint8(0, 7);
            strView.setUint16(1, utf8Bytes.byteLength, false);
            const strBytes = new Uint8Array(strView.buffer);
            strBytes.set(utf8Bytes, 3);
            return strBytes;
          case "timestamp":
            const tsBytes = new Uint8Array(9);
            tsBytes[0] = 8;
            tsBytes.set(Int64_1.Int64.fromNumber(header.value.valueOf()).bytes, 1);
            return tsBytes;
          case "uuid":
            if (!UUID_PATTERN2.test(header.value)) {
              throw new Error(`Invalid UUID received: ${header.value}`);
            }
            const uuidBytes = new Uint8Array(17);
            uuidBytes[0] = 9;
            uuidBytes.set((0, util_hex_encoding_1.fromHex)(header.value.replace(/\-/g, "")), 1);
            return uuidBytes;
        }
      }
      parse(headers) {
        const out = {};
        let position = 0;
        while (position < headers.byteLength) {
          const nameLength = headers.getUint8(position++);
          const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength));
          position += nameLength;
          switch (headers.getUint8(position++)) {
            case 0:
              out[name] = {
                type: BOOLEAN_TAG,
                value: true
              };
              break;
            case 1:
              out[name] = {
                type: BOOLEAN_TAG,
                value: false
              };
              break;
            case 2:
              out[name] = {
                type: BYTE_TAG,
                value: headers.getInt8(position++)
              };
              break;
            case 3:
              out[name] = {
                type: SHORT_TAG,
                value: headers.getInt16(position, false)
              };
              position += 2;
              break;
            case 4:
              out[name] = {
                type: INT_TAG,
                value: headers.getInt32(position, false)
              };
              position += 4;
              break;
            case 5:
              out[name] = {
                type: LONG_TAG,
                value: new Int64_1.Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8))
              };
              position += 8;
              break;
            case 6:
              const binaryLength = headers.getUint16(position, false);
              position += 2;
              out[name] = {
                type: BINARY_TAG,
                value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength)
              };
              position += binaryLength;
              break;
            case 7:
              const stringLength = headers.getUint16(position, false);
              position += 2;
              out[name] = {
                type: STRING_TAG,
                value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength))
              };
              position += stringLength;
              break;
            case 8:
              out[name] = {
                type: TIMESTAMP_TAG,
                value: new Date(new Int64_1.Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf())
              };
              position += 8;
              break;
            case 9:
              const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16);
              position += 16;
              out[name] = {
                type: UUID_TAG,
                value: `${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(0, 4))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(4, 6))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(6, 8))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(8, 10))}-${(0, util_hex_encoding_1.toHex)(uuidBytes.subarray(10))}`
              };
              break;
            default:
              throw new Error(`Unrecognized header type tag`);
          }
        }
        return out;
      }
    };
    exports.HeaderMarshaller = HeaderMarshaller;
    var HEADER_VALUE_TYPE2;
    (function(HEADER_VALUE_TYPE3) {
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
      HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
    })(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {}));
    var BOOLEAN_TAG = "boolean";
    var BYTE_TAG = "byte";
    var SHORT_TAG = "short";
    var INT_TAG = "integer";
    var LONG_TAG = "long";
    var BINARY_TAG = "binary";
    var STRING_TAG = "string";
    var TIMESTAMP_TAG = "timestamp";
    var UUID_TAG = "uuid";
    var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/splitMessage.js
var require_splitMessage = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/splitMessage.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.splitMessage = void 0;
    var crc32_1 = require_build2();
    var PRELUDE_MEMBER_LENGTH = 4;
    var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2;
    var CHECKSUM_LENGTH = 4;
    var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2;
    function splitMessage({ byteLength, byteOffset, buffer }) {
      if (byteLength < MINIMUM_MESSAGE_LENGTH) {
        throw new Error("Provided message too short to accommodate event stream message overhead");
      }
      const view = new DataView(buffer, byteOffset, byteLength);
      const messageLength = view.getUint32(0, false);
      if (byteLength !== messageLength) {
        throw new Error("Reported message length does not match received message length");
      }
      const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false);
      const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false);
      const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false);
      const checksummer = new crc32_1.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH));
      if (expectedPreludeChecksum !== checksummer.digest()) {
        throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);
      }
      checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)));
      if (expectedMessageChecksum !== checksummer.digest()) {
        throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);
      }
      return {
        headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength),
        body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH))
      };
    }
    exports.splitMessage = splitMessage;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/EventStreamCodec.js
var require_EventStreamCodec = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/EventStreamCodec.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EventStreamCodec = void 0;
    var crc32_1 = require_build2();
    var HeaderMarshaller_1 = require_HeaderMarshaller();
    var splitMessage_1 = require_splitMessage();
    var EventStreamCodec = class {
      constructor(toUtf84, fromUtf86) {
        this.headerMarshaller = new HeaderMarshaller_1.HeaderMarshaller(toUtf84, fromUtf86);
        this.messageBuffer = [];
        this.isEndOfStream = false;
      }
      feed(message) {
        this.messageBuffer.push(this.decode(message));
      }
      endOfStream() {
        this.isEndOfStream = true;
      }
      getMessage() {
        const message = this.messageBuffer.pop();
        const isEndOfStream = this.isEndOfStream;
        return {
          getMessage() {
            return message;
          },
          isEndOfStream() {
            return isEndOfStream;
          }
        };
      }
      getAvailableMessages() {
        const messages = this.messageBuffer;
        this.messageBuffer = [];
        const isEndOfStream = this.isEndOfStream;
        return {
          getMessages() {
            return messages;
          },
          isEndOfStream() {
            return isEndOfStream;
          }
        };
      }
      encode({ headers: rawHeaders, body }) {
        const headers = this.headerMarshaller.format(rawHeaders);
        const length = headers.byteLength + body.byteLength + 16;
        const out = new Uint8Array(length);
        const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
        const checksum = new crc32_1.Crc32();
        view.setUint32(0, length, false);
        view.setUint32(4, headers.byteLength, false);
        view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false);
        out.set(headers, 12);
        out.set(body, headers.byteLength + 12);
        view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false);
        return out;
      }
      decode(message) {
        const { headers, body } = (0, splitMessage_1.splitMessage)(message);
        return { headers: this.headerMarshaller.parse(headers), body };
      }
      formatHeaders(rawHeaders) {
        return this.headerMarshaller.format(rawHeaders);
      }
    };
    exports.EventStreamCodec = EventStreamCodec;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/Message.js
var require_Message2 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/Message.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/MessageDecoderStream.js
var require_MessageDecoderStream = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/MessageDecoderStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageDecoderStream = void 0;
    var MessageDecoderStream = class {
      constructor(options) {
        this.options = options;
      }
      [Symbol.asyncIterator]() {
        return this.asyncIterator();
      }
      async *asyncIterator() {
        for await (const bytes of this.options.inputStream) {
          const decoded = this.options.decoder.decode(bytes);
          yield decoded;
        }
      }
    };
    exports.MessageDecoderStream = MessageDecoderStream;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/MessageEncoderStream.js
var require_MessageEncoderStream = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/MessageEncoderStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MessageEncoderStream = void 0;
    var MessageEncoderStream = class {
      constructor(options) {
        this.options = options;
      }
      [Symbol.asyncIterator]() {
        return this.asyncIterator();
      }
      async *asyncIterator() {
        for await (const msg of this.options.messageStream) {
          const encoded = this.options.encoder.encode(msg);
          yield encoded;
        }
        if (this.options.includeEndFrame) {
          yield new Uint8Array(0);
        }
      }
    };
    exports.MessageEncoderStream = MessageEncoderStream;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/SmithyMessageDecoderStream.js
var require_SmithyMessageDecoderStream = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/SmithyMessageDecoderStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SmithyMessageDecoderStream = void 0;
    var SmithyMessageDecoderStream = class {
      constructor(options) {
        this.options = options;
      }
      [Symbol.asyncIterator]() {
        return this.asyncIterator();
      }
      async *asyncIterator() {
        for await (const message of this.options.messageStream) {
          const deserialized = await this.options.deserializer(message);
          if (deserialized === void 0)
            continue;
          yield deserialized;
        }
      }
    };
    exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/SmithyMessageEncoderStream.js
var require_SmithyMessageEncoderStream = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/SmithyMessageEncoderStream.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SmithyMessageEncoderStream = void 0;
    var SmithyMessageEncoderStream = class {
      constructor(options) {
        this.options = options;
      }
      [Symbol.asyncIterator]() {
        return this.asyncIterator();
      }
      async *asyncIterator() {
        for await (const chunk of this.options.inputStream) {
          const payloadBuf = this.options.serializer(chunk);
          yield payloadBuf;
        }
      }
    };
    exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/index.js
var require_dist_cjs9 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/eventstream-codec/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_EventStreamCodec(), exports);
    tslib_1.__exportStar(require_HeaderMarshaller(), exports);
    tslib_1.__exportStar(require_Int64(), exports);
    tslib_1.__exportStar(require_Message2(), exports);
    tslib_1.__exportStar(require_MessageDecoderStream(), exports);
    tslib_1.__exportStar(require_MessageEncoderStream(), exports);
    tslib_1.__exportStar(require_SmithyMessageDecoderStream(), exports);
    tslib_1.__exportStar(require_SmithyMessageEncoderStream(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/normalizeProvider.js
var require_normalizeProvider = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/normalizeProvider.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.normalizeProvider = void 0;
    var normalizeProvider3 = (input) => {
      if (typeof input === "function")
        return input;
      const promisified = Promise.resolve(input);
      return () => promisified;
    };
    exports.normalizeProvider = normalizeProvider3;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js
var require_dist_cjs10 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_normalizeProvider(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
var require_dist_cjs11 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isArrayBuffer = void 0;
    var isArrayBuffer2 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
    exports.isArrayBuffer = isArrayBuffer2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
var require_dist_cjs12 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fromString = exports.fromArrayBuffer = void 0;
    var is_array_buffer_1 = require_dist_cjs11();
    var buffer_1 = require_buffer();
    var fromArrayBuffer = (input, offset5 = 0, length = input.byteLength - offset5) => {
      if (!(0, is_array_buffer_1.isArrayBuffer)(input)) {
        throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
      }
      return buffer_1.Buffer.from(input, offset5, length);
    };
    exports.fromArrayBuffer = fromArrayBuffer;
    var fromString = (input, encoding) => {
      if (typeof input !== "string") {
        throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
      }
      return encoding ? buffer_1.Buffer.from(input, encoding) : buffer_1.Buffer.from(input);
    };
    exports.fromString = fromString;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/fromUtf8.js
var require_fromUtf8 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/fromUtf8.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fromUtf8 = void 0;
    var util_buffer_from_1 = require_dist_cjs12();
    var fromUtf86 = (input) => {
      const buf = (0, util_buffer_from_1.fromString)(input, "utf8");
      return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    };
    exports.fromUtf8 = fromUtf86;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/toUint8Array.js
var require_toUint8Array = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/toUint8Array.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUint8Array = void 0;
    var fromUtf8_1 = require_fromUtf8();
    var toUint8Array2 = (data) => {
      if (typeof data === "string") {
        return (0, fromUtf8_1.fromUtf8)(data);
      }
      if (ArrayBuffer.isView(data)) {
        return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
      }
      return new Uint8Array(data);
    };
    exports.toUint8Array = toUint8Array2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/toUtf8.js
var require_toUtf8 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/toUtf8.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toUtf8 = void 0;
    var util_buffer_from_1 = require_dist_cjs12();
    var toUtf84 = (input) => (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
    exports.toUtf8 = toUtf84;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js
var require_dist_cjs13 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_fromUtf8(), exports);
    tslib_1.__exportStar(require_toUint8Array(), exports);
    tslib_1.__exportStar(require_toUtf8(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/constants.js
var require_constants3 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MAX_PRESIGNED_TTL = exports.KEY_TYPE_IDENTIFIER = exports.MAX_CACHE_SIZE = exports.UNSIGNED_PAYLOAD = exports.EVENT_ALGORITHM_IDENTIFIER = exports.ALGORITHM_IDENTIFIER_V4A = exports.ALGORITHM_IDENTIFIER = exports.UNSIGNABLE_PATTERNS = exports.SEC_HEADER_PATTERN = exports.PROXY_HEADER_PATTERN = exports.ALWAYS_UNSIGNABLE_HEADERS = exports.HOST_HEADER = exports.TOKEN_HEADER = exports.SHA256_HEADER = exports.SIGNATURE_HEADER = exports.GENERATED_HEADERS = exports.DATE_HEADER = exports.AMZ_DATE_HEADER = exports.AUTH_HEADER = exports.REGION_SET_PARAM = exports.TOKEN_QUERY_PARAM = exports.SIGNATURE_QUERY_PARAM = exports.EXPIRES_QUERY_PARAM = exports.SIGNED_HEADERS_QUERY_PARAM = exports.AMZ_DATE_QUERY_PARAM = exports.CREDENTIAL_QUERY_PARAM = exports.ALGORITHM_QUERY_PARAM = void 0;
    exports.ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
    exports.CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
    exports.AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
    exports.SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
    exports.EXPIRES_QUERY_PARAM = "X-Amz-Expires";
    exports.SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
    exports.TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
    exports.REGION_SET_PARAM = "X-Amz-Region-Set";
    exports.AUTH_HEADER = "authorization";
    exports.AMZ_DATE_HEADER = exports.AMZ_DATE_QUERY_PARAM.toLowerCase();
    exports.DATE_HEADER = "date";
    exports.GENERATED_HEADERS = [exports.AUTH_HEADER, exports.AMZ_DATE_HEADER, exports.DATE_HEADER];
    exports.SIGNATURE_HEADER = exports.SIGNATURE_QUERY_PARAM.toLowerCase();
    exports.SHA256_HEADER = "x-amz-content-sha256";
    exports.TOKEN_HEADER = exports.TOKEN_QUERY_PARAM.toLowerCase();
    exports.HOST_HEADER = "host";
    exports.ALWAYS_UNSIGNABLE_HEADERS = {
      authorization: true,
      "cache-control": true,
      connection: true,
      expect: true,
      from: true,
      "keep-alive": true,
      "max-forwards": true,
      pragma: true,
      referer: true,
      te: true,
      trailer: true,
      "transfer-encoding": true,
      upgrade: true,
      "user-agent": true,
      "x-amzn-trace-id": true
    };
    exports.PROXY_HEADER_PATTERN = /^proxy-/;
    exports.SEC_HEADER_PATTERN = /^sec-/;
    exports.UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];
    exports.ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
    exports.ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256";
    exports.EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
    exports.UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
    exports.MAX_CACHE_SIZE = 50;
    exports.KEY_TYPE_IDENTIFIER = "aws4_request";
    exports.MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/credentialDerivation.js
var require_credentialDerivation = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/credentialDerivation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.clearCredentialCache = exports.getSigningKey = exports.createScope = void 0;
    var util_hex_encoding_1 = require_dist_cjs8();
    var util_utf8_1 = require_dist_cjs13();
    var constants_1 = require_constants3();
    var signingKeyCache2 = {};
    var cacheQueue2 = [];
    var createScope2 = (shortDate, region, service) => `${shortDate}/${region}/${service}/${constants_1.KEY_TYPE_IDENTIFIER}`;
    exports.createScope = createScope2;
    var getSigningKey2 = async (sha256Constructor, credentials, shortDate, region, service) => {
      const credsHash = await hmac2(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
      const cacheKey = `${shortDate}:${region}:${service}:${(0, util_hex_encoding_1.toHex)(credsHash)}:${credentials.sessionToken}`;
      if (cacheKey in signingKeyCache2) {
        return signingKeyCache2[cacheKey];
      }
      cacheQueue2.push(cacheKey);
      while (cacheQueue2.length > constants_1.MAX_CACHE_SIZE) {
        delete signingKeyCache2[cacheQueue2.shift()];
      }
      let key = `AWS4${credentials.secretAccessKey}`;
      for (const signable of [shortDate, region, service, constants_1.KEY_TYPE_IDENTIFIER]) {
        key = await hmac2(sha256Constructor, key, signable);
      }
      return signingKeyCache2[cacheKey] = key;
    };
    exports.getSigningKey = getSigningKey2;
    var clearCredentialCache = () => {
      cacheQueue2.length = 0;
      Object.keys(signingKeyCache2).forEach((cacheKey) => {
        delete signingKeyCache2[cacheKey];
      });
    };
    exports.clearCredentialCache = clearCredentialCache;
    var hmac2 = (ctor, secret, data) => {
      const hash = new ctor(secret);
      hash.update((0, util_utf8_1.toUint8Array)(data));
      return hash.digest();
    };
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getCanonicalHeaders.js
var require_getCanonicalHeaders = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getCanonicalHeaders.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getCanonicalHeaders = void 0;
    var constants_1 = require_constants3();
    var getCanonicalHeaders2 = ({ headers }, unsignableHeaders, signableHeaders) => {
      const canonical = {};
      for (const headerName of Object.keys(headers).sort()) {
        if (headers[headerName] == void 0) {
          continue;
        }
        const canonicalHeaderName = headerName.toLowerCase();
        if (canonicalHeaderName in constants_1.ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders === null || unsignableHeaders === void 0 ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || constants_1.PROXY_HEADER_PATTERN.test(canonicalHeaderName) || constants_1.SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
          if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
            continue;
          }
        }
        canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
      }
      return canonical;
    };
    exports.getCanonicalHeaders = getCanonicalHeaders2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/escape-uri.js
var require_escape_uri = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/escape-uri.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.escapeUri = void 0;
    var escapeUri2 = (uri2) => encodeURIComponent(uri2).replace(/[!'()*]/g, hexEncode2);
    exports.escapeUri = escapeUri2;
    var hexEncode2 = (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}`;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/escape-uri-path.js
var require_escape_uri_path = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/escape-uri-path.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.escapeUriPath = void 0;
    var escape_uri_1 = require_escape_uri();
    var escapeUriPath = (uri2) => uri2.split("/").map(escape_uri_1.escapeUri).join("/");
    exports.escapeUriPath = escapeUriPath;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
var require_dist_cjs14 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_escape_uri(), exports);
    tslib_1.__exportStar(require_escape_uri_path(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getCanonicalQuery.js
var require_getCanonicalQuery = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getCanonicalQuery.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getCanonicalQuery = void 0;
    var util_uri_escape_1 = require_dist_cjs14();
    var constants_1 = require_constants3();
    var getCanonicalQuery2 = ({ query = {} }) => {
      const keys = [];
      const serialized = {};
      for (const key of Object.keys(query).sort()) {
        if (key.toLowerCase() === constants_1.SIGNATURE_HEADER) {
          continue;
        }
        keys.push(key);
        const value = query[key];
        if (typeof value === "string") {
          serialized[key] = `${(0, util_uri_escape_1.escapeUri)(key)}=${(0, util_uri_escape_1.escapeUri)(value)}`;
        } else if (Array.isArray(value)) {
          serialized[key] = value.slice(0).sort().reduce((encoded, value2) => encoded.concat([`${(0, util_uri_escape_1.escapeUri)(key)}=${(0, util_uri_escape_1.escapeUri)(value2)}`]), []).join("&");
        }
      }
      return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
    };
    exports.getCanonicalQuery = getCanonicalQuery2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getPayloadHash.js
var require_getPayloadHash = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/getPayloadHash.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getPayloadHash = void 0;
    var is_array_buffer_1 = require_dist_cjs11();
    var util_hex_encoding_1 = require_dist_cjs8();
    var util_utf8_1 = require_dist_cjs13();
    var constants_1 = require_constants3();
    var getPayloadHash2 = async ({ headers, body }, hashConstructor) => {
      for (const headerName of Object.keys(headers)) {
        if (headerName.toLowerCase() === constants_1.SHA256_HEADER) {
          return headers[headerName];
        }
      }
      if (body == void 0) {
        return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
      } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, is_array_buffer_1.isArrayBuffer)(body)) {
        const hashCtor = new hashConstructor();
        hashCtor.update((0, util_utf8_1.toUint8Array)(body));
        return (0, util_hex_encoding_1.toHex)(await hashCtor.digest());
      }
      return constants_1.UNSIGNED_PAYLOAD;
    };
    exports.getPayloadHash = getPayloadHash2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/headerUtil.js
var require_headerUtil = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/headerUtil.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.deleteHeader = exports.getHeaderValue = exports.hasHeader = void 0;
    var hasHeader2 = (soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return true;
        }
      }
      return false;
    };
    exports.hasHeader = hasHeader2;
    var getHeaderValue = (soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          return headers[headerName];
        }
      }
      return void 0;
    };
    exports.getHeaderValue = getHeaderValue;
    var deleteHeader = (soughtHeader, headers) => {
      soughtHeader = soughtHeader.toLowerCase();
      for (const headerName of Object.keys(headers)) {
        if (soughtHeader === headerName.toLowerCase()) {
          delete headers[headerName];
        }
      }
    };
    exports.deleteHeader = deleteHeader;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/cloneRequest.js
var require_cloneRequest = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/cloneRequest.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.cloneQuery = exports.cloneRequest = void 0;
    var cloneRequest = ({ headers, query, ...rest }) => ({
      ...rest,
      headers: { ...headers },
      query: query ? (0, exports.cloneQuery)(query) : void 0
    });
    exports.cloneRequest = cloneRequest;
    var cloneQuery11 = (query) => Object.keys(query).reduce((carry, paramName) => {
      const param = query[paramName];
      return {
        ...carry,
        [paramName]: Array.isArray(param) ? [...param] : param
      };
    }, {});
    exports.cloneQuery = cloneQuery11;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/moveHeadersToQuery.js
var require_moveHeadersToQuery = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/moveHeadersToQuery.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.moveHeadersToQuery = void 0;
    var cloneRequest_1 = require_cloneRequest();
    var moveHeadersToQuery2 = (request, options = {}) => {
      var _a5;
      const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : (0, cloneRequest_1.cloneRequest)(request);
      for (const name of Object.keys(headers)) {
        const lname = name.toLowerCase();
        if (lname.slice(0, 6) === "x-amz-" && !((_a5 = options.unhoistableHeaders) === null || _a5 === void 0 ? void 0 : _a5.has(lname))) {
          query[name] = headers[name];
          delete headers[name];
        }
      }
      return {
        ...request,
        headers,
        query
      };
    };
    exports.moveHeadersToQuery = moveHeadersToQuery2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/prepareRequest.js
var require_prepareRequest = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/prepareRequest.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareRequest = void 0;
    var cloneRequest_1 = require_cloneRequest();
    var constants_1 = require_constants3();
    var prepareRequest2 = (request) => {
      request = typeof request.clone === "function" ? request.clone() : (0, cloneRequest_1.cloneRequest)(request);
      for (const headerName of Object.keys(request.headers)) {
        if (constants_1.GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
          delete request.headers[headerName];
        }
      }
      return request;
    };
    exports.prepareRequest = prepareRequest2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/utilDate.js
var require_utilDate = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/utilDate.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.toDate = exports.iso8601 = void 0;
    var iso86012 = (time2) => (0, exports.toDate)(time2).toISOString().replace(/\.\d{3}Z$/, "Z");
    exports.iso8601 = iso86012;
    var toDate2 = (time2) => {
      if (typeof time2 === "number") {
        return new Date(time2 * 1e3);
      }
      if (typeof time2 === "string") {
        if (Number(time2)) {
          return new Date(Number(time2) * 1e3);
        }
        return new Date(time2);
      }
      return time2;
    };
    exports.toDate = toDate2;
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/SignatureV4.js
var require_SignatureV4 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/SignatureV4.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SignatureV4 = void 0;
    var eventstream_codec_1 = require_dist_cjs9();
    var util_hex_encoding_1 = require_dist_cjs8();
    var util_middleware_1 = require_dist_cjs10();
    var util_utf8_1 = require_dist_cjs13();
    var constants_1 = require_constants3();
    var credentialDerivation_1 = require_credentialDerivation();
    var getCanonicalHeaders_1 = require_getCanonicalHeaders();
    var getCanonicalQuery_1 = require_getCanonicalQuery();
    var getPayloadHash_1 = require_getPayloadHash();
    var headerUtil_1 = require_headerUtil();
    var moveHeadersToQuery_1 = require_moveHeadersToQuery();
    var prepareRequest_1 = require_prepareRequest();
    var utilDate_1 = require_utilDate();
    var SignatureV42 = class {
      constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
        this.headerMarshaller = new eventstream_codec_1.HeaderMarshaller(util_utf8_1.toUtf8, util_utf8_1.fromUtf8);
        this.service = service;
        this.sha256 = sha256;
        this.uriEscapePath = uriEscapePath;
        this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
        this.regionProvider = (0, util_middleware_1.normalizeProvider)(region);
        this.credentialProvider = (0, util_middleware_1.normalizeProvider)(credentials);
      }
      async presign(originalRequest, options = {}) {
        const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, signingRegion, signingService } = options;
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : await this.regionProvider();
        const { longDate, shortDate } = formatDate2(signingDate);
        if (expiresIn > constants_1.MAX_PRESIGNED_TTL) {
          return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
        }
        const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service);
        const request = (0, moveHeadersToQuery_1.moveHeadersToQuery)((0, prepareRequest_1.prepareRequest)(originalRequest), { unhoistableHeaders });
        if (credentials.sessionToken) {
          request.query[constants_1.TOKEN_QUERY_PARAM] = credentials.sessionToken;
        }
        request.query[constants_1.ALGORITHM_QUERY_PARAM] = constants_1.ALGORITHM_IDENTIFIER;
        request.query[constants_1.CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
        request.query[constants_1.AMZ_DATE_QUERY_PARAM] = longDate;
        request.query[constants_1.EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
        const canonicalHeaders = (0, getCanonicalHeaders_1.getCanonicalHeaders)(request, unsignableHeaders, signableHeaders);
        request.query[constants_1.SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList2(canonicalHeaders);
        request.query[constants_1.SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await (0, getPayloadHash_1.getPayloadHash)(originalRequest, this.sha256)));
        return request;
      }
      async sign(toSign, options) {
        if (typeof toSign === "string") {
          return this.signString(toSign, options);
        } else if (toSign.headers && toSign.payload) {
          return this.signEvent(toSign, options);
        } else if (toSign.message) {
          return this.signMessage(toSign, options);
        } else {
          return this.signRequest(toSign, options);
        }
      }
      async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) {
        const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : await this.regionProvider();
        const { shortDate, longDate } = formatDate2(signingDate);
        const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service);
        const hashedPayload = await (0, getPayloadHash_1.getPayloadHash)({ headers: {}, body: payload }, this.sha256);
        const hash = new this.sha256();
        hash.update(headers);
        const hashedHeaders = (0, util_hex_encoding_1.toHex)(await hash.digest());
        const stringToSign = [
          constants_1.EVENT_ALGORITHM_IDENTIFIER,
          longDate,
          scope,
          priorSignature,
          hashedHeaders,
          hashedPayload
        ].join("\n");
        return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
      }
      async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) {
        const promise = this.signEvent({
          headers: this.headerMarshaller.format(signableMessage.message.headers),
          payload: signableMessage.message.body
        }, {
          signingDate,
          signingRegion,
          signingService,
          priorSignature: signableMessage.priorSignature
        });
        return promise.then((signature) => {
          return { message: signableMessage.message, signature };
        });
      }
      async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) {
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : await this.regionProvider();
        const { shortDate } = formatDate2(signingDate);
        const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
        hash.update((0, util_utf8_1.toUint8Array)(stringToSign));
        return (0, util_hex_encoding_1.toHex)(await hash.digest());
      }
      async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
        const credentials = await this.credentialProvider();
        this.validateResolvedCredentials(credentials);
        const region = signingRegion !== null && signingRegion !== void 0 ? signingRegion : await this.regionProvider();
        const request = (0, prepareRequest_1.prepareRequest)(requestToSign);
        const { longDate, shortDate } = formatDate2(signingDate);
        const scope = (0, credentialDerivation_1.createScope)(shortDate, region, signingService !== null && signingService !== void 0 ? signingService : this.service);
        request.headers[constants_1.AMZ_DATE_HEADER] = longDate;
        if (credentials.sessionToken) {
          request.headers[constants_1.TOKEN_HEADER] = credentials.sessionToken;
        }
        const payloadHash = await (0, getPayloadHash_1.getPayloadHash)(request, this.sha256);
        if (!(0, headerUtil_1.hasHeader)(constants_1.SHA256_HEADER, request.headers) && this.applyChecksum) {
          request.headers[constants_1.SHA256_HEADER] = payloadHash;
        }
        const canonicalHeaders = (0, getCanonicalHeaders_1.getCanonicalHeaders)(request, unsignableHeaders, signableHeaders);
        const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash));
        request.headers[constants_1.AUTH_HEADER] = `${constants_1.ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList2(canonicalHeaders)}, Signature=${signature}`;
        return request;
      }
      createCanonicalRequest(request, canonicalHeaders, payloadHash) {
        const sortedHeaders = Object.keys(canonicalHeaders).sort();
        return `${request.method}
${this.getCanonicalPath(request)}
${(0, getCanonicalQuery_1.getCanonicalQuery)(request)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
      }
      async createStringToSign(longDate, credentialScope, canonicalRequest) {
        const hash = new this.sha256();
        hash.update((0, util_utf8_1.toUint8Array)(canonicalRequest));
        const hashedRequest = await hash.digest();
        return `${constants_1.ALGORITHM_IDENTIFIER}
${longDate}
${credentialScope}
${(0, util_hex_encoding_1.toHex)(hashedRequest)}`;
      }
      getCanonicalPath({ path }) {
        if (this.uriEscapePath) {
          const normalizedPathSegments = [];
          for (const pathSegment of path.split("/")) {
            if ((pathSegment === null || pathSegment === void 0 ? void 0 : pathSegment.length) === 0)
              continue;
            if (pathSegment === ".")
              continue;
            if (pathSegment === "..") {
              normalizedPathSegments.pop();
            } else {
              normalizedPathSegments.push(pathSegment);
            }
          }
          const normalizedPath = `${(path === null || path === void 0 ? void 0 : path.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path === null || path === void 0 ? void 0 : path.endsWith("/")) ? "/" : ""}`;
          const doubleEncoded = encodeURIComponent(normalizedPath);
          return doubleEncoded.replace(/%2F/g, "/");
        }
        return path;
      }
      async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
        const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
        const hash = new this.sha256(await keyPromise);
        hash.update((0, util_utf8_1.toUint8Array)(stringToSign));
        return (0, util_hex_encoding_1.toHex)(await hash.digest());
      }
      getSigningKey(credentials, region, shortDate, service) {
        return (0, credentialDerivation_1.getSigningKey)(this.sha256, credentials, shortDate, region, service || this.service);
      }
      validateResolvedCredentials(credentials) {
        if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
          throw new Error("Resolved credential object is not valid");
        }
      }
    };
    exports.SignatureV4 = SignatureV42;
    var formatDate2 = (now3) => {
      const longDate = (0, utilDate_1.iso8601)(now3).replace(/[\-:]/g, "");
      return {
        longDate,
        shortDate: longDate.slice(0, 8)
      };
    };
    var getCanonicalHeaderList2 = (headers) => Object.keys(headers).sort().join(";");
  }
});

// node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/index.js
var require_dist_cjs15 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareRequest = exports.moveHeadersToQuery = exports.getPayloadHash = exports.getCanonicalQuery = exports.getCanonicalHeaders = void 0;
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_SignatureV4(), exports);
    var getCanonicalHeaders_1 = require_getCanonicalHeaders();
    Object.defineProperty(exports, "getCanonicalHeaders", { enumerable: true, get: function() {
      return getCanonicalHeaders_1.getCanonicalHeaders;
    } });
    var getCanonicalQuery_1 = require_getCanonicalQuery();
    Object.defineProperty(exports, "getCanonicalQuery", { enumerable: true, get: function() {
      return getCanonicalQuery_1.getCanonicalQuery;
    } });
    var getPayloadHash_1 = require_getPayloadHash();
    Object.defineProperty(exports, "getPayloadHash", { enumerable: true, get: function() {
      return getPayloadHash_1.getPayloadHash;
    } });
    var moveHeadersToQuery_1 = require_moveHeadersToQuery();
    Object.defineProperty(exports, "moveHeadersToQuery", { enumerable: true, get: function() {
      return moveHeadersToQuery_1.moveHeadersToQuery;
    } });
    var prepareRequest_1 = require_prepareRequest();
    Object.defineProperty(exports, "prepareRequest", { enumerable: true, get: function() {
      return prepareRequest_1.prepareRequest;
    } });
    tslib_1.__exportStar(require_credentialDerivation(), exports);
  }
});

// node_modules/@aws-sdk/signature-v4/dist-cjs/index.js
var require_dist_cjs16 = __commonJS({
  "node_modules/@aws-sdk/signature-v4/dist-cjs/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
    tslib_1.__exportStar(require_dist_cjs15(), exports);
  }
});

// node_modules/readable-stream/lib/ours/primordials.js
var require_primordials = __commonJS({
  "node_modules/readable-stream/lib/ours/primordials.js"(exports, module2) {
    "use strict";
    module2.exports = {
      ArrayIsArray(self2) {
        return Array.isArray(self2);
      },
      ArrayPrototypeIncludes(self2, el) {
        return self2.includes(el);
      },
      ArrayPrototypeIndexOf(self2, el) {
        return self2.indexOf(el);
      },
      ArrayPrototypeJoin(self2, sep) {
        return self2.join(sep);
      },
      ArrayPrototypeMap(self2, fn) {
        return self2.map(fn);
      },
      ArrayPrototypePop(self2, el) {
        return self2.pop(el);
      },
      ArrayPrototypePush(self2, el) {
        return self2.push(el);
      },
      ArrayPrototypeSlice(self2, start, end) {
        return self2.slice(start, end);
      },
      Error,
      FunctionPrototypeCall(fn, thisArgs, ...args) {
        return fn.call(thisArgs, ...args);
      },
      FunctionPrototypeSymbolHasInstance(self2, instance) {
        return Function.prototype[Symbol.hasInstance].call(self2, instance);
      },
      MathFloor: Math.floor,
      Number,
      NumberIsInteger: Number.isInteger,
      NumberIsNaN: Number.isNaN,
      NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
      NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
      NumberParseInt: Number.parseInt,
      ObjectDefineProperties(self2, props) {
        return Object.defineProperties(self2, props);
      },
      ObjectDefineProperty(self2, name, prop) {
        return Object.defineProperty(self2, name, prop);
      },
      ObjectGetOwnPropertyDescriptor(self2, name) {
        return Object.getOwnPropertyDescriptor(self2, name);
      },
      ObjectKeys(obj) {
        return Object.keys(obj);
      },
      ObjectSetPrototypeOf(target, proto) {
        return Object.setPrototypeOf(target, proto);
      },
      Promise,
      PromisePrototypeCatch(self2, fn) {
        return self2.catch(fn);
      },
      PromisePrototypeThen(self2, thenFn, catchFn) {
        return self2.then(thenFn, catchFn);
      },
      PromiseReject(err) {
        return Promise.reject(err);
      },
      PromiseResolve(val2) {
        return Promise.resolve(val2);
      },
      ReflectApply: Reflect.apply,
      RegExpPrototypeTest(self2, value) {
        return self2.test(value);
      },
      SafeSet: Set,
      String,
      StringPrototypeSlice(self2, start, end) {
        return self2.slice(start, end);
      },
      StringPrototypeToLowerCase(self2) {
        return self2.toLowerCase();
      },
      StringPrototypeToUpperCase(self2) {
        return self2.toUpperCase();
      },
      StringPrototypeTrim(self2) {
        return self2.trim();
      },
      Symbol,
      SymbolFor: Symbol.for,
      SymbolAsyncIterator: Symbol.asyncIterator,
      SymbolHasInstance: Symbol.hasInstance,
      SymbolIterator: Symbol.iterator,
      SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"),
      SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"),
      TypedArrayPrototypeSet(self2, buf, len) {
        return self2.set(buf, len);
      },
      Boolean,
      Uint8Array
    };
  }
});

// node_modules/abort-controller/browser.js
var require_browser = __commonJS({
  "node_modules/abort-controller/browser.js"(exports, module2) {
    "use strict";
    var { AbortController: AbortController2, AbortSignal: AbortSignal2 } = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : (
      /* otherwise */
      void 0
    );
    module2.exports = AbortController2;
    module2.exports.AbortSignal = AbortSignal2;
    module2.exports.default = AbortController2;
  }
});

// node_modules/events/events.js
var require_events = __commonJS({
  "node_modules/events/events.js"(exports, module2) {
    "use strict";
    var R = typeof Reflect === "object" ? Reflect : null;
    var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
      return Function.prototype.apply.call(target, receiver, args);
    };
    var ReflectOwnKeys;
    if (R && typeof R.ownKeys === "function") {
      ReflectOwnKeys = R.ownKeys;
    } else if (Object.getOwnPropertySymbols) {
      ReflectOwnKeys = function ReflectOwnKeys2(target) {
        return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
      };
    } else {
      ReflectOwnKeys = function ReflectOwnKeys2(target) {
        return Object.getOwnPropertyNames(target);
      };
    }
    function ProcessEmitWarning(warning) {
      if (console && console.warn)
        console.warn(warning);
    }
    var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
      return value !== value;
    };
    function EventEmitter() {
      EventEmitter.init.call(this);
    }
    module2.exports = EventEmitter;
    module2.exports.once = once;
    EventEmitter.EventEmitter = EventEmitter;
    EventEmitter.prototype._events = void 0;
    EventEmitter.prototype._eventsCount = 0;
    EventEmitter.prototype._maxListeners = void 0;
    var defaultMaxListeners = 10;
    function checkListener(listener) {
      if (typeof listener !== "function") {
        throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
      }
    }
    Object.defineProperty(EventEmitter, "defaultMaxListeners", {
      enumerable: true,
      get: function() {
        return defaultMaxListeners;
      },
      set: function(arg) {
        if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
          throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
        }
        defaultMaxListeners = arg;
      }
    });
    EventEmitter.init = function() {
      if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
        this._events = /* @__PURE__ */ Object.create(null);
        this._eventsCount = 0;
      }
      this._maxListeners = this._maxListeners || void 0;
    };
    EventEmitter.prototype.setMaxListeners = function setMaxListeners(n4) {
      if (typeof n4 !== "number" || n4 < 0 || NumberIsNaN(n4)) {
        throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n4 + ".");
      }
      this._maxListeners = n4;
      return this;
    };
    function _getMaxListeners(that) {
      if (that._maxListeners === void 0)
        return EventEmitter.defaultMaxListeners;
      return that._maxListeners;
    }
    EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
      return _getMaxListeners(this);
    };
    EventEmitter.prototype.emit = function emit(type) {
      var args = [];
      for (var i3 = 1; i3 < arguments.length; i3++)
        args.push(arguments[i3]);
      var doError = type === "error";
      var events = this._events;
      if (events !== void 0)
        doError = doError && events.error === void 0;
      else if (!doError)
        return false;
      if (doError) {
        var er;
        if (args.length > 0)
          er = args[0];
        if (er instanceof Error) {
          throw er;
        }
        var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
        err.context = er;
        throw err;
      }
      var handler = events[type];
      if (handler === void 0)
        return false;
      if (typeof handler === "function") {
        ReflectApply(handler, this, args);
      } else {
        var len = handler.length;
        var listeners = arrayClone(handler, len);
        for (var i3 = 0; i3 < len; ++i3)
          ReflectApply(listeners[i3], this, args);
      }
      return true;
    };
    function _addListener(target, type, listener, prepend) {
      var m3;
      var events;
      var existing;
      checkListener(listener);
      events = target._events;
      if (events === void 0) {
        events = target._events = /* @__PURE__ */ Object.create(null);
        target._eventsCount = 0;
      } else {
        if (events.newListener !== void 0) {
          target.emit(
            "newListener",
            type,
            listener.listener ? listener.listener : listener
          );
          events = target._events;
        }
        existing = events[type];
      }
      if (existing === void 0) {
        existing = events[type] = listener;
        ++target._eventsCount;
      } else {
        if (typeof existing === "function") {
          existing = events[type] = prepend ? [listener, existing] : [existing, listener];
        } else if (prepend) {
          existing.unshift(listener);
        } else {
          existing.push(listener);
        }
        m3 = _getMaxListeners(target);
        if (m3 > 0 && existing.length > m3 && !existing.warned) {
          existing.warned = true;
          var w2 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
          w2.name = "MaxListenersExceededWarning";
          w2.emitter = target;
          w2.type = type;
          w2.count = existing.length;
          ProcessEmitWarning(w2);
        }
      }
      return target;
    }
    EventEmitter.prototype.addListener = function addListener(type, listener) {
      return _addListener(this, type, listener, false);
    };
    EventEmitter.prototype.on = EventEmitter.prototype.addListener;
    EventEmitter.prototype.prependListener = function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };
    function onceWrapper() {
      if (!this.fired) {
        this.target.removeListener(this.type, this.wrapFn);
        this.fired = true;
        if (arguments.length === 0)
          return this.listener.call(this.target);
        return this.listener.apply(this.target, arguments);
      }
    }
    function _onceWrap(target, type, listener) {
      var state = { fired: false, wrapFn: void 0, target, type, listener };
      var wrapped = onceWrapper.bind(state);
      wrapped.listener = listener;
      state.wrapFn = wrapped;
      return wrapped;
    }
    EventEmitter.prototype.once = function once2(type, listener) {
      checkListener(listener);
      this.on(type, _onceWrap(this, type, listener));
      return this;
    };
    EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
      checkListener(listener);
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };
    EventEmitter.prototype.removeListener = function removeListener(type, listener) {
      var list, events, position, i3, originalListener;
      checkListener(listener);
      events = this._events;
      if (events === void 0)
        return this;
      list = events[type];
      if (list === void 0)
        return this;
      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = /* @__PURE__ */ Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit("removeListener", type, list.listener || listener);
        }
      } else if (typeof list !== "function") {
        position = -1;
        for (i3 = list.length - 1; i3 >= 0; i3--) {
          if (list[i3] === listener || list[i3].listener === listener) {
            originalListener = list[i3].listener;
            position = i3;
            break;
          }
        }
        if (position < 0)
          return this;
        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }
        if (list.length === 1)
          events[type] = list[0];
        if (events.removeListener !== void 0)
          this.emit("removeListener", type, originalListener || listener);
      }
      return this;
    };
    EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
    EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
      var listeners, events, i3;
      events = this._events;
      if (events === void 0)
        return this;
      if (events.removeListener === void 0) {
        if (arguments.length === 0) {
          this._events = /* @__PURE__ */ Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== void 0) {
          if (--this._eventsCount === 0)
            this._events = /* @__PURE__ */ Object.create(null);
          else
            delete events[type];
        }
        return this;
      }
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i3 = 0; i3 < keys.length; ++i3) {
          key = keys[i3];
          if (key === "removeListener")
            continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners("removeListener");
        this._events = /* @__PURE__ */ Object.create(null);
        this._eventsCount = 0;
        return this;
      }
      listeners = events[type];
      if (typeof listeners === "function") {
        this.removeListener(type, listeners);
      } else if (listeners !== void 0) {
        for (i3 = listeners.length - 1; i3 >= 0; i3--) {
          this.removeListener(type, listeners[i3]);
        }
      }
      return this;
    };
    function _listeners(target, type, unwrap) {
      var events = target._events;
      if (events === void 0)
        return [];
      var evlistener = events[type];
      if (evlistener === void 0)
        return [];
      if (typeof evlistener === "function")
        return unwrap ? [evlistener.listener || evlistener] : [evlistener];
      return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
    }
    EventEmitter.prototype.listeners = function listeners(type) {
      return _listeners(this, type, true);
    };
    EventEmitter.prototype.rawListeners = function rawListeners(type) {
      return _listeners(this, type, false);
    };
    EventEmitter.listenerCount = function(emitter, type) {
      if (typeof emitter.listenerCount === "function") {
        return emitter.listenerCount(type);
      } else {
        return listenerCount.call(emitter, type);
      }
    };
    EventEmitter.prototype.listenerCount = listenerCount;
    function listenerCount(type) {
      var events = this._events;
      if (events !== void 0) {
        var evlistener = events[type];
        if (typeof evlistener === "function") {
          return 1;
        } else if (evlistener !== void 0) {
          return evlistener.length;
        }
      }
      return 0;
    }
    EventEmitter.prototype.eventNames = function eventNames() {
      return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
    };
    function arrayClone(arr2, n4) {
      var copy = new Array(n4);
      for (var i3 = 0; i3 < n4; ++i3)
        copy[i3] = arr2[i3];
      return copy;
    }
    function spliceOne(list, index2) {
      for (; index2 + 1 < list.length; index2++)
        list[index2] = list[index2 + 1];
      list.pop();
    }
    function unwrapListeners(arr2) {
      var ret = new Array(arr2.length);
      for (var i3 = 0; i3 < ret.length; ++i3) {
        ret[i3] = arr2[i3].listener || arr2[i3];
      }
      return ret;
    }
    function once(emitter, name) {
      return new Promise(function(resolve, reject) {
        function errorListener(err) {
          emitter.removeListener(name, resolver);
          reject(err);
        }
        function resolver() {
          if (typeof emitter.removeListener === "function") {
            emitter.removeListener("error", errorListener);
          }
          resolve([].slice.call(arguments));
        }
        ;
        eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
        if (name !== "error") {
          addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
        }
      });
    }
    function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
      if (typeof emitter.on === "function") {
        eventTargetAgnosticAddListener(emitter, "error", handler, flags);
      }
    }
    function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
      if (typeof emitter.on === "function") {
        if (flags.once) {
          emitter.once(name, listener);
        } else {
          emitter.on(name, listener);
        }
      } else if (typeof emitter.addEventListener === "function") {
        emitter.addEventListener(name, function wrapListener(arg) {
          if (flags.once) {
            emitter.removeEventListener(name, wrapListener);
          }
          listener(arg);
        });
      } else {
        throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
      }
    }
  }
});

// node_modules/readable-stream/lib/ours/util.js
var require_util3 = __commonJS({
  "node_modules/readable-stream/lib/ours/util.js"(exports, module2) {
    "use strict";
    var bufferModule = require_buffer();
    var { kResistStopPropagation, SymbolDispose } = require_primordials();
    var AbortSignal2 = globalThis.AbortSignal || require_browser().AbortSignal;
    var AbortController2 = globalThis.AbortController || require_browser().AbortController;
    var AsyncFunction = Object.getPrototypeOf(async function() {
    }).constructor;
    var Blob5 = globalThis.Blob || bufferModule.Blob;
    var isBlob = typeof Blob5 !== "undefined" ? function isBlob2(b3) {
      return b3 instanceof Blob5;
    } : function isBlob2(b3) {
      return false;
    };
    var validateAbortSignal = (signal, name) => {
      if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
        throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
      }
    };
    var validateFunction = (value, name) => {
      if (typeof value !== "function")
        throw new ERR_INVALID_ARG_TYPE(name, "Function", value);
    };
    var AggregateError2 = class extends Error {
      constructor(errors2) {
        if (!Array.isArray(errors2)) {
          throw new TypeError(`Expected input to be an Array, got ${typeof errors2}`);
        }
        let message = "";
        for (let i3 = 0; i3 < errors2.length; i3++) {
          message += `    ${errors2[i3].stack}
`;
        }
        super(message);
        this.name = "AggregateError";
        this.errors = errors2;
      }
    };
    module2.exports = {
      AggregateError: AggregateError2,
      kEmptyObject: Object.freeze({}),
      once(callback) {
        let called = false;
        return function(...args) {
          if (called) {
            return;
          }
          called = true;
          callback.apply(this, args);
        };
      },
      createDeferredPromise: function() {
        let resolve;
        let reject;
        const promise = new Promise((res, rej) => {
          resolve = res;
          reject = rej;
        });
        return {
          promise,
          resolve,
          reject
        };
      },
      promisify(fn) {
        return new Promise((resolve, reject) => {
          fn((err, ...args) => {
            if (err) {
              return reject(err);
            }
            return resolve(...args);
          });
        });
      },
      debuglog() {
        return function() {
        };
      },
      format(format, ...args) {
        return format.replace(/%([sdifj])/g, function(...[_unused, type]) {
          const replacement = args.shift();
          if (type === "f") {
            return replacement.toFixed(6);
          } else if (type === "j") {
            return JSON.stringify(replacement);
          } else if (type === "s" && typeof replacement === "object") {
            const ctor = replacement.constructor !== Object ? replacement.constructor.name : "";
            return `${ctor} {}`.trim();
          } else {
            return replacement.toString();
          }
        });
      },
      inspect(value) {
        switch (typeof value) {
          case "string":
            if (value.includes("'")) {
              if (!value.includes('"')) {
                return `"${value}"`;
              } else if (!value.includes("`") && !value.includes("${")) {
                return `\`${value}\``;
              }
            }
            return `'${value}'`;
          case "number":
            if (isNaN(value)) {
              return "NaN";
            } else if (Object.is(value, -0)) {
              return String(value);
            }
            return value;
          case "bigint":
            return `${String(value)}n`;
          case "boolean":
          case "undefined":
            return String(value);
          case "object":
            return "{}";
        }
      },
      types: {
        isAsyncFunction(fn) {
          return fn instanceof AsyncFunction;
        },
        isArrayBufferView(arr2) {
          return ArrayBuffer.isView(arr2);
        }
      },
      isBlob,
      deprecate(fn, message) {
        return fn;
      },
      addAbortListener: require_events().addAbortListener || function addAbortListener(signal, listener) {
        if (signal === void 0) {
          throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal);
        }
        validateAbortSignal(signal, "signal");
        validateFunction(listener, "listener");
        let removeEventListener;
        if (signal.aborted) {
          queueMicrotask(() => listener());
        } else {
          signal.addEventListener("abort", listener, {
            __proto__: null,
            once: true,
            [kResistStopPropagation]: true
          });
          removeEventListener = () => {
            signal.removeEventListener("abort", listener);
          };
        }
        return {
          __proto__: null,
          [SymbolDispose]() {
            var _removeEventListener;
            (_removeEventListener = removeEventListener) === null || _removeEventListener === void 0 ? void 0 : _removeEventListener();
          }
        };
      },
      AbortSignalAny: AbortSignal2.any || function AbortSignalAny(signals) {
        if (signals.length === 1) {
          return signals[0];
        }
        const ac = new AbortController2();
        const abort = () => ac.abort();
        signals.forEach((signal) => {
          validateAbortSignal(signal, "signals");
          signal.addEventListener("abort", abort, {
            once: true
          });
        });
        ac.signal.addEventListener(
          "abort",
          () => {
            signals.forEach((signal) => signal.removeEventListener("abort", abort));
          },
          {
            once: true
          }
        );
        return ac.signal;
      }
    };
    module2.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom");
  }
});

// node_modules/readable-stream/lib/ours/errors.js
var require_errors3 = __commonJS({
  "node_modules/readable-stream/lib/ours/errors.js"(exports, module2) {
    "use strict";
    var { format, inspect, AggregateError: CustomAggregateError } = require_util3();
    var AggregateError2 = globalThis.AggregateError || CustomAggregateError;
    var kIsNodeError = Symbol("kIsNodeError");
    var kTypes = [
      "string",
      "function",
      "number",
      "object",
      // Accept 'Function' and 'Object' as alternative to the lower cased version.
      "Function",
      "Object",
      "boolean",
      "bigint",
      "symbol"
    ];
    var classRegExp = /^([A-Z][a-z0-9]*)+$/;
    var nodeInternalPrefix = "__node_internal_";
    var codes = {};
    function assert(value, message) {
      if (!value) {
        throw new codes.ERR_INTERNAL_ASSERTION(message);
      }
    }
    function addNumericalSeparator(val2) {
      let res = "";
      let i3 = val2.length;
      const start = val2[0] === "-" ? 1 : 0;
      for (; i3 >= start + 4; i3 -= 3) {
        res = `_${val2.slice(i3 - 3, i3)}${res}`;
      }
      return `${val2.slice(0, i3)}${res}`;
    }
    function getMessage(key, msg, args) {
      if (typeof msg === "function") {
        assert(
          msg.length <= args.length,
          // Default options do not count.
          `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`
        );
        return msg(...args);
      }
      const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length;
      assert(
        expectedLength === args.length,
        `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`
      );
      if (args.length === 0) {
        return msg;
      }
      return format(msg, ...args);
    }
    function E2(code, message, Base) {
      if (!Base) {
        Base = Error;
      }
      class NodeError extends Base {
        constructor(...args) {
          super(getMessage(code, message, args));
        }
        toString() {
          return `${this.name} [${code}]: ${this.message}`;
        }
      }
      Object.defineProperties(NodeError.prototype, {
        name: {
          value: Base.name,
          writable: true,
          enumerable: false,
          configurable: true
        },
        toString: {
          value() {
            return `${this.name} [${code}]: ${this.message}`;
          },
          writable: true,
          enumerable: false,
          configurable: true
        }
      });
      NodeError.prototype.code = code;
      NodeError.prototype[kIsNodeError] = true;
      codes[code] = NodeError;
    }
    function hideStackFrames(fn) {
      const hidden = nodeInternalPrefix + fn.name;
      Object.defineProperty(fn, "name", {
        value: hidden
      });
      return fn;
    }
    function aggregateTwoErrors(innerError, outerError) {
      if (innerError && outerError && innerError !== outerError) {
        if (Array.isArray(outerError.errors)) {
          outerError.errors.push(innerError);
          return outerError;
        }
        const err = new AggregateError2([outerError, innerError], outerError.message);
        err.code = outerError.code;
        return err;
      }
      return innerError || outerError;
    }
    var AbortError = class extends Error {
      constructor(message = "The operation was aborted", options = void 0) {
        if (options !== void 0 && typeof options !== "object") {
          throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options);
        }
        super(message, options);
        this.code = "ABORT_ERR";
        this.name = "AbortError";
      }
    };
    E2("ERR_ASSERTION", "%s", Error);
    E2(
      "ERR_INVALID_ARG_TYPE",
      (name, expected, actual) => {
        assert(typeof name === "string", "'name' must be a string");
        if (!Array.isArray(expected)) {
          expected = [expected];
        }
        let msg = "The ";
        if (name.endsWith(" argument")) {
          msg += `${name} `;
        } else {
          msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `;
        }
        msg += "must be ";
        const types = [];
        const instances = [];
        const other = [];
        for (const value of expected) {
          assert(typeof value === "string", "All expected entries have to be of type string");
          if (kTypes.includes(value)) {
            types.push(value.toLowerCase());
          } else if (classRegExp.test(value)) {
            instances.push(value);
          } else {
            assert(value !== "object", 'The value "object" should be written as "Object"');
            other.push(value);
          }
        }
        if (instances.length > 0) {
          const pos = types.indexOf("object");
          if (pos !== -1) {
            types.splice(types, pos, 1);
            instances.push("Object");
          }
        }
        if (types.length > 0) {
          switch (types.length) {
            case 1:
              msg += `of type ${types[0]}`;
              break;
            case 2:
              msg += `one of type ${types[0]} or ${types[1]}`;
              break;
            default: {
              const last = types.pop();
              msg += `one of type ${types.join(", ")}, or ${last}`;
            }
          }
          if (instances.length > 0 || other.length > 0) {
            msg += " or ";
          }
        }
        if (instances.length > 0) {
          switch (instances.length) {
            case 1:
              msg += `an instance of ${instances[0]}`;
              break;
            case 2:
              msg += `an instance of ${instances[0]} or ${instances[1]}`;
              break;
            default: {
              const last = instances.pop();
              msg += `an instance of ${instances.join(", ")}, or ${last}`;
            }
          }
          if (other.length > 0) {
            msg += " or ";
          }
        }
        switch (other.length) {
          case 0:
            break;
          case 1:
            if (other[0].toLowerCase() !== other[0]) {
              msg += "an ";
            }
            msg += `${other[0]}`;
            break;
          case 2:
            msg += `one of ${other[0]} or ${other[1]}`;
            break;
          default: {
            const last = other.pop();
            msg += `one of ${other.join(", ")}, or ${last}`;
          }
        }
        if (actual == null) {
          msg += `. Received ${actual}`;
        } else if (typeof actual === "function" && actual.name) {
          msg += `. Received function ${actual.name}`;
        } else if (typeof actual === "object") {
          var _actual$constructor;
          if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) {
            msg += `. Received an instance of ${actual.constructor.name}`;
          } else {
            const inspected = inspect(actual, {
              depth: -1
            });
            msg += `. Received ${inspected}`;
          }
        } else {
          let inspected = inspect(actual, {
            colors: false
          });
          if (inspected.length > 25) {
            inspected = `${inspected.slice(0, 25)}...`;
          }
          msg += `. Received type ${typeof actual} (${inspected})`;
        }
        return msg;
      },
      TypeError
    );
    E2(
      "ERR_INVALID_ARG_VALUE",
      (name, value, reason = "is invalid") => {
        let inspected = inspect(value);
        if (inspected.length > 128) {
          inspected = inspected.slice(0, 128) + "...";
        }
        const type = name.includes(".") ? "property" : "argument";
        return `The ${type} '${name}' ${reason}. Received ${inspected}`;
      },
      TypeError
    );
    E2(
      "ERR_INVALID_RETURN_VALUE",
      (input, name, value) => {
        var _value$constructor;
        const type = value !== null && value !== void 0 && (_value$constructor = value.constructor) !== null && _value$constructor !== void 0 && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`;
        return `Expected ${input} to be returned from the "${name}" function but got ${type}.`;
      },
      TypeError
    );
    E2(
      "ERR_MISSING_ARGS",
      (...args) => {
        assert(args.length > 0, "At least one arg needs to be specified");
        let msg;
        const len = args.length;
        args = (Array.isArray(args) ? args : [args]).map((a3) => `"${a3}"`).join(" or ");
        switch (len) {
          case 1:
            msg += `The ${args[0]} argument`;
            break;
          case 2:
            msg += `The ${args[0]} and ${args[1]} arguments`;
            break;
          default:
            {
              const last = args.pop();
              msg += `The ${args.join(", ")}, and ${last} arguments`;
            }
            break;
        }
        return `${msg} must be specified`;
      },
      TypeError
    );
    E2(
      "ERR_OUT_OF_RANGE",
      (str2, range, input) => {
        assert(range, 'Missing "range" argument');
        let received;
        if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
          received = addNumericalSeparator(String(input));
        } else if (typeof input === "bigint") {
          received = String(input);
          if (input > 2n ** 32n || input < -(2n ** 32n)) {
            received = addNumericalSeparator(received);
          }
          received += "n";
        } else {
          received = inspect(input);
        }
        return `The value of "${str2}" is out of range. It must be ${range}. Received ${received}`;
      },
      RangeError
    );
    E2("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error);
    E2("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error);
    E2("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error);
    E2("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error);
    E2("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error);
    E2("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
    E2("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error);
    E2("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error);
    E2("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error);
    E2("ERR_STREAM_WRITE_AFTER_END", "write after end", Error);
    E2("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError);
    module2.exports = {
      AbortError,
      aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),
      hideStackFrames,
      codes
    };
  }
});

// node_modules/readable-stream/lib/internal/validators.js
var require_validators = __commonJS({
  "node_modules/readable-stream/lib/internal/validators.js"(exports, module2) {
    "use strict";
    var {
      ArrayIsArray,
      ArrayPrototypeIncludes,
      ArrayPrototypeJoin,
      ArrayPrototypeMap,
      NumberIsInteger,
      NumberIsNaN,
      NumberMAX_SAFE_INTEGER,
      NumberMIN_SAFE_INTEGER,
      NumberParseInt,
      ObjectPrototypeHasOwnProperty,
      RegExpPrototypeExec,
      String: String2,
      StringPrototypeToUpperCase,
      StringPrototypeTrim
    } = require_primordials();
    var {
      hideStackFrames,
      codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }
    } = require_errors3();
    var { normalizeEncoding } = require_util3();
    var { isAsyncFunction: isAsyncFunction2, isArrayBufferView } = require_util3().types;
    var signals = {};
    function isInt32(value) {
      return value === (value | 0);
    }
    function isUint32(value) {
      return value === value >>> 0;
    }
    var octalReg = /^[0-7]+$/;
    var modeDesc = "must be a 32-bit unsigned integer or an octal string";
    function parseFileMode(value, name, def) {
      if (typeof value === "undefined") {
        value = def;
      }
      if (typeof value === "string") {
        if (RegExpPrototypeExec(octalReg, value) === null) {
          throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
        }
        value = NumberParseInt(value, 8);
      }
      validateUint32(value, name);
      return value;
    }
    var validateInteger = hideStackFrames((value, name, min2 = NumberMIN_SAFE_INTEGER, max2 = NumberMAX_SAFE_INTEGER) => {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
      if (!NumberIsInteger(value))
        throw new ERR_OUT_OF_RANGE(name, "an integer", value);
      if (value < min2 || value > max2)
        throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value);
    });
    var validateInt32 = hideStackFrames((value, name, min2 = -2147483648, max2 = 2147483647) => {
      if (typeof value !== "number") {
        throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
      }
      if (!NumberIsInteger(value)) {
        throw new ERR_OUT_OF_RANGE(name, "an integer", value);
      }
      if (value < min2 || value > max2) {
        throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value);
      }
    });
    var validateUint32 = hideStackFrames((value, name, positive = false) => {
      if (typeof value !== "number") {
        throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
      }
      if (!NumberIsInteger(value)) {
        throw new ERR_OUT_OF_RANGE(name, "an integer", value);
      }
      const min2 = positive ? 1 : 0;
      const max2 = 4294967295;
      if (value < min2 || value > max2) {
        throw new ERR_OUT_OF_RANGE(name, `>= ${min2} && <= ${max2}`, value);
      }
    });
    function validateString(value, name) {
      if (typeof value !== "string")
        throw new ERR_INVALID_ARG_TYPE2(name, "string", value);
    }
    function validateNumber(value, name, min2 = void 0, max2) {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
      if (min2 != null && value < min2 || max2 != null && value > max2 || (min2 != null || max2 != null) && NumberIsNaN(value)) {
        throw new ERR_OUT_OF_RANGE(
          name,
          `${min2 != null ? `>= ${min2}` : ""}${min2 != null && max2 != null ? " && " : ""}${max2 != null ? `<= ${max2}` : ""}`,
          value
        );
      }
    }
    var validateOneOf = hideStackFrames((value, name, oneOf2) => {
      if (!ArrayPrototypeIncludes(oneOf2, value)) {
        const allowed = ArrayPrototypeJoin(
          ArrayPrototypeMap(oneOf2, (v5) => typeof v5 === "string" ? `'${v5}'` : String2(v5)),
          ", "
        );
        const reason = "must be one of: " + allowed;
        throw new ERR_INVALID_ARG_VALUE(name, value, reason);
      }
    });
    function validateBoolean(value, name) {
      if (typeof value !== "boolean")
        throw new ERR_INVALID_ARG_TYPE2(name, "boolean", value);
    }
    function getOwnPropertyValueOrDefault(options, key, defaultValue) {
      return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key];
    }
    var validateObject = hideStackFrames((value, name, options = null) => {
      const allowArray = getOwnPropertyValueOrDefault(options, "allowArray", false);
      const allowFunction = getOwnPropertyValueOrDefault(options, "allowFunction", false);
      const nullable = getOwnPropertyValueOrDefault(options, "nullable", false);
      if (!nullable && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) {
        throw new ERR_INVALID_ARG_TYPE2(name, "Object", value);
      }
    });
    var validateDictionary = hideStackFrames((value, name) => {
      if (value != null && typeof value !== "object" && typeof value !== "function") {
        throw new ERR_INVALID_ARG_TYPE2(name, "a dictionary", value);
      }
    });
    var validateArray = hideStackFrames((value, name, minLength = 0) => {
      if (!ArrayIsArray(value)) {
        throw new ERR_INVALID_ARG_TYPE2(name, "Array", value);
      }
      if (value.length < minLength) {
        const reason = `must be longer than ${minLength}`;
        throw new ERR_INVALID_ARG_VALUE(name, value, reason);
      }
    });
    function validateStringArray(value, name) {
      validateArray(value, name);
      for (let i3 = 0; i3 < value.length; i3++) {
        validateString(value[i3], `${name}[${i3}]`);
      }
    }
    function validateBooleanArray(value, name) {
      validateArray(value, name);
      for (let i3 = 0; i3 < value.length; i3++) {
        validateBoolean(value[i3], `${name}[${i3}]`);
      }
    }
    function validateAbortSignalArray(value, name) {
      validateArray(value, name);
      for (let i3 = 0; i3 < value.length; i3++) {
        const signal = value[i3];
        const indexedName = `${name}[${i3}]`;
        if (signal == null) {
          throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal);
        }
        validateAbortSignal(signal, indexedName);
      }
    }
    function validateSignalName(signal, name = "signal") {
      validateString(signal, name);
      if (signals[signal] === void 0) {
        if (signals[StringPrototypeToUpperCase(signal)] !== void 0) {
          throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)");
        }
        throw new ERR_UNKNOWN_SIGNAL(signal);
      }
    }
    var validateBuffer = hideStackFrames((buffer, name = "buffer") => {
      if (!isArrayBufferView(buffer)) {
        throw new ERR_INVALID_ARG_TYPE2(name, ["Buffer", "TypedArray", "DataView"], buffer);
      }
    });
    function validateEncoding(data, encoding) {
      const normalizedEncoding = normalizeEncoding(encoding);
      const length = data.length;
      if (normalizedEncoding === "hex" && length % 2 !== 0) {
        throw new ERR_INVALID_ARG_VALUE("encoding", encoding, `is invalid for data of length ${length}`);
      }
    }
    function validatePort(port, name = "Port", allowZero = true) {
      if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero) {
        throw new ERR_SOCKET_BAD_PORT(name, port, allowZero);
      }
      return port | 0;
    }
    var validateAbortSignal = hideStackFrames((signal, name) => {
      if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
        throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal);
      }
    });
    var validateFunction = hideStackFrames((value, name) => {
      if (typeof value !== "function")
        throw new ERR_INVALID_ARG_TYPE2(name, "Function", value);
    });
    var validatePlainFunction = hideStackFrames((value, name) => {
      if (typeof value !== "function" || isAsyncFunction2(value))
        throw new ERR_INVALID_ARG_TYPE2(name, "Function", value);
    });
    var validateUndefined = hideStackFrames((value, name) => {
      if (value !== void 0)
        throw new ERR_INVALID_ARG_TYPE2(name, "undefined", value);
    });
    function validateUnion(value, name, union) {
      if (!ArrayPrototypeIncludes(union, value)) {
        throw new ERR_INVALID_ARG_TYPE2(name, `('${ArrayPrototypeJoin(union, "|")}')`, value);
      }
    }
    var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
    function validateLinkHeaderFormat(value, name) {
      if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) {
        throw new ERR_INVALID_ARG_VALUE(
          name,
          value,
          'must be an array or string of format "</styles.css>; rel=preload; as=style"'
        );
      }
    }
    function validateLinkHeaderValue(hints) {
      if (typeof hints === "string") {
        validateLinkHeaderFormat(hints, "hints");
        return hints;
      } else if (ArrayIsArray(hints)) {
        const hintsLength = hints.length;
        let result = "";
        if (hintsLength === 0) {
          return result;
        }
        for (let i3 = 0; i3 < hintsLength; i3++) {
          const link = hints[i3];
          validateLinkHeaderFormat(link, "hints");
          result += link;
          if (i3 !== hintsLength - 1) {
            result += ", ";
          }
        }
        return result;
      }
      throw new ERR_INVALID_ARG_VALUE(
        "hints",
        hints,
        'must be an array or string of format "</styles.css>; rel=preload; as=style"'
      );
    }
    module2.exports = {
      isInt32,
      isUint32,
      parseFileMode,
      validateArray,
      validateStringArray,
      validateBooleanArray,
      validateAbortSignalArray,
      validateBoolean,
      validateBuffer,
      validateDictionary,
      validateEncoding,
      validateFunction,
      validateInt32,
      validateInteger,
      validateNumber,
      validateObject,
      validateOneOf,
      validatePlainFunction,
      validatePort,
      validateSignalName,
      validateString,
      validateUint32,
      validateUndefined,
      validateUnion,
      validateAbortSignal,
      validateLinkHeaderValue
    };
  }
});

// node_modules/process/browser.js
var require_browser2 = __commonJS({
  "node_modules/process/browser.js"(exports, module2) {
    var process2 = module2.exports = {};
    var cachedSetTimeout;
    var cachedClearTimeout;
    function defaultSetTimout() {
      throw new Error("setTimeout has not been defined");
    }
    function defaultClearTimeout() {
      throw new Error("clearTimeout has not been defined");
    }
    (function() {
      try {
        if (typeof setTimeout === "function") {
          cachedSetTimeout = setTimeout;
        } else {
          cachedSetTimeout = defaultSetTimout;
        }
      } catch (e3) {
        cachedSetTimeout = defaultSetTimout;
      }
      try {
        if (typeof clearTimeout === "function") {
          cachedClearTimeout = clearTimeout;
        } else {
          cachedClearTimeout = defaultClearTimeout;
        }
      } catch (e3) {
        cachedClearTimeout = defaultClearTimeout;
      }
    })();
    function runTimeout(fun) {
      if (cachedSetTimeout === setTimeout) {
        return setTimeout(fun, 0);
      }
      if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
      }
      try {
        return cachedSetTimeout(fun, 0);
      } catch (e3) {
        try {
          return cachedSetTimeout.call(null, fun, 0);
        } catch (e4) {
          return cachedSetTimeout.call(this, fun, 0);
        }
      }
    }
    function runClearTimeout(marker) {
      if (cachedClearTimeout === clearTimeout) {
        return clearTimeout(marker);
      }
      if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
      }
      try {
        return cachedClearTimeout(marker);
      } catch (e3) {
        try {
          return cachedClearTimeout.call(null, marker);
        } catch (e4) {
          return cachedClearTimeout.call(this, marker);
        }
      }
    }
    var queue2 = [];
    var draining = false;
    var currentQueue;
    var queueIndex = -1;
    function cleanUpNextTick() {
      if (!draining || !currentQueue) {
        return;
      }
      draining = false;
      if (currentQueue.length) {
        queue2 = currentQueue.concat(queue2);
      } else {
        queueIndex = -1;
      }
      if (queue2.length) {
        drainQueue();
      }
    }
    function drainQueue() {
      if (draining) {
        return;
      }
      var timeout = runTimeout(cleanUpNextTick);
      draining = true;
      var len = queue2.length;
      while (len) {
        currentQueue = queue2;
        queue2 = [];
        while (++queueIndex < len) {
          if (currentQueue) {
            currentQueue[queueIndex].run();
          }
        }
        queueIndex = -1;
        len = queue2.length;
      }
      currentQueue = null;
      draining = false;
      runClearTimeout(timeout);
    }
    process2.nextTick = function(fun) {
      var args = new Array(arguments.length - 1);
      if (arguments.length > 1) {
        for (var i3 = 1; i3 < arguments.length; i3++) {
          args[i3 - 1] = arguments[i3];
        }
      }
      queue2.push(new Item4(fun, args));
      if (queue2.length === 1 && !draining) {
        runTimeout(drainQueue);
      }
    };
    function Item4(fun, array) {
      this.fun = fun;
      this.array = array;
    }
    Item4.prototype.run = function() {
      this.fun.apply(null, this.array);
    };
    process2.title = "browser";
    process2.browser = true;
    process2.env = {};
    process2.argv = [];
    process2.version = "";
    process2.versions = {};
    function noop2() {
    }
    process2.on = noop2;
    process2.addListener = noop2;
    process2.once = noop2;
    process2.off = noop2;
    process2.removeListener = noop2;
    process2.removeAllListeners = noop2;
    process2.emit = noop2;
    process2.prependListener = noop2;
    process2.prependOnceListener = noop2;
    process2.listeners = function(name) {
      return [];
    };
    process2.binding = function(name) {
      throw new Error("process.binding is not supported");
    };
    process2.cwd = function() {
      return "/";
    };
    process2.chdir = function(dir) {
      throw new Error("process.chdir is not supported");
    };
    process2.umask = function() {
      return 0;
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/utils.js
var require_utils = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/utils.js"(exports, module2) {
    "use strict";
    var { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require_primordials();
    var kIsDestroyed = SymbolFor("nodejs.stream.destroyed");
    var kIsErrored = SymbolFor("nodejs.stream.errored");
    var kIsReadable = SymbolFor("nodejs.stream.readable");
    var kIsWritable = SymbolFor("nodejs.stream.writable");
    var kIsDisturbed = SymbolFor("nodejs.stream.disturbed");
    var kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise");
    var kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction");
    function isReadableNodeStream(obj, strict2 = false) {
      var _obj$_readableState;
      return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict2 || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex
      (!obj._writableState || obj._readableState));
    }
    function isWritableNodeStream(obj) {
      var _obj$_writableState;
      return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false));
    }
    function isDuplexNodeStream(obj) {
      return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function");
    }
    function isNodeStream(obj) {
      return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function");
    }
    function isReadableStream2(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function");
    }
    function isWritableStream(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function");
    }
    function isTransformStream(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object");
    }
    function isWebStream(obj) {
      return isReadableStream2(obj) || isWritableStream(obj) || isTransformStream(obj);
    }
    function isIterable(obj, isAsync2) {
      if (obj == null)
        return false;
      if (isAsync2 === true)
        return typeof obj[SymbolAsyncIterator] === "function";
      if (isAsync2 === false)
        return typeof obj[SymbolIterator] === "function";
      return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function";
    }
    function isDestroyed(stream) {
      if (!isNodeStream(stream))
        return null;
      const wState = stream._writableState;
      const rState = stream._readableState;
      const state = wState || rState;
      return !!(stream.destroyed || stream[kIsDestroyed] || state !== null && state !== void 0 && state.destroyed);
    }
    function isWritableEnded(stream) {
      if (!isWritableNodeStream(stream))
        return null;
      if (stream.writableEnded === true)
        return true;
      const wState = stream._writableState;
      if (wState !== null && wState !== void 0 && wState.errored)
        return false;
      if (typeof (wState === null || wState === void 0 ? void 0 : wState.ended) !== "boolean")
        return null;
      return wState.ended;
    }
    function isWritableFinished(stream, strict2) {
      if (!isWritableNodeStream(stream))
        return null;
      if (stream.writableFinished === true)
        return true;
      const wState = stream._writableState;
      if (wState !== null && wState !== void 0 && wState.errored)
        return false;
      if (typeof (wState === null || wState === void 0 ? void 0 : wState.finished) !== "boolean")
        return null;
      return !!(wState.finished || strict2 === false && wState.ended === true && wState.length === 0);
    }
    function isReadableEnded(stream) {
      if (!isReadableNodeStream(stream))
        return null;
      if (stream.readableEnded === true)
        return true;
      const rState = stream._readableState;
      if (!rState || rState.errored)
        return false;
      if (typeof (rState === null || rState === void 0 ? void 0 : rState.ended) !== "boolean")
        return null;
      return rState.ended;
    }
    function isReadableFinished(stream, strict2) {
      if (!isReadableNodeStream(stream))
        return null;
      const rState = stream._readableState;
      if (rState !== null && rState !== void 0 && rState.errored)
        return false;
      if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean")
        return null;
      return !!(rState.endEmitted || strict2 === false && rState.ended === true && rState.length === 0);
    }
    function isReadable(stream) {
      if (stream && stream[kIsReadable] != null)
        return stream[kIsReadable];
      if (typeof (stream === null || stream === void 0 ? void 0 : stream.readable) !== "boolean")
        return null;
      if (isDestroyed(stream))
        return false;
      return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream);
    }
    function isWritable(stream) {
      if (stream && stream[kIsWritable] != null)
        return stream[kIsWritable];
      if (typeof (stream === null || stream === void 0 ? void 0 : stream.writable) !== "boolean")
        return null;
      if (isDestroyed(stream))
        return false;
      return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream);
    }
    function isFinished(stream, opts) {
      if (!isNodeStream(stream)) {
        return null;
      }
      if (isDestroyed(stream)) {
        return true;
      }
      if ((opts === null || opts === void 0 ? void 0 : opts.readable) !== false && isReadable(stream)) {
        return false;
      }
      if ((opts === null || opts === void 0 ? void 0 : opts.writable) !== false && isWritable(stream)) {
        return false;
      }
      return true;
    }
    function isWritableErrored(stream) {
      var _stream$_writableStat, _stream$_writableStat2;
      if (!isNodeStream(stream)) {
        return null;
      }
      if (stream.writableErrored) {
        return stream.writableErrored;
      }
      return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === void 0 ? void 0 : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== void 0 ? _stream$_writableStat : null;
    }
    function isReadableErrored(stream) {
      var _stream$_readableStat, _stream$_readableStat2;
      if (!isNodeStream(stream)) {
        return null;
      }
      if (stream.readableErrored) {
        return stream.readableErrored;
      }
      return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === void 0 ? void 0 : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== void 0 ? _stream$_readableStat : null;
    }
    function isClosed(stream) {
      if (!isNodeStream(stream)) {
        return null;
      }
      if (typeof stream.closed === "boolean") {
        return stream.closed;
      }
      const wState = stream._writableState;
      const rState = stream._readableState;
      if (typeof (wState === null || wState === void 0 ? void 0 : wState.closed) === "boolean" || typeof (rState === null || rState === void 0 ? void 0 : rState.closed) === "boolean") {
        return (wState === null || wState === void 0 ? void 0 : wState.closed) || (rState === null || rState === void 0 ? void 0 : rState.closed);
      }
      if (typeof stream._closed === "boolean" && isOutgoingMessage(stream)) {
        return stream._closed;
      }
      return null;
    }
    function isOutgoingMessage(stream) {
      return typeof stream._closed === "boolean" && typeof stream._defaultKeepAlive === "boolean" && typeof stream._removedConnection === "boolean" && typeof stream._removedContLen === "boolean";
    }
    function isServerResponse(stream) {
      return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream);
    }
    function isServerRequest(stream) {
      var _stream$req;
      return typeof stream._consuming === "boolean" && typeof stream._dumped === "boolean" && ((_stream$req = stream.req) === null || _stream$req === void 0 ? void 0 : _stream$req.upgradeOrConnect) === void 0;
    }
    function willEmitClose(stream) {
      if (!isNodeStream(stream))
        return null;
      const wState = stream._writableState;
      const rState = stream._readableState;
      const state = wState || rState;
      return !state && isServerResponse(stream) || !!(state && state.autoDestroy && state.emitClose && state.closed === false);
    }
    function isDisturbed(stream) {
      var _stream$kIsDisturbed;
      return !!(stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== void 0 ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted));
    }
    function isErrored(stream) {
      var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4;
      return !!(stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== void 0 ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== void 0 ? _ref5 : stream.writableErrored) !== null && _ref4 !== void 0 ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === void 0 ? void 0 : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== void 0 ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === void 0 ? void 0 : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== void 0 ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === void 0 ? void 0 : _stream$_readableStat4.errored) !== null && _ref !== void 0 ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === void 0 ? void 0 : _stream$_writableStat4.errored));
    }
    module2.exports = {
      isDestroyed,
      kIsDestroyed,
      isDisturbed,
      kIsDisturbed,
      isErrored,
      kIsErrored,
      isReadable,
      kIsReadable,
      kIsClosedPromise,
      kControllerErrorFunction,
      kIsWritable,
      isClosed,
      isDuplexNodeStream,
      isFinished,
      isIterable,
      isReadableNodeStream,
      isReadableStream: isReadableStream2,
      isReadableEnded,
      isReadableFinished,
      isReadableErrored,
      isNodeStream,
      isWebStream,
      isWritable,
      isWritableNodeStream,
      isWritableStream,
      isWritableEnded,
      isWritableFinished,
      isWritableErrored,
      isServerRequest,
      isServerResponse,
      willEmitClose,
      isTransformStream
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/end-of-stream.js
var require_end_of_stream = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports, module2) {
    var process2 = require_browser2();
    var { AbortError, codes } = require_errors3();
    var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_PREMATURE_CLOSE } = codes;
    var { kEmptyObject, once } = require_util3();
    var { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require_validators();
    var { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials();
    var {
      isClosed,
      isReadable,
      isReadableNodeStream,
      isReadableStream: isReadableStream2,
      isReadableFinished,
      isReadableErrored,
      isWritable,
      isWritableNodeStream,
      isWritableStream,
      isWritableFinished,
      isWritableErrored,
      isNodeStream,
      willEmitClose: _willEmitClose,
      kIsClosedPromise
    } = require_utils();
    var addAbortListener;
    function isRequest(stream) {
      return stream.setHeader && typeof stream.abort === "function";
    }
    var nop = () => {
    };
    function eos2(stream, options, callback) {
      var _options$readable, _options$writable;
      if (arguments.length === 2) {
        callback = options;
        options = kEmptyObject;
      } else if (options == null) {
        options = kEmptyObject;
      } else {
        validateObject(options, "options");
      }
      validateFunction(callback, "callback");
      validateAbortSignal(options.signal, "options.signal");
      callback = once(callback);
      if (isReadableStream2(stream) || isWritableStream(stream)) {
        return eosWeb(stream, options, callback);
      }
      if (!isNodeStream(stream)) {
        throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
      }
      const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream);
      const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream);
      const wState = stream._writableState;
      const rState = stream._readableState;
      const onlegacyfinish = () => {
        if (!stream.writable) {
          onfinish();
        }
      };
      let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable;
      let writableFinished = isWritableFinished(stream, false);
      const onfinish = () => {
        writableFinished = true;
        if (stream.destroyed) {
          willEmitClose = false;
        }
        if (willEmitClose && (!stream.readable || readable)) {
          return;
        }
        if (!readable || readableFinished) {
          callback.call(stream);
        }
      };
      let readableFinished = isReadableFinished(stream, false);
      const onend = () => {
        readableFinished = true;
        if (stream.destroyed) {
          willEmitClose = false;
        }
        if (willEmitClose && (!stream.writable || writable)) {
          return;
        }
        if (!writable || writableFinished) {
          callback.call(stream);
        }
      };
      const onerror = (err) => {
        callback.call(stream, err);
      };
      let closed = isClosed(stream);
      const onclose = () => {
        closed = true;
        const errored = isWritableErrored(stream) || isReadableErrored(stream);
        if (errored && typeof errored !== "boolean") {
          return callback.call(stream, errored);
        }
        if (readable && !readableFinished && isReadableNodeStream(stream, true)) {
          if (!isReadableFinished(stream, false))
            return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
        }
        if (writable && !writableFinished) {
          if (!isWritableFinished(stream, false))
            return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
        }
        callback.call(stream);
      };
      const onclosed = () => {
        closed = true;
        const errored = isWritableErrored(stream) || isReadableErrored(stream);
        if (errored && typeof errored !== "boolean") {
          return callback.call(stream, errored);
        }
        callback.call(stream);
      };
      const onrequest = () => {
        stream.req.on("finish", onfinish);
      };
      if (isRequest(stream)) {
        stream.on("complete", onfinish);
        if (!willEmitClose) {
          stream.on("abort", onclose);
        }
        if (stream.req) {
          onrequest();
        } else {
          stream.on("request", onrequest);
        }
      } else if (writable && !wState) {
        stream.on("end", onlegacyfinish);
        stream.on("close", onlegacyfinish);
      }
      if (!willEmitClose && typeof stream.aborted === "boolean") {
        stream.on("aborted", onclose);
      }
      stream.on("end", onend);
      stream.on("finish", onfinish);
      if (options.error !== false) {
        stream.on("error", onerror);
      }
      stream.on("close", onclose);
      if (closed) {
        process2.nextTick(onclose);
      } else if (wState !== null && wState !== void 0 && wState.errorEmitted || rState !== null && rState !== void 0 && rState.errorEmitted) {
        if (!willEmitClose) {
          process2.nextTick(onclosed);
        }
      } else if (!readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false)) {
        process2.nextTick(onclosed);
      } else if (!writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false)) {
        process2.nextTick(onclosed);
      } else if (rState && stream.req && stream.aborted) {
        process2.nextTick(onclosed);
      }
      const cleanup = () => {
        callback = nop;
        stream.removeListener("aborted", onclose);
        stream.removeListener("complete", onfinish);
        stream.removeListener("abort", onclose);
        stream.removeListener("request", onrequest);
        if (stream.req)
          stream.req.removeListener("finish", onfinish);
        stream.removeListener("end", onlegacyfinish);
        stream.removeListener("close", onlegacyfinish);
        stream.removeListener("finish", onfinish);
        stream.removeListener("end", onend);
        stream.removeListener("error", onerror);
        stream.removeListener("close", onclose);
      };
      if (options.signal && !closed) {
        const abort = () => {
          const endCallback = callback;
          cleanup();
          endCallback.call(
            stream,
            new AbortError(void 0, {
              cause: options.signal.reason
            })
          );
        };
        if (options.signal.aborted) {
          process2.nextTick(abort);
        } else {
          addAbortListener = addAbortListener || require_util3().addAbortListener;
          const disposable = addAbortListener(options.signal, abort);
          const originalCallback = callback;
          callback = once((...args) => {
            disposable[SymbolDispose]();
            originalCallback.apply(stream, args);
          });
        }
      }
      return cleanup;
    }
    function eosWeb(stream, options, callback) {
      let isAborted2 = false;
      let abort = nop;
      if (options.signal) {
        abort = () => {
          isAborted2 = true;
          callback.call(
            stream,
            new AbortError(void 0, {
              cause: options.signal.reason
            })
          );
        };
        if (options.signal.aborted) {
          process2.nextTick(abort);
        } else {
          addAbortListener = addAbortListener || require_util3().addAbortListener;
          const disposable = addAbortListener(options.signal, abort);
          const originalCallback = callback;
          callback = once((...args) => {
            disposable[SymbolDispose]();
            originalCallback.apply(stream, args);
          });
        }
      }
      const resolverFn = (...args) => {
        if (!isAborted2) {
          process2.nextTick(() => callback.apply(stream, args));
        }
      };
      PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn);
      return nop;
    }
    function finished(stream, opts) {
      var _opts;
      let autoCleanup = false;
      if (opts === null) {
        opts = kEmptyObject;
      }
      if ((_opts = opts) !== null && _opts !== void 0 && _opts.cleanup) {
        validateBoolean(opts.cleanup, "cleanup");
        autoCleanup = opts.cleanup;
      }
      return new Promise2((resolve, reject) => {
        const cleanup = eos2(stream, opts, (err) => {
          if (autoCleanup) {
            cleanup();
          }
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
    module2.exports = eos2;
    module2.exports.finished = finished;
  }
});

// node_modules/readable-stream/lib/internal/streams/destroy.js
var require_destroy = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports, module2) {
    "use strict";
    var process2 = require_browser2();
    var {
      aggregateTwoErrors,
      codes: { ERR_MULTIPLE_CALLBACK },
      AbortError
    } = require_errors3();
    var { Symbol: Symbol2 } = require_primordials();
    var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils();
    var kDestroy = Symbol2("kDestroy");
    var kConstruct = Symbol2("kConstruct");
    function checkError(err, w2, r4) {
      if (err) {
        err.stack;
        if (w2 && !w2.errored) {
          w2.errored = err;
        }
        if (r4 && !r4.errored) {
          r4.errored = err;
        }
      }
    }
    function destroy(err, cb) {
      const r4 = this._readableState;
      const w2 = this._writableState;
      const s4 = w2 || r4;
      if (w2 !== null && w2 !== void 0 && w2.destroyed || r4 !== null && r4 !== void 0 && r4.destroyed) {
        if (typeof cb === "function") {
          cb();
        }
        return this;
      }
      checkError(err, w2, r4);
      if (w2) {
        w2.destroyed = true;
      }
      if (r4) {
        r4.destroyed = true;
      }
      if (!s4.constructed) {
        this.once(kDestroy, function(er) {
          _destroy(this, aggregateTwoErrors(er, err), cb);
        });
      } else {
        _destroy(this, err, cb);
      }
      return this;
    }
    function _destroy(self2, err, cb) {
      let called = false;
      function onDestroy(err2) {
        if (called) {
          return;
        }
        called = true;
        const r4 = self2._readableState;
        const w2 = self2._writableState;
        checkError(err2, w2, r4);
        if (w2) {
          w2.closed = true;
        }
        if (r4) {
          r4.closed = true;
        }
        if (typeof cb === "function") {
          cb(err2);
        }
        if (err2) {
          process2.nextTick(emitErrorCloseNT, self2, err2);
        } else {
          process2.nextTick(emitCloseNT, self2);
        }
      }
      try {
        self2._destroy(err || null, onDestroy);
      } catch (err2) {
        onDestroy(err2);
      }
    }
    function emitErrorCloseNT(self2, err) {
      emitErrorNT(self2, err);
      emitCloseNT(self2);
    }
    function emitCloseNT(self2) {
      const r4 = self2._readableState;
      const w2 = self2._writableState;
      if (w2) {
        w2.closeEmitted = true;
      }
      if (r4) {
        r4.closeEmitted = true;
      }
      if (w2 !== null && w2 !== void 0 && w2.emitClose || r4 !== null && r4 !== void 0 && r4.emitClose) {
        self2.emit("close");
      }
    }
    function emitErrorNT(self2, err) {
      const r4 = self2._readableState;
      const w2 = self2._writableState;
      if (w2 !== null && w2 !== void 0 && w2.errorEmitted || r4 !== null && r4 !== void 0 && r4.errorEmitted) {
        return;
      }
      if (w2) {
        w2.errorEmitted = true;
      }
      if (r4) {
        r4.errorEmitted = true;
      }
      self2.emit("error", err);
    }
    function undestroy() {
      const r4 = this._readableState;
      const w2 = this._writableState;
      if (r4) {
        r4.constructed = true;
        r4.closed = false;
        r4.closeEmitted = false;
        r4.destroyed = false;
        r4.errored = null;
        r4.errorEmitted = false;
        r4.reading = false;
        r4.ended = r4.readable === false;
        r4.endEmitted = r4.readable === false;
      }
      if (w2) {
        w2.constructed = true;
        w2.destroyed = false;
        w2.closed = false;
        w2.closeEmitted = false;
        w2.errored = null;
        w2.errorEmitted = false;
        w2.finalCalled = false;
        w2.prefinished = false;
        w2.ended = w2.writable === false;
        w2.ending = w2.writable === false;
        w2.finished = w2.writable === false;
      }
    }
    function errorOrDestroy(stream, err, sync) {
      const r4 = stream._readableState;
      const w2 = stream._writableState;
      if (w2 !== null && w2 !== void 0 && w2.destroyed || r4 !== null && r4 !== void 0 && r4.destroyed) {
        return this;
      }
      if (r4 !== null && r4 !== void 0 && r4.autoDestroy || w2 !== null && w2 !== void 0 && w2.autoDestroy)
        stream.destroy(err);
      else if (err) {
        err.stack;
        if (w2 && !w2.errored) {
          w2.errored = err;
        }
        if (r4 && !r4.errored) {
          r4.errored = err;
        }
        if (sync) {
          process2.nextTick(emitErrorNT, stream, err);
        } else {
          emitErrorNT(stream, err);
        }
      }
    }
    function construct(stream, cb) {
      if (typeof stream._construct !== "function") {
        return;
      }
      const r4 = stream._readableState;
      const w2 = stream._writableState;
      if (r4) {
        r4.constructed = false;
      }
      if (w2) {
        w2.constructed = false;
      }
      stream.once(kConstruct, cb);
      if (stream.listenerCount(kConstruct) > 1) {
        return;
      }
      process2.nextTick(constructNT, stream);
    }
    function constructNT(stream) {
      let called = false;
      function onConstruct(err) {
        if (called) {
          errorOrDestroy(stream, err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK());
          return;
        }
        called = true;
        const r4 = stream._readableState;
        const w2 = stream._writableState;
        const s4 = w2 || r4;
        if (r4) {
          r4.constructed = true;
        }
        if (w2) {
          w2.constructed = true;
        }
        if (s4.destroyed) {
          stream.emit(kDestroy, err);
        } else if (err) {
          errorOrDestroy(stream, err, true);
        } else {
          process2.nextTick(emitConstructNT, stream);
        }
      }
      try {
        stream._construct((err) => {
          process2.nextTick(onConstruct, err);
        });
      } catch (err) {
        process2.nextTick(onConstruct, err);
      }
    }
    function emitConstructNT(stream) {
      stream.emit(kConstruct);
    }
    function isRequest(stream) {
      return (stream === null || stream === void 0 ? void 0 : stream.setHeader) && typeof stream.abort === "function";
    }
    function emitCloseLegacy(stream) {
      stream.emit("close");
    }
    function emitErrorCloseLegacy(stream, err) {
      stream.emit("error", err);
      process2.nextTick(emitCloseLegacy, stream);
    }
    function destroyer(stream, err) {
      if (!stream || isDestroyed(stream)) {
        return;
      }
      if (!err && !isFinished(stream)) {
        err = new AbortError();
      }
      if (isServerRequest(stream)) {
        stream.socket = null;
        stream.destroy(err);
      } else if (isRequest(stream)) {
        stream.abort();
      } else if (isRequest(stream.req)) {
        stream.req.abort();
      } else if (typeof stream.destroy === "function") {
        stream.destroy(err);
      } else if (typeof stream.close === "function") {
        stream.close();
      } else if (err) {
        process2.nextTick(emitErrorCloseLegacy, stream, err);
      } else {
        process2.nextTick(emitCloseLegacy, stream);
      }
      if (!stream.destroyed) {
        stream[kIsDestroyed] = true;
      }
    }
    module2.exports = {
      construct,
      destroyer,
      destroy,
      undestroy,
      errorOrDestroy
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/legacy.js
var require_legacy = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/legacy.js"(exports, module2) {
    "use strict";
    var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials();
    var { EventEmitter: EE } = require_events();
    function Stream4(opts) {
      EE.call(this, opts);
    }
    ObjectSetPrototypeOf(Stream4.prototype, EE.prototype);
    ObjectSetPrototypeOf(Stream4, EE);
    Stream4.prototype.pipe = function(dest, options) {
      const source = this;
      function ondata(chunk) {
        if (dest.writable && dest.write(chunk) === false && source.pause) {
          source.pause();
        }
      }
      source.on("data", ondata);
      function ondrain() {
        if (source.readable && source.resume) {
          source.resume();
        }
      }
      dest.on("drain", ondrain);
      if (!dest._isStdio && (!options || options.end !== false)) {
        source.on("end", onend);
        source.on("close", onclose);
      }
      let didOnEnd = false;
      function onend() {
        if (didOnEnd)
          return;
        didOnEnd = true;
        dest.end();
      }
      function onclose() {
        if (didOnEnd)
          return;
        didOnEnd = true;
        if (typeof dest.destroy === "function")
          dest.destroy();
      }
      function onerror(er) {
        cleanup();
        if (EE.listenerCount(this, "error") === 0) {
          this.emit("error", er);
        }
      }
      prependListener(source, "error", onerror);
      prependListener(dest, "error", onerror);
      function cleanup() {
        source.removeListener("data", ondata);
        dest.removeListener("drain", ondrain);
        source.removeListener("end", onend);
        source.removeListener("close", onclose);
        source.removeListener("error", onerror);
        dest.removeListener("error", onerror);
        source.removeListener("end", cleanup);
        source.removeListener("close", cleanup);
        dest.removeListener("close", cleanup);
      }
      source.on("end", cleanup);
      source.on("close", cleanup);
      dest.on("close", cleanup);
      dest.emit("pipe", source);
      return dest;
    };
    function prependListener(emitter, event, fn) {
      if (typeof emitter.prependListener === "function")
        return emitter.prependListener(event, fn);
      if (!emitter._events || !emitter._events[event])
        emitter.on(event, fn);
      else if (ArrayIsArray(emitter._events[event]))
        emitter._events[event].unshift(fn);
      else
        emitter._events[event] = [fn, emitter._events[event]];
    }
    module2.exports = {
      Stream: Stream4,
      prependListener
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/add-abort-signal.js
var require_add_abort_signal = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(exports, module2) {
    "use strict";
    var { SymbolDispose } = require_primordials();
    var { AbortError, codes } = require_errors3();
    var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils();
    var eos2 = require_end_of_stream();
    var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2 } = codes;
    var addAbortListener;
    var validateAbortSignal = (signal, name) => {
      if (typeof signal !== "object" || !("aborted" in signal)) {
        throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal);
      }
    };
    module2.exports.addAbortSignal = function addAbortSignal(signal, stream) {
      validateAbortSignal(signal, "signal");
      if (!isNodeStream(stream) && !isWebStream(stream)) {
        throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
      }
      return module2.exports.addAbortSignalNoValidate(signal, stream);
    };
    module2.exports.addAbortSignalNoValidate = function(signal, stream) {
      if (typeof signal !== "object" || !("aborted" in signal)) {
        return stream;
      }
      const onAbort = isNodeStream(stream) ? () => {
        stream.destroy(
          new AbortError(void 0, {
            cause: signal.reason
          })
        );
      } : () => {
        stream[kControllerErrorFunction](
          new AbortError(void 0, {
            cause: signal.reason
          })
        );
      };
      if (signal.aborted) {
        onAbort();
      } else {
        addAbortListener = addAbortListener || require_util3().addAbortListener;
        const disposable = addAbortListener(signal, onAbort);
        eos2(stream, disposable[SymbolDispose]);
      }
      return stream;
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/buffer_list.js
var require_buffer_list = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports, module2) {
    "use strict";
    var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials();
    var { Buffer: Buffer2 } = require_buffer();
    var { inspect } = require_util3();
    module2.exports = class BufferList {
      constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
      }
      push(v5) {
        const entry = {
          data: v5,
          next: null
        };
        if (this.length > 0)
          this.tail.next = entry;
        else
          this.head = entry;
        this.tail = entry;
        ++this.length;
      }
      unshift(v5) {
        const entry = {
          data: v5,
          next: this.head
        };
        if (this.length === 0)
          this.tail = entry;
        this.head = entry;
        ++this.length;
      }
      shift() {
        if (this.length === 0)
          return;
        const ret = this.head.data;
        if (this.length === 1)
          this.head = this.tail = null;
        else
          this.head = this.head.next;
        --this.length;
        return ret;
      }
      clear() {
        this.head = this.tail = null;
        this.length = 0;
      }
      join(s4) {
        if (this.length === 0)
          return "";
        let p3 = this.head;
        let ret = "" + p3.data;
        while ((p3 = p3.next) !== null)
          ret += s4 + p3.data;
        return ret;
      }
      concat(n4) {
        if (this.length === 0)
          return Buffer2.alloc(0);
        const ret = Buffer2.allocUnsafe(n4 >>> 0);
        let p3 = this.head;
        let i3 = 0;
        while (p3) {
          TypedArrayPrototypeSet(ret, p3.data, i3);
          i3 += p3.data.length;
          p3 = p3.next;
        }
        return ret;
      }
      // Consumes a specified amount of bytes or characters from the buffered data.
      consume(n4, hasStrings) {
        const data = this.head.data;
        if (n4 < data.length) {
          const slice = data.slice(0, n4);
          this.head.data = data.slice(n4);
          return slice;
        }
        if (n4 === data.length) {
          return this.shift();
        }
        return hasStrings ? this._getString(n4) : this._getBuffer(n4);
      }
      first() {
        return this.head.data;
      }
      *[SymbolIterator]() {
        for (let p3 = this.head; p3; p3 = p3.next) {
          yield p3.data;
        }
      }
      // Consumes a specified amount of characters from the buffered data.
      _getString(n4) {
        let ret = "";
        let p3 = this.head;
        let c4 = 0;
        do {
          const str2 = p3.data;
          if (n4 > str2.length) {
            ret += str2;
            n4 -= str2.length;
          } else {
            if (n4 === str2.length) {
              ret += str2;
              ++c4;
              if (p3.next)
                this.head = p3.next;
              else
                this.head = this.tail = null;
            } else {
              ret += StringPrototypeSlice(str2, 0, n4);
              this.head = p3;
              p3.data = StringPrototypeSlice(str2, n4);
            }
            break;
          }
          ++c4;
        } while ((p3 = p3.next) !== null);
        this.length -= c4;
        return ret;
      }
      // Consumes a specified amount of bytes from the buffered data.
      _getBuffer(n4) {
        const ret = Buffer2.allocUnsafe(n4);
        const retLen = n4;
        let p3 = this.head;
        let c4 = 0;
        do {
          const buf = p3.data;
          if (n4 > buf.length) {
            TypedArrayPrototypeSet(ret, buf, retLen - n4);
            n4 -= buf.length;
          } else {
            if (n4 === buf.length) {
              TypedArrayPrototypeSet(ret, buf, retLen - n4);
              ++c4;
              if (p3.next)
                this.head = p3.next;
              else
                this.head = this.tail = null;
            } else {
              TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n4), retLen - n4);
              this.head = p3;
              p3.data = buf.slice(n4);
            }
            break;
          }
          ++c4;
        } while ((p3 = p3.next) !== null);
        this.length -= c4;
        return ret;
      }
      // Make sure the linked list only shows the minimal necessary information.
      [Symbol.for("nodejs.util.inspect.custom")](_2, options) {
        return inspect(this, {
          ...options,
          // Only inspect one level.
          depth: 0,
          // It should not recurse.
          customInspect: false
        });
      }
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/state.js
var require_state = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/state.js"(exports, module2) {
    "use strict";
    var { MathFloor, NumberIsInteger } = require_primordials();
    var { validateInteger } = require_validators();
    var { ERR_INVALID_ARG_VALUE } = require_errors3().codes;
    var defaultHighWaterMarkBytes = 16 * 1024;
    var defaultHighWaterMarkObjectMode = 16;
    function highWaterMarkFrom(options, isDuplex, duplexKey) {
      return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
    }
    function getDefaultHighWaterMark(objectMode) {
      return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes;
    }
    function setDefaultHighWaterMark(objectMode, value) {
      validateInteger(value, "value", 0);
      if (objectMode) {
        defaultHighWaterMarkObjectMode = value;
      } else {
        defaultHighWaterMarkBytes = value;
      }
    }
    function getHighWaterMark(state, options, duplexKey, isDuplex) {
      const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
      if (hwm != null) {
        if (!NumberIsInteger(hwm) || hwm < 0) {
          const name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark";
          throw new ERR_INVALID_ARG_VALUE(name, hwm);
        }
        return MathFloor(hwm);
      }
      return getDefaultHighWaterMark(state.objectMode);
    }
    module2.exports = {
      getHighWaterMark,
      getDefaultHighWaterMark,
      setDefaultHighWaterMark
    };
  }
});

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

// node_modules/string_decoder/lib/string_decoder.js
var require_string_decoder = __commonJS({
  "node_modules/string_decoder/lib/string_decoder.js"(exports) {
    "use strict";
    var Buffer2 = require_safe_buffer().Buffer;
    var isEncoding = Buffer2.isEncoding || function(encoding) {
      encoding = "" + encoding;
      switch (encoding && encoding.toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
        case "raw":
          return true;
        default:
          return false;
      }
    };
    function _normalizeEncoding(enc) {
      if (!enc)
        return "utf8";
      var retried;
      while (true) {
        switch (enc) {
          case "utf8":
          case "utf-8":
            return "utf8";
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return "utf16le";
          case "latin1":
          case "binary":
            return "latin1";
          case "base64":
          case "ascii":
          case "hex":
            return enc;
          default:
            if (retried)
              return;
            enc = ("" + enc).toLowerCase();
            retried = true;
        }
      }
    }
    function normalizeEncoding(enc) {
      var nenc = _normalizeEncoding(enc);
      if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc)))
        throw new Error("Unknown encoding: " + enc);
      return nenc || enc;
    }
    exports.StringDecoder = StringDecoder;
    function StringDecoder(encoding) {
      this.encoding = normalizeEncoding(encoding);
      var nb;
      switch (this.encoding) {
        case "utf16le":
          this.text = utf16Text;
          this.end = utf16End;
          nb = 4;
          break;
        case "utf8":
          this.fillLast = utf8FillLast;
          nb = 4;
          break;
        case "base64":
          this.text = base64Text;
          this.end = base64End;
          nb = 3;
          break;
        default:
          this.write = simpleWrite;
          this.end = simpleEnd;
          return;
      }
      this.lastNeed = 0;
      this.lastTotal = 0;
      this.lastChar = Buffer2.allocUnsafe(nb);
    }
    StringDecoder.prototype.write = function(buf) {
      if (buf.length === 0)
        return "";
      var r4;
      var i3;
      if (this.lastNeed) {
        r4 = this.fillLast(buf);
        if (r4 === void 0)
          return "";
        i3 = this.lastNeed;
        this.lastNeed = 0;
      } else {
        i3 = 0;
      }
      if (i3 < buf.length)
        return r4 ? r4 + this.text(buf, i3) : this.text(buf, i3);
      return r4 || "";
    };
    StringDecoder.prototype.end = utf8End;
    StringDecoder.prototype.text = utf8Text;
    StringDecoder.prototype.fillLast = function(buf) {
      if (this.lastNeed <= buf.length) {
        buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
        return this.lastChar.toString(this.encoding, 0, this.lastTotal);
      }
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
      this.lastNeed -= buf.length;
    };
    function utf8CheckByte(byte) {
      if (byte <= 127)
        return 0;
      else if (byte >> 5 === 6)
        return 2;
      else if (byte >> 4 === 14)
        return 3;
      else if (byte >> 3 === 30)
        return 4;
      return byte >> 6 === 2 ? -1 : -2;
    }
    function utf8CheckIncomplete(self2, buf, i3) {
      var j3 = buf.length - 1;
      if (j3 < i3)
        return 0;
      var nb = utf8CheckByte(buf[j3]);
      if (nb >= 0) {
        if (nb > 0)
          self2.lastNeed = nb - 1;
        return nb;
      }
      if (--j3 < i3 || nb === -2)
        return 0;
      nb = utf8CheckByte(buf[j3]);
      if (nb >= 0) {
        if (nb > 0)
          self2.lastNeed = nb - 2;
        return nb;
      }
      if (--j3 < i3 || nb === -2)
        return 0;
      nb = utf8CheckByte(buf[j3]);
      if (nb >= 0) {
        if (nb > 0) {
          if (nb === 2)
            nb = 0;
          else
            self2.lastNeed = nb - 3;
        }
        return nb;
      }
      return 0;
    }
    function utf8CheckExtraBytes(self2, buf, p3) {
      if ((buf[0] & 192) !== 128) {
        self2.lastNeed = 0;
        return "\uFFFD";
      }
      if (self2.lastNeed > 1 && buf.length > 1) {
        if ((buf[1] & 192) !== 128) {
          self2.lastNeed = 1;
          return "\uFFFD";
        }
        if (self2.lastNeed > 2 && buf.length > 2) {
          if ((buf[2] & 192) !== 128) {
            self2.lastNeed = 2;
            return "\uFFFD";
          }
        }
      }
    }
    function utf8FillLast(buf) {
      var p3 = this.lastTotal - this.lastNeed;
      var r4 = utf8CheckExtraBytes(this, buf, p3);
      if (r4 !== void 0)
        return r4;
      if (this.lastNeed <= buf.length) {
        buf.copy(this.lastChar, p3, 0, this.lastNeed);
        return this.lastChar.toString(this.encoding, 0, this.lastTotal);
      }
      buf.copy(this.lastChar, p3, 0, buf.length);
      this.lastNeed -= buf.length;
    }
    function utf8Text(buf, i3) {
      var total = utf8CheckIncomplete(this, buf, i3);
      if (!this.lastNeed)
        return buf.toString("utf8", i3);
      this.lastTotal = total;
      var end = buf.length - (total - this.lastNeed);
      buf.copy(this.lastChar, 0, end);
      return buf.toString("utf8", i3, end);
    }
    function utf8End(buf) {
      var r4 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed)
        return r4 + "\uFFFD";
      return r4;
    }
    function utf16Text(buf, i3) {
      if ((buf.length - i3) % 2 === 0) {
        var r4 = buf.toString("utf16le", i3);
        if (r4) {
          var c4 = r4.charCodeAt(r4.length - 1);
          if (c4 >= 55296 && c4 <= 56319) {
            this.lastNeed = 2;
            this.lastTotal = 4;
            this.lastChar[0] = buf[buf.length - 2];
            this.lastChar[1] = buf[buf.length - 1];
            return r4.slice(0, -1);
          }
        }
        return r4;
      }
      this.lastNeed = 1;
      this.lastTotal = 2;
      this.lastChar[0] = buf[buf.length - 1];
      return buf.toString("utf16le", i3, buf.length - 1);
    }
    function utf16End(buf) {
      var r4 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed) {
        var end = this.lastTotal - this.lastNeed;
        return r4 + this.lastChar.toString("utf16le", 0, end);
      }
      return r4;
    }
    function base64Text(buf, i3) {
      var n4 = (buf.length - i3) % 3;
      if (n4 === 0)
        return buf.toString("base64", i3);
      this.lastNeed = 3 - n4;
      this.lastTotal = 3;
      if (n4 === 1) {
        this.lastChar[0] = buf[buf.length - 1];
      } else {
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
      }
      return buf.toString("base64", i3, buf.length - n4);
    }
    function base64End(buf) {
      var r4 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed)
        return r4 + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
      return r4;
    }
    function simpleWrite(buf) {
      return buf.toString(this.encoding);
    }
    function simpleEnd(buf) {
      return buf && buf.length ? this.write(buf) : "";
    }
  }
});

// node_modules/readable-stream/lib/internal/streams/from.js
var require_from = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/from.js"(exports, module2) {
    "use strict";
    var process2 = require_browser2();
    var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials();
    var { Buffer: Buffer2 } = require_buffer();
    var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_NULL_VALUES } = require_errors3().codes;
    function from(Readable, iterable, opts) {
      let iterator;
      if (typeof iterable === "string" || iterable instanceof Buffer2) {
        return new Readable({
          objectMode: true,
          ...opts,
          read() {
            this.push(iterable);
            this.push(null);
          }
        });
      }
      let isAsync2;
      if (iterable && iterable[SymbolAsyncIterator]) {
        isAsync2 = true;
        iterator = iterable[SymbolAsyncIterator]();
      } else if (iterable && iterable[SymbolIterator]) {
        isAsync2 = false;
        iterator = iterable[SymbolIterator]();
      } else {
        throw new ERR_INVALID_ARG_TYPE2("iterable", ["Iterable"], iterable);
      }
      const readable = new Readable({
        objectMode: true,
        highWaterMark: 1,
        // TODO(ronag): What options should be allowed?
        ...opts
      });
      let reading = false;
      readable._read = function() {
        if (!reading) {
          reading = true;
          next();
        }
      };
      readable._destroy = function(error, cb) {
        PromisePrototypeThen(
          close(error),
          () => process2.nextTick(cb, error),
          // nextTick is here in case cb throws
          (e3) => process2.nextTick(cb, e3 || error)
        );
      };
      async function close(error) {
        const hadError = error !== void 0 && error !== null;
        const hasThrow = typeof iterator.throw === "function";
        if (hadError && hasThrow) {
          const { value, done } = await iterator.throw(error);
          await value;
          if (done) {
            return;
          }
        }
        if (typeof iterator.return === "function") {
          const { value } = await iterator.return();
          await value;
        }
      }
      async function next() {
        for (; ; ) {
          try {
            const { value, done } = isAsync2 ? await iterator.next() : iterator.next();
            if (done) {
              readable.push(null);
            } else {
              const res = value && typeof value.then === "function" ? await value : value;
              if (res === null) {
                reading = false;
                throw new ERR_STREAM_NULL_VALUES();
              } else if (readable.push(res)) {
                continue;
              } else {
                reading = false;
              }
            }
          } catch (err) {
            readable.destroy(err);
          }
          break;
        }
      }
      return readable;
    }
    module2.exports = from;
  }
});

// node_modules/readable-stream/lib/internal/streams/readable.js
var require_readable = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/readable.js"(exports, module2) {
    var process2 = require_browser2();
    var {
      ArrayPrototypeIndexOf,
      NumberIsInteger,
      NumberIsNaN,
      NumberParseInt,
      ObjectDefineProperties,
      ObjectKeys,
      ObjectSetPrototypeOf,
      Promise: Promise2,
      SafeSet,
      SymbolAsyncDispose,
      SymbolAsyncIterator,
      Symbol: Symbol2
    } = require_primordials();
    module2.exports = Readable;
    Readable.ReadableState = ReadableState;
    var { EventEmitter: EE } = require_events();
    var { Stream: Stream4, prependListener } = require_legacy();
    var { Buffer: Buffer2 } = require_buffer();
    var { addAbortSignal } = require_add_abort_signal();
    var eos2 = require_end_of_stream();
    var debug4 = require_util3().debuglog("stream", (fn) => {
      debug4 = fn;
    });
    var BufferList = require_buffer_list();
    var destroyImpl = require_destroy();
    var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
    var {
      aggregateTwoErrors,
      codes: {
        ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
        ERR_METHOD_NOT_IMPLEMENTED,
        ERR_OUT_OF_RANGE,
        ERR_STREAM_PUSH_AFTER_EOF,
        ERR_STREAM_UNSHIFT_AFTER_END_EVENT
      },
      AbortError
    } = require_errors3();
    var { validateObject } = require_validators();
    var kPaused = Symbol2("kPaused");
    var { StringDecoder } = require_string_decoder();
    var from = require_from();
    ObjectSetPrototypeOf(Readable.prototype, Stream4.prototype);
    ObjectSetPrototypeOf(Readable, Stream4);
    var nop = () => {
    };
    var { errorOrDestroy } = destroyImpl;
    var kObjectMode = 1 << 0;
    var kEnded = 1 << 1;
    var kEndEmitted = 1 << 2;
    var kReading = 1 << 3;
    var kConstructed = 1 << 4;
    var kSync = 1 << 5;
    var kNeedReadable = 1 << 6;
    var kEmittedReadable = 1 << 7;
    var kReadableListening = 1 << 8;
    var kResumeScheduled = 1 << 9;
    var kErrorEmitted = 1 << 10;
    var kEmitClose = 1 << 11;
    var kAutoDestroy = 1 << 12;
    var kDestroyed = 1 << 13;
    var kClosed = 1 << 14;
    var kCloseEmitted = 1 << 15;
    var kMultiAwaitDrain = 1 << 16;
    var kReadingMore = 1 << 17;
    var kDataEmitted = 1 << 18;
    function makeBitMapDescriptor(bit) {
      return {
        enumerable: false,
        get() {
          return (this.state & bit) !== 0;
        },
        set(value) {
          if (value)
            this.state |= bit;
          else
            this.state &= ~bit;
        }
      };
    }
    ObjectDefineProperties(ReadableState.prototype, {
      objectMode: makeBitMapDescriptor(kObjectMode),
      ended: makeBitMapDescriptor(kEnded),
      endEmitted: makeBitMapDescriptor(kEndEmitted),
      reading: makeBitMapDescriptor(kReading),
      // Stream is still being constructed and cannot be
      // destroyed until construction finished or failed.
      // Async construction is opt in, therefore we start as
      // constructed.
      constructed: makeBitMapDescriptor(kConstructed),
      // A flag to be able to tell if the event 'readable'/'data' is emitted
      // immediately, or on a later tick.  We set this to true at first, because
      // any actions that shouldn't happen until "later" should generally also
      // not happen before the first read call.
      sync: makeBitMapDescriptor(kSync),
      // Whenever we return null, then we set a flag to say
      // that we're awaiting a 'readable' event emission.
      needReadable: makeBitMapDescriptor(kNeedReadable),
      emittedReadable: makeBitMapDescriptor(kEmittedReadable),
      readableListening: makeBitMapDescriptor(kReadableListening),
      resumeScheduled: makeBitMapDescriptor(kResumeScheduled),
      // True if the error was already emitted and should not be thrown again.
      errorEmitted: makeBitMapDescriptor(kErrorEmitted),
      emitClose: makeBitMapDescriptor(kEmitClose),
      autoDestroy: makeBitMapDescriptor(kAutoDestroy),
      // Has it been destroyed.
      destroyed: makeBitMapDescriptor(kDestroyed),
      // Indicates whether the stream has finished destroying.
      closed: makeBitMapDescriptor(kClosed),
      // True if close has been emitted or would have been emitted
      // depending on emitClose.
      closeEmitted: makeBitMapDescriptor(kCloseEmitted),
      multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),
      // If true, a maybeReadMore has been scheduled.
      readingMore: makeBitMapDescriptor(kReadingMore),
      dataEmitted: makeBitMapDescriptor(kDataEmitted)
    });
    function ReadableState(options, stream, isDuplex) {
      if (typeof isDuplex !== "boolean")
        isDuplex = stream instanceof require_duplex();
      this.state = kEmitClose | kAutoDestroy | kConstructed | kSync;
      if (options && options.objectMode)
        this.state |= kObjectMode;
      if (isDuplex && options && options.readableObjectMode)
        this.state |= kObjectMode;
      this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false);
      this.buffer = new BufferList();
      this.length = 0;
      this.pipes = [];
      this.flowing = null;
      this[kPaused] = null;
      if (options && options.emitClose === false)
        this.state &= ~kEmitClose;
      if (options && options.autoDestroy === false)
        this.state &= ~kAutoDestroy;
      this.errored = null;
      this.defaultEncoding = options && options.defaultEncoding || "utf8";
      this.awaitDrainWriters = null;
      this.decoder = null;
      this.encoding = null;
      if (options && options.encoding) {
        this.decoder = new StringDecoder(options.encoding);
        this.encoding = options.encoding;
      }
    }
    function Readable(options) {
      if (!(this instanceof Readable))
        return new Readable(options);
      const isDuplex = this instanceof require_duplex();
      this._readableState = new ReadableState(options, this, isDuplex);
      if (options) {
        if (typeof options.read === "function")
          this._read = options.read;
        if (typeof options.destroy === "function")
          this._destroy = options.destroy;
        if (typeof options.construct === "function")
          this._construct = options.construct;
        if (options.signal && !isDuplex)
          addAbortSignal(options.signal, this);
      }
      Stream4.call(this, options);
      destroyImpl.construct(this, () => {
        if (this._readableState.needReadable) {
          maybeReadMore(this, this._readableState);
        }
      });
    }
    Readable.prototype.destroy = destroyImpl.destroy;
    Readable.prototype._undestroy = destroyImpl.undestroy;
    Readable.prototype._destroy = function(err, cb) {
      cb(err);
    };
    Readable.prototype[EE.captureRejectionSymbol] = function(err) {
      this.destroy(err);
    };
    Readable.prototype[SymbolAsyncDispose] = function() {
      let error;
      if (!this.destroyed) {
        error = this.readableEnded ? null : new AbortError();
        this.destroy(error);
      }
      return new Promise2((resolve, reject) => eos2(this, (err) => err && err !== error ? reject(err) : resolve(null)));
    };
    Readable.prototype.push = function(chunk, encoding) {
      return readableAddChunk(this, chunk, encoding, false);
    };
    Readable.prototype.unshift = function(chunk, encoding) {
      return readableAddChunk(this, chunk, encoding, true);
    };
    function readableAddChunk(stream, chunk, encoding, addToFront) {
      debug4("readableAddChunk", chunk);
      const state = stream._readableState;
      let err;
      if ((state.state & kObjectMode) === 0) {
        if (typeof chunk === "string") {
          encoding = encoding || state.defaultEncoding;
          if (state.encoding !== encoding) {
            if (addToFront && state.encoding) {
              chunk = Buffer2.from(chunk, encoding).toString(state.encoding);
            } else {
              chunk = Buffer2.from(chunk, encoding);
              encoding = "";
            }
          }
        } else if (chunk instanceof Buffer2) {
          encoding = "";
        } else if (Stream4._isUint8Array(chunk)) {
          chunk = Stream4._uint8ArrayToBuffer(chunk);
          encoding = "";
        } else if (chunk != null) {
          err = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk);
        }
      }
      if (err) {
        errorOrDestroy(stream, err);
      } else if (chunk === null) {
        state.state &= ~kReading;
        onEofChunk(stream, state);
      } else if ((state.state & kObjectMode) !== 0 || chunk && chunk.length > 0) {
        if (addToFront) {
          if ((state.state & kEndEmitted) !== 0)
            errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
          else if (state.destroyed || state.errored)
            return false;
          else
            addChunk(stream, state, chunk, true);
        } else if (state.ended) {
          errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
        } else if (state.destroyed || state.errored) {
          return false;
        } else {
          state.state &= ~kReading;
          if (state.decoder && !encoding) {
            chunk = state.decoder.write(chunk);
            if (state.objectMode || chunk.length !== 0)
              addChunk(stream, state, chunk, false);
            else
              maybeReadMore(stream, state);
          } else {
            addChunk(stream, state, chunk, false);
          }
        }
      } else if (!addToFront) {
        state.state &= ~kReading;
        maybeReadMore(stream, state);
      }
      return !state.ended && (state.length < state.highWaterMark || state.length === 0);
    }
    function addChunk(stream, state, chunk, addToFront) {
      if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) {
        if ((state.state & kMultiAwaitDrain) !== 0) {
          state.awaitDrainWriters.clear();
        } else {
          state.awaitDrainWriters = null;
        }
        state.dataEmitted = true;
        stream.emit("data", chunk);
      } else {
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront)
          state.buffer.unshift(chunk);
        else
          state.buffer.push(chunk);
        if ((state.state & kNeedReadable) !== 0)
          emitReadable(stream);
      }
      maybeReadMore(stream, state);
    }
    Readable.prototype.isPaused = function() {
      const state = this._readableState;
      return state[kPaused] === true || state.flowing === false;
    };
    Readable.prototype.setEncoding = function(enc) {
      const decoder = new StringDecoder(enc);
      this._readableState.decoder = decoder;
      this._readableState.encoding = this._readableState.decoder.encoding;
      const buffer = this._readableState.buffer;
      let content = "";
      for (const data of buffer) {
        content += decoder.write(data);
      }
      buffer.clear();
      if (content !== "")
        buffer.push(content);
      this._readableState.length = content.length;
      return this;
    };
    var MAX_HWM = 1073741824;
    function computeNewHighWaterMark(n4) {
      if (n4 > MAX_HWM) {
        throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n4);
      } else {
        n4--;
        n4 |= n4 >>> 1;
        n4 |= n4 >>> 2;
        n4 |= n4 >>> 4;
        n4 |= n4 >>> 8;
        n4 |= n4 >>> 16;
        n4++;
      }
      return n4;
    }
    function howMuchToRead(n4, state) {
      if (n4 <= 0 || state.length === 0 && state.ended)
        return 0;
      if ((state.state & kObjectMode) !== 0)
        return 1;
      if (NumberIsNaN(n4)) {
        if (state.flowing && state.length)
          return state.buffer.first().length;
        return state.length;
      }
      if (n4 <= state.length)
        return n4;
      return state.ended ? state.length : 0;
    }
    Readable.prototype.read = function(n4) {
      debug4("read", n4);
      if (n4 === void 0) {
        n4 = NaN;
      } else if (!NumberIsInteger(n4)) {
        n4 = NumberParseInt(n4, 10);
      }
      const state = this._readableState;
      const nOrig = n4;
      if (n4 > state.highWaterMark)
        state.highWaterMark = computeNewHighWaterMark(n4);
      if (n4 !== 0)
        state.state &= ~kEmittedReadable;
      if (n4 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
        debug4("read: emitReadable", state.length, state.ended);
        if (state.length === 0 && state.ended)
          endReadable(this);
        else
          emitReadable(this);
        return null;
      }
      n4 = howMuchToRead(n4, state);
      if (n4 === 0 && state.ended) {
        if (state.length === 0)
          endReadable(this);
        return null;
      }
      let doRead = (state.state & kNeedReadable) !== 0;
      debug4("need readable", doRead);
      if (state.length === 0 || state.length - n4 < state.highWaterMark) {
        doRead = true;
        debug4("length less than watermark", doRead);
      }
      if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {
        doRead = false;
        debug4("reading, ended or constructing", doRead);
      } else if (doRead) {
        debug4("do read");
        state.state |= kReading | kSync;
        if (state.length === 0)
          state.state |= kNeedReadable;
        try {
          this._read(state.highWaterMark);
        } catch (err) {
          errorOrDestroy(this, err);
        }
        state.state &= ~kSync;
        if (!state.reading)
          n4 = howMuchToRead(nOrig, state);
      }
      let ret;
      if (n4 > 0)
        ret = fromList2(n4, state);
      else
        ret = null;
      if (ret === null) {
        state.needReadable = state.length <= state.highWaterMark;
        n4 = 0;
      } else {
        state.length -= n4;
        if (state.multiAwaitDrain) {
          state.awaitDrainWriters.clear();
        } else {
          state.awaitDrainWriters = null;
        }
      }
      if (state.length === 0) {
        if (!state.ended)
          state.needReadable = true;
        if (nOrig !== n4 && state.ended)
          endReadable(this);
      }
      if (ret !== null && !state.errorEmitted && !state.closeEmitted) {
        state.dataEmitted = true;
        this.emit("data", ret);
      }
      return ret;
    };
    function onEofChunk(stream, state) {
      debug4("onEofChunk");
      if (state.ended)
        return;
      if (state.decoder) {
        const chunk = state.decoder.end();
        if (chunk && chunk.length) {
          state.buffer.push(chunk);
          state.length += state.objectMode ? 1 : chunk.length;
        }
      }
      state.ended = true;
      if (state.sync) {
        emitReadable(stream);
      } else {
        state.needReadable = false;
        state.emittedReadable = true;
        emitReadable_(stream);
      }
    }
    function emitReadable(stream) {
      const state = stream._readableState;
      debug4("emitReadable", state.needReadable, state.emittedReadable);
      state.needReadable = false;
      if (!state.emittedReadable) {
        debug4("emitReadable", state.flowing);
        state.emittedReadable = true;
        process2.nextTick(emitReadable_, stream);
      }
    }
    function emitReadable_(stream) {
      const state = stream._readableState;
      debug4("emitReadable_", state.destroyed, state.length, state.ended);
      if (!state.destroyed && !state.errored && (state.length || state.ended)) {
        stream.emit("readable");
        state.emittedReadable = false;
      }
      state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
      flow(stream);
    }
    function maybeReadMore(stream, state) {
      if (!state.readingMore && state.constructed) {
        state.readingMore = true;
        process2.nextTick(maybeReadMore_, stream, state);
      }
    }
    function maybeReadMore_(stream, state) {
      while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
        const len = state.length;
        debug4("maybeReadMore read 0");
        stream.read(0);
        if (len === state.length)
          break;
      }
      state.readingMore = false;
    }
    Readable.prototype._read = function(n4) {
      throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");
    };
    Readable.prototype.pipe = function(dest, pipeOpts) {
      const src = this;
      const state = this._readableState;
      if (state.pipes.length === 1) {
        if (!state.multiAwaitDrain) {
          state.multiAwaitDrain = true;
          state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []);
        }
      }
      state.pipes.push(dest);
      debug4("pipe count=%d opts=%j", state.pipes.length, pipeOpts);
      const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process2.stdout && dest !== process2.stderr;
      const endFn = doEnd ? onend : unpipe;
      if (state.endEmitted)
        process2.nextTick(endFn);
      else
        src.once("end", endFn);
      dest.on("unpipe", onunpipe);
      function onunpipe(readable, unpipeInfo) {
        debug4("onunpipe");
        if (readable === src) {
          if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
            unpipeInfo.hasUnpiped = true;
            cleanup();
          }
        }
      }
      function onend() {
        debug4("onend");
        dest.end();
      }
      let ondrain;
      let cleanedUp = false;
      function cleanup() {
        debug4("cleanup");
        dest.removeListener("close", onclose);
        dest.removeListener("finish", onfinish);
        if (ondrain) {
          dest.removeListener("drain", ondrain);
        }
        dest.removeListener("error", onerror);
        dest.removeListener("unpipe", onunpipe);
        src.removeListener("end", onend);
        src.removeListener("end", unpipe);
        src.removeListener("data", ondata);
        cleanedUp = true;
        if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain))
          ondrain();
      }
      function pause() {
        if (!cleanedUp) {
          if (state.pipes.length === 1 && state.pipes[0] === dest) {
            debug4("false write response, pause", 0);
            state.awaitDrainWriters = dest;
            state.multiAwaitDrain = false;
          } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {
            debug4("false write response, pause", state.awaitDrainWriters.size);
            state.awaitDrainWriters.add(dest);
          }
          src.pause();
        }
        if (!ondrain) {
          ondrain = pipeOnDrain(src, dest);
          dest.on("drain", ondrain);
        }
      }
      src.on("data", ondata);
      function ondata(chunk) {
        debug4("ondata");
        const ret = dest.write(chunk);
        debug4("dest.write", ret);
        if (ret === false) {
          pause();
        }
      }
      function onerror(er) {
        debug4("onerror", er);
        unpipe();
        dest.removeListener("error", onerror);
        if (dest.listenerCount("error") === 0) {
          const s4 = dest._writableState || dest._readableState;
          if (s4 && !s4.errorEmitted) {
            errorOrDestroy(dest, er);
          } else {
            dest.emit("error", er);
          }
        }
      }
      prependListener(dest, "error", onerror);
      function onclose() {
        dest.removeListener("finish", onfinish);
        unpipe();
      }
      dest.once("close", onclose);
      function onfinish() {
        debug4("onfinish");
        dest.removeListener("close", onclose);
        unpipe();
      }
      dest.once("finish", onfinish);
      function unpipe() {
        debug4("unpipe");
        src.unpipe(dest);
      }
      dest.emit("pipe", src);
      if (dest.writableNeedDrain === true) {
        pause();
      } else if (!state.flowing) {
        debug4("pipe resume");
        src.resume();
      }
      return dest;
    };
    function pipeOnDrain(src, dest) {
      return function pipeOnDrainFunctionResult() {
        const state = src._readableState;
        if (state.awaitDrainWriters === dest) {
          debug4("pipeOnDrain", 1);
          state.awaitDrainWriters = null;
        } else if (state.multiAwaitDrain) {
          debug4("pipeOnDrain", state.awaitDrainWriters.size);
          state.awaitDrainWriters.delete(dest);
        }
        if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data")) {
          src.resume();
        }
      };
    }
    Readable.prototype.unpipe = function(dest) {
      const state = this._readableState;
      const unpipeInfo = {
        hasUnpiped: false
      };
      if (state.pipes.length === 0)
        return this;
      if (!dest) {
        const dests = state.pipes;
        state.pipes = [];
        this.pause();
        for (let i3 = 0; i3 < dests.length; i3++)
          dests[i3].emit("unpipe", this, {
            hasUnpiped: false
          });
        return this;
      }
      const index2 = ArrayPrototypeIndexOf(state.pipes, dest);
      if (index2 === -1)
        return this;
      state.pipes.splice(index2, 1);
      if (state.pipes.length === 0)
        this.pause();
      dest.emit("unpipe", this, unpipeInfo);
      return this;
    };
    Readable.prototype.on = function(ev, fn) {
      const res = Stream4.prototype.on.call(this, ev, fn);
      const state = this._readableState;
      if (ev === "data") {
        state.readableListening = this.listenerCount("readable") > 0;
        if (state.flowing !== false)
          this.resume();
      } else if (ev === "readable") {
        if (!state.endEmitted && !state.readableListening) {
          state.readableListening = state.needReadable = true;
          state.flowing = false;
          state.emittedReadable = false;
          debug4("on readable", state.length, state.reading);
          if (state.length) {
            emitReadable(this);
          } else if (!state.reading) {
            process2.nextTick(nReadingNextTick, this);
          }
        }
      }
      return res;
    };
    Readable.prototype.addListener = Readable.prototype.on;
    Readable.prototype.removeListener = function(ev, fn) {
      const res = Stream4.prototype.removeListener.call(this, ev, fn);
      if (ev === "readable") {
        process2.nextTick(updateReadableListening, this);
      }
      return res;
    };
    Readable.prototype.off = Readable.prototype.removeListener;
    Readable.prototype.removeAllListeners = function(ev) {
      const res = Stream4.prototype.removeAllListeners.apply(this, arguments);
      if (ev === "readable" || ev === void 0) {
        process2.nextTick(updateReadableListening, this);
      }
      return res;
    };
    function updateReadableListening(self2) {
      const state = self2._readableState;
      state.readableListening = self2.listenerCount("readable") > 0;
      if (state.resumeScheduled && state[kPaused] === false) {
        state.flowing = true;
      } else if (self2.listenerCount("data") > 0) {
        self2.resume();
      } else if (!state.readableListening) {
        state.flowing = null;
      }
    }
    function nReadingNextTick(self2) {
      debug4("readable nexttick read 0");
      self2.read(0);
    }
    Readable.prototype.resume = function() {
      const state = this._readableState;
      if (!state.flowing) {
        debug4("resume");
        state.flowing = !state.readableListening;
        resume(this, state);
      }
      state[kPaused] = false;
      return this;
    };
    function resume(stream, state) {
      if (!state.resumeScheduled) {
        state.resumeScheduled = true;
        process2.nextTick(resume_, stream, state);
      }
    }
    function resume_(stream, state) {
      debug4("resume", state.reading);
      if (!state.reading) {
        stream.read(0);
      }
      state.resumeScheduled = false;
      stream.emit("resume");
      flow(stream);
      if (state.flowing && !state.reading)
        stream.read(0);
    }
    Readable.prototype.pause = function() {
      debug4("call pause flowing=%j", this._readableState.flowing);
      if (this._readableState.flowing !== false) {
        debug4("pause");
        this._readableState.flowing = false;
        this.emit("pause");
      }
      this._readableState[kPaused] = true;
      return this;
    };
    function flow(stream) {
      const state = stream._readableState;
      debug4("flow", state.flowing);
      while (state.flowing && stream.read() !== null)
        ;
    }
    Readable.prototype.wrap = function(stream) {
      let paused = false;
      stream.on("data", (chunk) => {
        if (!this.push(chunk) && stream.pause) {
          paused = true;
          stream.pause();
        }
      });
      stream.on("end", () => {
        this.push(null);
      });
      stream.on("error", (err) => {
        errorOrDestroy(this, err);
      });
      stream.on("close", () => {
        this.destroy();
      });
      stream.on("destroy", () => {
        this.destroy();
      });
      this._read = () => {
        if (paused && stream.resume) {
          paused = false;
          stream.resume();
        }
      };
      const streamKeys = ObjectKeys(stream);
      for (let j3 = 1; j3 < streamKeys.length; j3++) {
        const i3 = streamKeys[j3];
        if (this[i3] === void 0 && typeof stream[i3] === "function") {
          this[i3] = stream[i3].bind(stream);
        }
      }
      return this;
    };
    Readable.prototype[SymbolAsyncIterator] = function() {
      return streamToAsyncIterator(this);
    };
    Readable.prototype.iterator = function(options) {
      if (options !== void 0) {
        validateObject(options, "options");
      }
      return streamToAsyncIterator(this, options);
    };
    function streamToAsyncIterator(stream, options) {
      if (typeof stream.read !== "function") {
        stream = Readable.wrap(stream, {
          objectMode: true
        });
      }
      const iter = createAsyncIterator(stream, options);
      iter.stream = stream;
      return iter;
    }
    async function* createAsyncIterator(stream, options) {
      let callback = nop;
      function next(resolve) {
        if (this === stream) {
          callback();
          callback = nop;
        } else {
          callback = resolve;
        }
      }
      stream.on("readable", next);
      let error;
      const cleanup = eos2(
        stream,
        {
          writable: false
        },
        (err) => {
          error = err ? aggregateTwoErrors(error, err) : null;
          callback();
          callback = nop;
        }
      );
      try {
        while (true) {
          const chunk = stream.destroyed ? null : stream.read();
          if (chunk !== null) {
            yield chunk;
          } else if (error) {
            throw error;
          } else if (error === null) {
            return;
          } else {
            await new Promise2(next);
          }
        }
      } catch (err) {
        error = aggregateTwoErrors(error, err);
        throw error;
      } finally {
        if ((error || (options === null || options === void 0 ? void 0 : options.destroyOnReturn) !== false) && (error === void 0 || stream._readableState.autoDestroy)) {
          destroyImpl.destroyer(stream, null);
        } else {
          stream.off("readable", next);
          cleanup();
        }
      }
    }
    ObjectDefineProperties(Readable.prototype, {
      readable: {
        __proto__: null,
        get() {
          const r4 = this._readableState;
          return !!r4 && r4.readable !== false && !r4.destroyed && !r4.errorEmitted && !r4.endEmitted;
        },
        set(val2) {
          if (this._readableState) {
            this._readableState.readable = !!val2;
          }
        }
      },
      readableDidRead: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return this._readableState.dataEmitted;
        }
      },
      readableAborted: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted);
        }
      },
      readableHighWaterMark: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return this._readableState.highWaterMark;
        }
      },
      readableBuffer: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return this._readableState && this._readableState.buffer;
        }
      },
      readableFlowing: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return this._readableState.flowing;
        },
        set: function(state) {
          if (this._readableState) {
            this._readableState.flowing = state;
          }
        }
      },
      readableLength: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState.length;
        }
      },
      readableObjectMode: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState ? this._readableState.objectMode : false;
        }
      },
      readableEncoding: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState ? this._readableState.encoding : null;
        }
      },
      errored: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState ? this._readableState.errored : null;
        }
      },
      closed: {
        __proto__: null,
        get() {
          return this._readableState ? this._readableState.closed : false;
        }
      },
      destroyed: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState ? this._readableState.destroyed : false;
        },
        set(value) {
          if (!this._readableState) {
            return;
          }
          this._readableState.destroyed = value;
        }
      },
      readableEnded: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._readableState ? this._readableState.endEmitted : false;
        }
      }
    });
    ObjectDefineProperties(ReadableState.prototype, {
      // Legacy getter for `pipesCount`.
      pipesCount: {
        __proto__: null,
        get() {
          return this.pipes.length;
        }
      },
      // Legacy property for `paused`.
      paused: {
        __proto__: null,
        get() {
          return this[kPaused] !== false;
        },
        set(value) {
          this[kPaused] = !!value;
        }
      }
    });
    Readable._fromList = fromList2;
    function fromList2(n4, state) {
      if (state.length === 0)
        return null;
      let ret;
      if (state.objectMode)
        ret = state.buffer.shift();
      else if (!n4 || n4 >= state.length) {
        if (state.decoder)
          ret = state.buffer.join("");
        else if (state.buffer.length === 1)
          ret = state.buffer.first();
        else
          ret = state.buffer.concat(state.length);
        state.buffer.clear();
      } else {
        ret = state.buffer.consume(n4, state.decoder);
      }
      return ret;
    }
    function endReadable(stream) {
      const state = stream._readableState;
      debug4("endReadable", state.endEmitted);
      if (!state.endEmitted) {
        state.ended = true;
        process2.nextTick(endReadableNT, state, stream);
      }
    }
    function endReadableNT(state, stream) {
      debug4("endReadableNT", state.endEmitted, state.length);
      if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {
        state.endEmitted = true;
        stream.emit("end");
        if (stream.writable && stream.allowHalfOpen === false) {
          process2.nextTick(endWritableNT, stream);
        } else if (state.autoDestroy) {
          const wState = stream._writableState;
          const autoDestroy = !wState || wState.autoDestroy && // We don't expect the writable to ever 'finish'
          // if writable is explicitly set to false.
          (wState.finished || wState.writable === false);
          if (autoDestroy) {
            stream.destroy();
          }
        }
      }
    }
    function endWritableNT(stream) {
      const writable = stream.writable && !stream.writableEnded && !stream.destroyed;
      if (writable) {
        stream.end();
      }
    }
    Readable.from = function(iterable, opts) {
      return from(Readable, iterable, opts);
    };
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === void 0)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Readable.fromWeb = function(readableStream, options) {
      return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options);
    };
    Readable.toWeb = function(streamReadable, options) {
      return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options);
    };
    Readable.wrap = function(src, options) {
      var _ref, _src$readableObjectMo;
      return new Readable({
        objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src.objectMode) !== null && _ref !== void 0 ? _ref : true,
        ...options,
        destroy(err, callback) {
          destroyImpl.destroyer(src, err);
          callback(err);
        }
      }).wrap(src);
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/writable.js
var require_writable = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/writable.js"(exports, module2) {
    var process2 = require_browser2();
    var {
      ArrayPrototypeSlice,
      Error: Error2,
      FunctionPrototypeSymbolHasInstance,
      ObjectDefineProperty,
      ObjectDefineProperties,
      ObjectSetPrototypeOf,
      StringPrototypeToLowerCase,
      Symbol: Symbol2,
      SymbolHasInstance
    } = require_primordials();
    module2.exports = Writable;
    Writable.WritableState = WritableState;
    var { EventEmitter: EE } = require_events();
    var Stream4 = require_legacy().Stream;
    var { Buffer: Buffer2 } = require_buffer();
    var destroyImpl = require_destroy();
    var { addAbortSignal } = require_add_abort_signal();
    var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
    var {
      ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
      ERR_METHOD_NOT_IMPLEMENTED,
      ERR_MULTIPLE_CALLBACK,
      ERR_STREAM_CANNOT_PIPE,
      ERR_STREAM_DESTROYED,
      ERR_STREAM_ALREADY_FINISHED,
      ERR_STREAM_NULL_VALUES,
      ERR_STREAM_WRITE_AFTER_END,
      ERR_UNKNOWN_ENCODING
    } = require_errors3().codes;
    var { errorOrDestroy } = destroyImpl;
    ObjectSetPrototypeOf(Writable.prototype, Stream4.prototype);
    ObjectSetPrototypeOf(Writable, Stream4);
    function nop() {
    }
    var kOnFinished = Symbol2("kOnFinished");
    function WritableState(options, stream, isDuplex) {
      if (typeof isDuplex !== "boolean")
        isDuplex = stream instanceof require_duplex();
      this.objectMode = !!(options && options.objectMode);
      if (isDuplex)
        this.objectMode = this.objectMode || !!(options && options.writableObjectMode);
      this.highWaterMark = options ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false);
      this.finalCalled = false;
      this.needDrain = false;
      this.ending = false;
      this.ended = false;
      this.finished = false;
      this.destroyed = false;
      const noDecode = !!(options && options.decodeStrings === false);
      this.decodeStrings = !noDecode;
      this.defaultEncoding = options && options.defaultEncoding || "utf8";
      this.length = 0;
      this.writing = false;
      this.corked = 0;
      this.sync = true;
      this.bufferProcessing = false;
      this.onwrite = onwrite.bind(void 0, stream);
      this.writecb = null;
      this.writelen = 0;
      this.afterWriteTickInfo = null;
      resetBuffer(this);
      this.pendingcb = 0;
      this.constructed = true;
      this.prefinished = false;
      this.errorEmitted = false;
      this.emitClose = !options || options.emitClose !== false;
      this.autoDestroy = !options || options.autoDestroy !== false;
      this.errored = null;
      this.closed = false;
      this.closeEmitted = false;
      this[kOnFinished] = [];
    }
    function resetBuffer(state) {
      state.buffered = [];
      state.bufferedIndex = 0;
      state.allBuffers = true;
      state.allNoop = true;
    }
    WritableState.prototype.getBuffer = function getBuffer() {
      return ArrayPrototypeSlice(this.buffered, this.bufferedIndex);
    };
    ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", {
      __proto__: null,
      get() {
        return this.buffered.length - this.bufferedIndex;
      }
    });
    function Writable(options) {
      const isDuplex = this instanceof require_duplex();
      if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this))
        return new Writable(options);
      this._writableState = new WritableState(options, this, isDuplex);
      if (options) {
        if (typeof options.write === "function")
          this._write = options.write;
        if (typeof options.writev === "function")
          this._writev = options.writev;
        if (typeof options.destroy === "function")
          this._destroy = options.destroy;
        if (typeof options.final === "function")
          this._final = options.final;
        if (typeof options.construct === "function")
          this._construct = options.construct;
        if (options.signal)
          addAbortSignal(options.signal, this);
      }
      Stream4.call(this, options);
      destroyImpl.construct(this, () => {
        const state = this._writableState;
        if (!state.writing) {
          clearBuffer(this, state);
        }
        finishMaybe(this, state);
      });
    }
    ObjectDefineProperty(Writable, SymbolHasInstance, {
      __proto__: null,
      value: function(object) {
        if (FunctionPrototypeSymbolHasInstance(this, object))
          return true;
        if (this !== Writable)
          return false;
        return object && object._writableState instanceof WritableState;
      }
    });
    Writable.prototype.pipe = function() {
      errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
    };
    function _write(stream, chunk, encoding, cb) {
      const state = stream._writableState;
      if (typeof encoding === "function") {
        cb = encoding;
        encoding = state.defaultEncoding;
      } else {
        if (!encoding)
          encoding = state.defaultEncoding;
        else if (encoding !== "buffer" && !Buffer2.isEncoding(encoding))
          throw new ERR_UNKNOWN_ENCODING(encoding);
        if (typeof cb !== "function")
          cb = nop;
      }
      if (chunk === null) {
        throw new ERR_STREAM_NULL_VALUES();
      } else if (!state.objectMode) {
        if (typeof chunk === "string") {
          if (state.decodeStrings !== false) {
            chunk = Buffer2.from(chunk, encoding);
            encoding = "buffer";
          }
        } else if (chunk instanceof Buffer2) {
          encoding = "buffer";
        } else if (Stream4._isUint8Array(chunk)) {
          chunk = Stream4._uint8ArrayToBuffer(chunk);
          encoding = "buffer";
        } else {
          throw new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk);
        }
      }
      let err;
      if (state.ending) {
        err = new ERR_STREAM_WRITE_AFTER_END();
      } else if (state.destroyed) {
        err = new ERR_STREAM_DESTROYED("write");
      }
      if (err) {
        process2.nextTick(cb, err);
        errorOrDestroy(stream, err, true);
        return err;
      }
      state.pendingcb++;
      return writeOrBuffer(stream, state, chunk, encoding, cb);
    }
    Writable.prototype.write = function(chunk, encoding, cb) {
      return _write(this, chunk, encoding, cb) === true;
    };
    Writable.prototype.cork = function() {
      this._writableState.corked++;
    };
    Writable.prototype.uncork = function() {
      const state = this._writableState;
      if (state.corked) {
        state.corked--;
        if (!state.writing)
          clearBuffer(this, state);
      }
    };
    Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
      if (typeof encoding === "string")
        encoding = StringPrototypeToLowerCase(encoding);
      if (!Buffer2.isEncoding(encoding))
        throw new ERR_UNKNOWN_ENCODING(encoding);
      this._writableState.defaultEncoding = encoding;
      return this;
    };
    function writeOrBuffer(stream, state, chunk, encoding, callback) {
      const len = state.objectMode ? 1 : chunk.length;
      state.length += len;
      const ret = state.length < state.highWaterMark;
      if (!ret)
        state.needDrain = true;
      if (state.writing || state.corked || state.errored || !state.constructed) {
        state.buffered.push({
          chunk,
          encoding,
          callback
        });
        if (state.allBuffers && encoding !== "buffer") {
          state.allBuffers = false;
        }
        if (state.allNoop && callback !== nop) {
          state.allNoop = false;
        }
      } else {
        state.writelen = len;
        state.writecb = callback;
        state.writing = true;
        state.sync = true;
        stream._write(chunk, encoding, state.onwrite);
        state.sync = false;
      }
      return ret && !state.errored && !state.destroyed;
    }
    function doWrite(stream, state, writev, len, chunk, encoding, cb) {
      state.writelen = len;
      state.writecb = cb;
      state.writing = true;
      state.sync = true;
      if (state.destroyed)
        state.onwrite(new ERR_STREAM_DESTROYED("write"));
      else if (writev)
        stream._writev(chunk, state.onwrite);
      else
        stream._write(chunk, encoding, state.onwrite);
      state.sync = false;
    }
    function onwriteError(stream, state, er, cb) {
      --state.pendingcb;
      cb(er);
      errorBuffer(state);
      errorOrDestroy(stream, er);
    }
    function onwrite(stream, er) {
      const state = stream._writableState;
      const sync = state.sync;
      const cb = state.writecb;
      if (typeof cb !== "function") {
        errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK());
        return;
      }
      state.writing = false;
      state.writecb = null;
      state.length -= state.writelen;
      state.writelen = 0;
      if (er) {
        er.stack;
        if (!state.errored) {
          state.errored = er;
        }
        if (stream._readableState && !stream._readableState.errored) {
          stream._readableState.errored = er;
        }
        if (sync) {
          process2.nextTick(onwriteError, stream, state, er, cb);
        } else {
          onwriteError(stream, state, er, cb);
        }
      } else {
        if (state.buffered.length > state.bufferedIndex) {
          clearBuffer(stream, state);
        }
        if (sync) {
          if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {
            state.afterWriteTickInfo.count++;
          } else {
            state.afterWriteTickInfo = {
              count: 1,
              cb,
              stream,
              state
            };
            process2.nextTick(afterWriteTick, state.afterWriteTickInfo);
          }
        } else {
          afterWrite(stream, state, 1, cb);
        }
      }
    }
    function afterWriteTick({ stream, state, count: count5, cb }) {
      state.afterWriteTickInfo = null;
      return afterWrite(stream, state, count5, cb);
    }
    function afterWrite(stream, state, count5, cb) {
      const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain;
      if (needDrain) {
        state.needDrain = false;
        stream.emit("drain");
      }
      while (count5-- > 0) {
        state.pendingcb--;
        cb();
      }
      if (state.destroyed) {
        errorBuffer(state);
      }
      finishMaybe(stream, state);
    }
    function errorBuffer(state) {
      if (state.writing) {
        return;
      }
      for (let n4 = state.bufferedIndex; n4 < state.buffered.length; ++n4) {
        var _state$errored;
        const { chunk, callback } = state.buffered[n4];
        const len = state.objectMode ? 1 : chunk.length;
        state.length -= len;
        callback(
          (_state$errored = state.errored) !== null && _state$errored !== void 0 ? _state$errored : new ERR_STREAM_DESTROYED("write")
        );
      }
      const onfinishCallbacks = state[kOnFinished].splice(0);
      for (let i3 = 0; i3 < onfinishCallbacks.length; i3++) {
        var _state$errored2;
        onfinishCallbacks[i3](
          (_state$errored2 = state.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 : new ERR_STREAM_DESTROYED("end")
        );
      }
      resetBuffer(state);
    }
    function clearBuffer(stream, state) {
      if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {
        return;
      }
      const { buffered, bufferedIndex, objectMode } = state;
      const bufferedLength = buffered.length - bufferedIndex;
      if (!bufferedLength) {
        return;
      }
      let i3 = bufferedIndex;
      state.bufferProcessing = true;
      if (bufferedLength > 1 && stream._writev) {
        state.pendingcb -= bufferedLength - 1;
        const callback = state.allNoop ? nop : (err) => {
          for (let n4 = i3; n4 < buffered.length; ++n4) {
            buffered[n4].callback(err);
          }
        };
        const chunks = state.allNoop && i3 === 0 ? buffered : ArrayPrototypeSlice(buffered, i3);
        chunks.allBuffers = state.allBuffers;
        doWrite(stream, state, true, state.length, chunks, "", callback);
        resetBuffer(state);
      } else {
        do {
          const { chunk, encoding, callback } = buffered[i3];
          buffered[i3++] = null;
          const len = objectMode ? 1 : chunk.length;
          doWrite(stream, state, false, len, chunk, encoding, callback);
        } while (i3 < buffered.length && !state.writing);
        if (i3 === buffered.length) {
          resetBuffer(state);
        } else if (i3 > 256) {
          buffered.splice(0, i3);
          state.bufferedIndex = 0;
        } else {
          state.bufferedIndex = i3;
        }
      }
      state.bufferProcessing = false;
    }
    Writable.prototype._write = function(chunk, encoding, cb) {
      if (this._writev) {
        this._writev(
          [
            {
              chunk,
              encoding
            }
          ],
          cb
        );
      } else {
        throw new ERR_METHOD_NOT_IMPLEMENTED("_write()");
      }
    };
    Writable.prototype._writev = null;
    Writable.prototype.end = function(chunk, encoding, cb) {
      const state = this._writableState;
      if (typeof chunk === "function") {
        cb = chunk;
        chunk = null;
        encoding = null;
      } else if (typeof encoding === "function") {
        cb = encoding;
        encoding = null;
      }
      let err;
      if (chunk !== null && chunk !== void 0) {
        const ret = _write(this, chunk, encoding);
        if (ret instanceof Error2) {
          err = ret;
        }
      }
      if (state.corked) {
        state.corked = 1;
        this.uncork();
      }
      if (err) {
      } else if (!state.errored && !state.ending) {
        state.ending = true;
        finishMaybe(this, state, true);
        state.ended = true;
      } else if (state.finished) {
        err = new ERR_STREAM_ALREADY_FINISHED("end");
      } else if (state.destroyed) {
        err = new ERR_STREAM_DESTROYED("end");
      }
      if (typeof cb === "function") {
        if (err || state.finished) {
          process2.nextTick(cb, err);
        } else {
          state[kOnFinished].push(cb);
        }
      }
      return this;
    };
    function needFinish(state) {
      return state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted;
    }
    function callFinal(stream, state) {
      let called = false;
      function onFinish(err) {
        if (called) {
          errorOrDestroy(stream, err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK());
          return;
        }
        called = true;
        state.pendingcb--;
        if (err) {
          const onfinishCallbacks = state[kOnFinished].splice(0);
          for (let i3 = 0; i3 < onfinishCallbacks.length; i3++) {
            onfinishCallbacks[i3](err);
          }
          errorOrDestroy(stream, err, state.sync);
        } else if (needFinish(state)) {
          state.prefinished = true;
          stream.emit("prefinish");
          state.pendingcb++;
          process2.nextTick(finish, stream, state);
        }
      }
      state.sync = true;
      state.pendingcb++;
      try {
        stream._final(onFinish);
      } catch (err) {
        onFinish(err);
      }
      state.sync = false;
    }
    function prefinish(stream, state) {
      if (!state.prefinished && !state.finalCalled) {
        if (typeof stream._final === "function" && !state.destroyed) {
          state.finalCalled = true;
          callFinal(stream, state);
        } else {
          state.prefinished = true;
          stream.emit("prefinish");
        }
      }
    }
    function finishMaybe(stream, state, sync) {
      if (needFinish(state)) {
        prefinish(stream, state);
        if (state.pendingcb === 0) {
          if (sync) {
            state.pendingcb++;
            process2.nextTick(
              (stream2, state2) => {
                if (needFinish(state2)) {
                  finish(stream2, state2);
                } else {
                  state2.pendingcb--;
                }
              },
              stream,
              state
            );
          } else if (needFinish(state)) {
            state.pendingcb++;
            finish(stream, state);
          }
        }
      }
    }
    function finish(stream, state) {
      state.pendingcb--;
      state.finished = true;
      const onfinishCallbacks = state[kOnFinished].splice(0);
      for (let i3 = 0; i3 < onfinishCallbacks.length; i3++) {
        onfinishCallbacks[i3]();
      }
      stream.emit("finish");
      if (state.autoDestroy) {
        const rState = stream._readableState;
        const autoDestroy = !rState || rState.autoDestroy && // We don't expect the readable to ever 'end'
        // if readable is explicitly set to false.
        (rState.endEmitted || rState.readable === false);
        if (autoDestroy) {
          stream.destroy();
        }
      }
    }
    ObjectDefineProperties(Writable.prototype, {
      closed: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.closed : false;
        }
      },
      destroyed: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.destroyed : false;
        },
        set(value) {
          if (this._writableState) {
            this._writableState.destroyed = value;
          }
        }
      },
      writable: {
        __proto__: null,
        get() {
          const w2 = this._writableState;
          return !!w2 && w2.writable !== false && !w2.destroyed && !w2.errored && !w2.ending && !w2.ended;
        },
        set(val2) {
          if (this._writableState) {
            this._writableState.writable = !!val2;
          }
        }
      },
      writableFinished: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.finished : false;
        }
      },
      writableObjectMode: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.objectMode : false;
        }
      },
      writableBuffer: {
        __proto__: null,
        get() {
          return this._writableState && this._writableState.getBuffer();
        }
      },
      writableEnded: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.ending : false;
        }
      },
      writableNeedDrain: {
        __proto__: null,
        get() {
          const wState = this._writableState;
          if (!wState)
            return false;
          return !wState.destroyed && !wState.ending && wState.needDrain;
        }
      },
      writableHighWaterMark: {
        __proto__: null,
        get() {
          return this._writableState && this._writableState.highWaterMark;
        }
      },
      writableCorked: {
        __proto__: null,
        get() {
          return this._writableState ? this._writableState.corked : 0;
        }
      },
      writableLength: {
        __proto__: null,
        get() {
          return this._writableState && this._writableState.length;
        }
      },
      errored: {
        __proto__: null,
        enumerable: false,
        get() {
          return this._writableState ? this._writableState.errored : null;
        }
      },
      writableAborted: {
        __proto__: null,
        enumerable: false,
        get: function() {
          return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished);
        }
      }
    });
    var destroy = destroyImpl.destroy;
    Writable.prototype.destroy = function(err, cb) {
      const state = this._writableState;
      if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {
        process2.nextTick(errorBuffer, state);
      }
      destroy.call(this, err, cb);
      return this;
    };
    Writable.prototype._undestroy = destroyImpl.undestroy;
    Writable.prototype._destroy = function(err, cb) {
      cb(err);
    };
    Writable.prototype[EE.captureRejectionSymbol] = function(err) {
      this.destroy(err);
    };
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === void 0)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Writable.fromWeb = function(writableStream, options) {
      return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options);
    };
    Writable.toWeb = function(streamWritable) {
      return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable);
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/duplexify.js
var require_duplexify = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/duplexify.js"(exports, module2) {
    var process2 = require_browser2();
    var bufferModule = require_buffer();
    var {
      isReadable,
      isWritable,
      isIterable,
      isNodeStream,
      isReadableNodeStream,
      isWritableNodeStream,
      isDuplexNodeStream,
      isReadableStream: isReadableStream2,
      isWritableStream
    } = require_utils();
    var eos2 = require_end_of_stream();
    var {
      AbortError,
      codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_RETURN_VALUE }
    } = require_errors3();
    var { destroyer } = require_destroy();
    var Duplex = require_duplex();
    var Readable = require_readable();
    var Writable = require_writable();
    var { createDeferredPromise } = require_util3();
    var from = require_from();
    var Blob5 = globalThis.Blob || bufferModule.Blob;
    var isBlob = typeof Blob5 !== "undefined" ? function isBlob2(b3) {
      return b3 instanceof Blob5;
    } : function isBlob2(b3) {
      return false;
    };
    var AbortController2 = globalThis.AbortController || require_browser().AbortController;
    var { FunctionPrototypeCall } = require_primordials();
    var Duplexify = class extends Duplex {
      constructor(options) {
        super(options);
        if ((options === null || options === void 0 ? void 0 : options.readable) === false) {
          this._readableState.readable = false;
          this._readableState.ended = true;
          this._readableState.endEmitted = true;
        }
        if ((options === null || options === void 0 ? void 0 : options.writable) === false) {
          this._writableState.writable = false;
          this._writableState.ending = true;
          this._writableState.ended = true;
          this._writableState.finished = true;
        }
      }
    };
    module2.exports = function duplexify(body, name) {
      if (isDuplexNodeStream(body)) {
        return body;
      }
      if (isReadableNodeStream(body)) {
        return _duplexify({
          readable: body
        });
      }
      if (isWritableNodeStream(body)) {
        return _duplexify({
          writable: body
        });
      }
      if (isNodeStream(body)) {
        return _duplexify({
          writable: false,
          readable: false
        });
      }
      if (isReadableStream2(body)) {
        return _duplexify({
          readable: Readable.fromWeb(body)
        });
      }
      if (isWritableStream(body)) {
        return _duplexify({
          writable: Writable.fromWeb(body)
        });
      }
      if (typeof body === "function") {
        const { value, write, final, destroy } = fromAsyncGen(body);
        if (isIterable(value)) {
          return from(Duplexify, value, {
            // TODO (ronag): highWaterMark?
            objectMode: true,
            write,
            final,
            destroy
          });
        }
        const then2 = value === null || value === void 0 ? void 0 : value.then;
        if (typeof then2 === "function") {
          let d3;
          const promise = FunctionPrototypeCall(
            then2,
            value,
            (val2) => {
              if (val2 != null) {
                throw new ERR_INVALID_RETURN_VALUE("nully", "body", val2);
              }
            },
            (err) => {
              destroyer(d3, err);
            }
          );
          return d3 = new Duplexify({
            // TODO (ronag): highWaterMark?
            objectMode: true,
            readable: false,
            write,
            final(cb) {
              final(async () => {
                try {
                  await promise;
                  process2.nextTick(cb, null);
                } catch (err) {
                  process2.nextTick(cb, err);
                }
              });
            },
            destroy
          });
        }
        throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value);
      }
      if (isBlob(body)) {
        return duplexify(body.arrayBuffer());
      }
      if (isIterable(body)) {
        return from(Duplexify, body, {
          // TODO (ronag): highWaterMark?
          objectMode: true,
          writable: false
        });
      }
      if (isReadableStream2(body === null || body === void 0 ? void 0 : body.readable) && isWritableStream(body === null || body === void 0 ? void 0 : body.writable)) {
        return Duplexify.fromWeb(body);
      }
      if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") {
        const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0;
        const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0;
        return _duplexify({
          readable,
          writable
        });
      }
      const then = body === null || body === void 0 ? void 0 : body.then;
      if (typeof then === "function") {
        let d3;
        FunctionPrototypeCall(
          then,
          body,
          (val2) => {
            if (val2 != null) {
              d3.push(val2);
            }
            d3.push(null);
          },
          (err) => {
            destroyer(d3, err);
          }
        );
        return d3 = new Duplexify({
          objectMode: true,
          writable: false,
          read() {
          }
        });
      }
      throw new ERR_INVALID_ARG_TYPE2(
        name,
        [
          "Blob",
          "ReadableStream",
          "WritableStream",
          "Stream",
          "Iterable",
          "AsyncIterable",
          "Function",
          "{ readable, writable } pair",
          "Promise"
        ],
        body
      );
    };
    function fromAsyncGen(fn) {
      let { promise, resolve } = createDeferredPromise();
      const ac = new AbortController2();
      const signal = ac.signal;
      const value = fn(
        async function* () {
          while (true) {
            const _promise = promise;
            promise = null;
            const { chunk, done, cb } = await _promise;
            process2.nextTick(cb);
            if (done)
              return;
            if (signal.aborted)
              throw new AbortError(void 0, {
                cause: signal.reason
              });
            ({ promise, resolve } = createDeferredPromise());
            yield chunk;
          }
        }(),
        {
          signal
        }
      );
      return {
        value,
        write(chunk, encoding, cb) {
          const _resolve = resolve;
          resolve = null;
          _resolve({
            chunk,
            done: false,
            cb
          });
        },
        final(cb) {
          const _resolve = resolve;
          resolve = null;
          _resolve({
            done: true,
            cb
          });
        },
        destroy(err, cb) {
          ac.abort();
          cb(err);
        }
      };
    }
    function _duplexify(pair) {
      const r4 = pair.readable && typeof pair.readable.read !== "function" ? Readable.wrap(pair.readable) : pair.readable;
      const w2 = pair.writable;
      let readable = !!isReadable(r4);
      let writable = !!isWritable(w2);
      let ondrain;
      let onfinish;
      let onreadable;
      let onclose;
      let d3;
      function onfinished(err) {
        const cb = onclose;
        onclose = null;
        if (cb) {
          cb(err);
        } else if (err) {
          d3.destroy(err);
        }
      }
      d3 = new Duplexify({
        // TODO (ronag): highWaterMark?
        readableObjectMode: !!(r4 !== null && r4 !== void 0 && r4.readableObjectMode),
        writableObjectMode: !!(w2 !== null && w2 !== void 0 && w2.writableObjectMode),
        readable,
        writable
      });
      if (writable) {
        eos2(w2, (err) => {
          writable = false;
          if (err) {
            destroyer(r4, err);
          }
          onfinished(err);
        });
        d3._write = function(chunk, encoding, callback) {
          if (w2.write(chunk, encoding)) {
            callback();
          } else {
            ondrain = callback;
          }
        };
        d3._final = function(callback) {
          w2.end();
          onfinish = callback;
        };
        w2.on("drain", function() {
          if (ondrain) {
            const cb = ondrain;
            ondrain = null;
            cb();
          }
        });
        w2.on("finish", function() {
          if (onfinish) {
            const cb = onfinish;
            onfinish = null;
            cb();
          }
        });
      }
      if (readable) {
        eos2(r4, (err) => {
          readable = false;
          if (err) {
            destroyer(r4, err);
          }
          onfinished(err);
        });
        r4.on("readable", function() {
          if (onreadable) {
            const cb = onreadable;
            onreadable = null;
            cb();
          }
        });
        r4.on("end", function() {
          d3.push(null);
        });
        d3._read = function() {
          while (true) {
            const buf = r4.read();
            if (buf === null) {
              onreadable = d3._read;
              return;
            }
            if (!d3.push(buf)) {
              return;
            }
          }
        };
      }
      d3._destroy = function(err, callback) {
        if (!err && onclose !== null) {
          err = new AbortError();
        }
        onreadable = null;
        ondrain = null;
        onfinish = null;
        if (onclose === null) {
          callback(err);
        } else {
          onclose = callback;
          destroyer(w2, err);
          destroyer(r4, err);
        }
      };
      return d3;
    }
  }
});

// node_modules/readable-stream/lib/internal/streams/duplex.js
var require_duplex = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/duplex.js"(exports, module2) {
    "use strict";
    var {
      ObjectDefineProperties,
      ObjectGetOwnPropertyDescriptor,
      ObjectKeys,
      ObjectSetPrototypeOf
    } = require_primordials();
    module2.exports = Duplex;
    var Readable = require_readable();
    var Writable = require_writable();
    ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype);
    ObjectSetPrototypeOf(Duplex, Readable);
    {
      const keys = ObjectKeys(Writable.prototype);
      for (let i3 = 0; i3 < keys.length; i3++) {
        const method = keys[i3];
        if (!Duplex.prototype[method])
          Duplex.prototype[method] = Writable.prototype[method];
      }
    }
    function Duplex(options) {
      if (!(this instanceof Duplex))
        return new Duplex(options);
      Readable.call(this, options);
      Writable.call(this, options);
      if (options) {
        this.allowHalfOpen = options.allowHalfOpen !== false;
        if (options.readable === false) {
          this._readableState.readable = false;
          this._readableState.ended = true;
          this._readableState.endEmitted = true;
        }
        if (options.writable === false) {
          this._writableState.writable = false;
          this._writableState.ending = true;
          this._writableState.ended = true;
          this._writableState.finished = true;
        }
      } else {
        this.allowHalfOpen = true;
      }
    }
    ObjectDefineProperties(Duplex.prototype, {
      writable: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable")
      },
      writableHighWaterMark: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableHighWaterMark")
      },
      writableObjectMode: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableObjectMode")
      },
      writableBuffer: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer")
      },
      writableLength: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength")
      },
      writableFinished: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableFinished")
      },
      writableCorked: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked")
      },
      writableEnded: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded")
      },
      writableNeedDrain: {
        __proto__: null,
        ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableNeedDrain")
      },
      destroyed: {
        __proto__: null,
        get() {
          if (this._readableState === void 0 || this._writableState === void 0) {
            return false;
          }
          return this._readableState.destroyed && this._writableState.destroyed;
        },
        set(value) {
          if (this._readableState && this._writableState) {
            this._readableState.destroyed = value;
            this._writableState.destroyed = value;
          }
        }
      }
    });
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === void 0)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Duplex.fromWeb = function(pair, options) {
      return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options);
    };
    Duplex.toWeb = function(duplex) {
      return lazyWebStreams().newReadableWritablePairFromDuplex(duplex);
    };
    var duplexify;
    Duplex.from = function(body) {
      if (!duplexify) {
        duplexify = require_duplexify();
      }
      return duplexify(body, "body");
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/transform.js
var require_transform = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/transform.js"(exports, module2) {
    "use strict";
    var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials();
    module2.exports = Transform;
    var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors3().codes;
    var Duplex = require_duplex();
    var { getHighWaterMark } = require_state();
    ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
    ObjectSetPrototypeOf(Transform, Duplex);
    var kCallback = Symbol2("kCallback");
    function Transform(options) {
      if (!(this instanceof Transform))
        return new Transform(options);
      const readableHighWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", true) : null;
      if (readableHighWaterMark === 0) {
        options = {
          ...options,
          highWaterMark: null,
          readableHighWaterMark,
          // TODO (ronag): 0 is not optimal since we have
          // a "bug" where we check needDrain before calling _write and not after.
          // Refs: https://github.com/nodejs/node/pull/32887
          // Refs: https://github.com/nodejs/node/pull/35941
          writableHighWaterMark: options.writableHighWaterMark || 0
        };
      }
      Duplex.call(this, options);
      this._readableState.sync = false;
      this[kCallback] = null;
      if (options) {
        if (typeof options.transform === "function")
          this._transform = options.transform;
        if (typeof options.flush === "function")
          this._flush = options.flush;
      }
      this.on("prefinish", prefinish);
    }
    function final(cb) {
      if (typeof this._flush === "function" && !this.destroyed) {
        this._flush((er, data) => {
          if (er) {
            if (cb) {
              cb(er);
            } else {
              this.destroy(er);
            }
            return;
          }
          if (data != null) {
            this.push(data);
          }
          this.push(null);
          if (cb) {
            cb();
          }
        });
      } else {
        this.push(null);
        if (cb) {
          cb();
        }
      }
    }
    function prefinish() {
      if (this._final !== final) {
        final.call(this);
      }
    }
    Transform.prototype._final = final;
    Transform.prototype._transform = function(chunk, encoding, callback) {
      throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()");
    };
    Transform.prototype._write = function(chunk, encoding, callback) {
      const rState = this._readableState;
      const wState = this._writableState;
      const length = rState.length;
      this._transform(chunk, encoding, (err, val2) => {
        if (err) {
          callback(err);
          return;
        }
        if (val2 != null) {
          this.push(val2);
        }
        if (wState.ended || // Backwards compat.
        length === rState.length || // Backwards compat.
        rState.length < rState.highWaterMark) {
          callback();
        } else {
          this[kCallback] = callback;
        }
      });
    };
    Transform.prototype._read = function() {
      if (this[kCallback]) {
        const callback = this[kCallback];
        this[kCallback] = null;
        callback();
      }
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/passthrough.js
var require_passthrough = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/passthrough.js"(exports, module2) {
    "use strict";
    var { ObjectSetPrototypeOf } = require_primordials();
    module2.exports = PassThrough;
    var Transform = require_transform();
    ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype);
    ObjectSetPrototypeOf(PassThrough, Transform);
    function PassThrough(options) {
      if (!(this instanceof PassThrough))
        return new PassThrough(options);
      Transform.call(this, options);
    }
    PassThrough.prototype._transform = function(chunk, encoding, cb) {
      cb(null, chunk);
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/pipeline.js
var require_pipeline = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports, module2) {
    var process2 = require_browser2();
    var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials();
    var eos2 = require_end_of_stream();
    var { once } = require_util3();
    var destroyImpl = require_destroy();
    var Duplex = require_duplex();
    var {
      aggregateTwoErrors,
      codes: {
        ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
        ERR_INVALID_RETURN_VALUE,
        ERR_MISSING_ARGS,
        ERR_STREAM_DESTROYED,
        ERR_STREAM_PREMATURE_CLOSE
      },
      AbortError
    } = require_errors3();
    var { validateFunction, validateAbortSignal } = require_validators();
    var {
      isIterable,
      isReadable,
      isReadableNodeStream,
      isNodeStream,
      isTransformStream,
      isWebStream,
      isReadableStream: isReadableStream2,
      isReadableFinished
    } = require_utils();
    var AbortController2 = globalThis.AbortController || require_browser().AbortController;
    var PassThrough;
    var Readable;
    var addAbortListener;
    function destroyer(stream, reading, writing) {
      let finished = false;
      stream.on("close", () => {
        finished = true;
      });
      const cleanup = eos2(
        stream,
        {
          readable: reading,
          writable: writing
        },
        (err) => {
          finished = !err;
        }
      );
      return {
        destroy: (err) => {
          if (finished)
            return;
          finished = true;
          destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED("pipe"));
        },
        cleanup
      };
    }
    function popCallback(streams) {
      validateFunction(streams[streams.length - 1], "streams[stream.length - 1]");
      return streams.pop();
    }
    function makeAsyncIterable(val2) {
      if (isIterable(val2)) {
        return val2;
      } else if (isReadableNodeStream(val2)) {
        return fromReadable(val2);
      }
      throw new ERR_INVALID_ARG_TYPE2("val", ["Readable", "Iterable", "AsyncIterable"], val2);
    }
    async function* fromReadable(val2) {
      if (!Readable) {
        Readable = require_readable();
      }
      yield* Readable.prototype[SymbolAsyncIterator].call(val2);
    }
    async function pumpToNode(iterable, writable, finish, { end }) {
      let error;
      let onresolve = null;
      const resume = (err) => {
        if (err) {
          error = err;
        }
        if (onresolve) {
          const callback = onresolve;
          onresolve = null;
          callback();
        }
      };
      const wait = () => new Promise2((resolve, reject) => {
        if (error) {
          reject(error);
        } else {
          onresolve = () => {
            if (error) {
              reject(error);
            } else {
              resolve();
            }
          };
        }
      });
      writable.on("drain", resume);
      const cleanup = eos2(
        writable,
        {
          readable: false
        },
        resume
      );
      try {
        if (writable.writableNeedDrain) {
          await wait();
        }
        for await (const chunk of iterable) {
          if (!writable.write(chunk)) {
            await wait();
          }
        }
        if (end) {
          writable.end();
          await wait();
        }
        finish();
      } catch (err) {
        finish(error !== err ? aggregateTwoErrors(error, err) : err);
      } finally {
        cleanup();
        writable.off("drain", resume);
      }
    }
    async function pumpToWeb(readable, writable, finish, { end }) {
      if (isTransformStream(writable)) {
        writable = writable.writable;
      }
      const writer = writable.getWriter();
      try {
        for await (const chunk of readable) {
          await writer.ready;
          writer.write(chunk).catch(() => {
          });
        }
        await writer.ready;
        if (end) {
          await writer.close();
        }
        finish();
      } catch (err) {
        try {
          await writer.abort(err);
          finish(err);
        } catch (err2) {
          finish(err2);
        }
      }
    }
    function pipeline(...streams) {
      return pipelineImpl(streams, once(popCallback(streams)));
    }
    function pipelineImpl(streams, callback, opts) {
      if (streams.length === 1 && ArrayIsArray(streams[0])) {
        streams = streams[0];
      }
      if (streams.length < 2) {
        throw new ERR_MISSING_ARGS("streams");
      }
      const ac = new AbortController2();
      const signal = ac.signal;
      const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal;
      const lastStreamCleanup = [];
      validateAbortSignal(outerSignal, "options.signal");
      function abort() {
        finishImpl(new AbortError());
      }
      addAbortListener = addAbortListener || require_util3().addAbortListener;
      let disposable;
      if (outerSignal) {
        disposable = addAbortListener(outerSignal, abort);
      }
      let error;
      let value;
      const destroys = [];
      let finishCount = 0;
      function finish(err) {
        finishImpl(err, --finishCount === 0);
      }
      function finishImpl(err, final) {
        var _disposable;
        if (err && (!error || error.code === "ERR_STREAM_PREMATURE_CLOSE")) {
          error = err;
        }
        if (!error && !final) {
          return;
        }
        while (destroys.length) {
          destroys.shift()(error);
        }
        ;
        (_disposable = disposable) === null || _disposable === void 0 ? void 0 : _disposable[SymbolDispose]();
        ac.abort();
        if (final) {
          if (!error) {
            lastStreamCleanup.forEach((fn) => fn());
          }
          process2.nextTick(callback, error, value);
        }
      }
      let ret;
      for (let i3 = 0; i3 < streams.length; i3++) {
        const stream = streams[i3];
        const reading = i3 < streams.length - 1;
        const writing = i3 > 0;
        const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false;
        const isLastStream = i3 === streams.length - 1;
        if (isNodeStream(stream)) {
          let onError2 = function(err) {
            if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE") {
              finish(err);
            }
          };
          var onError = onError2;
          if (end) {
            const { destroy, cleanup } = destroyer(stream, reading, writing);
            destroys.push(destroy);
            if (isReadable(stream) && isLastStream) {
              lastStreamCleanup.push(cleanup);
            }
          }
          stream.on("error", onError2);
          if (isReadable(stream) && isLastStream) {
            lastStreamCleanup.push(() => {
              stream.removeListener("error", onError2);
            });
          }
        }
        if (i3 === 0) {
          if (typeof stream === "function") {
            ret = stream({
              signal
            });
            if (!isIterable(ret)) {
              throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret);
            }
          } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {
            ret = stream;
          } else {
            ret = Duplex.from(stream);
          }
        } else if (typeof stream === "function") {
          if (isTransformStream(ret)) {
            var _ret;
            ret = makeAsyncIterable((_ret = ret) === null || _ret === void 0 ? void 0 : _ret.readable);
          } else {
            ret = makeAsyncIterable(ret);
          }
          ret = stream(ret, {
            signal
          });
          if (reading) {
            if (!isIterable(ret, true)) {
              throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i3 - 1}]`, ret);
            }
          } else {
            var _ret2;
            if (!PassThrough) {
              PassThrough = require_passthrough();
            }
            const pt = new PassThrough({
              objectMode: true
            });
            const then = (_ret2 = ret) === null || _ret2 === void 0 ? void 0 : _ret2.then;
            if (typeof then === "function") {
              finishCount++;
              then.call(
                ret,
                (val2) => {
                  value = val2;
                  if (val2 != null) {
                    pt.write(val2);
                  }
                  if (end) {
                    pt.end();
                  }
                  process2.nextTick(finish);
                },
                (err) => {
                  pt.destroy(err);
                  process2.nextTick(finish, err);
                }
              );
            } else if (isIterable(ret, true)) {
              finishCount++;
              pumpToNode(ret, pt, finish, {
                end
              });
            } else if (isReadableStream2(ret) || isTransformStream(ret)) {
              const toRead = ret.readable || ret;
              finishCount++;
              pumpToNode(toRead, pt, finish, {
                end
              });
            } else {
              throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret);
            }
            ret = pt;
            const { destroy, cleanup } = destroyer(ret, false, true);
            destroys.push(destroy);
            if (isLastStream) {
              lastStreamCleanup.push(cleanup);
            }
          }
        } else if (isNodeStream(stream)) {
          if (isReadableNodeStream(ret)) {
            finishCount += 2;
            const cleanup = pipe(ret, stream, finish, {
              end
            });
            if (isReadable(stream) && isLastStream) {
              lastStreamCleanup.push(cleanup);
            }
          } else if (isTransformStream(ret) || isReadableStream2(ret)) {
            const toRead = ret.readable || ret;
            finishCount++;
            pumpToNode(toRead, stream, finish, {
              end
            });
          } else if (isIterable(ret)) {
            finishCount++;
            pumpToNode(ret, stream, finish, {
              end
            });
          } else {
            throw new ERR_INVALID_ARG_TYPE2(
              "val",
              ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"],
              ret
            );
          }
          ret = stream;
        } else if (isWebStream(stream)) {
          if (isReadableNodeStream(ret)) {
            finishCount++;
            pumpToWeb(makeAsyncIterable(ret), stream, finish, {
              end
            });
          } else if (isReadableStream2(ret) || isIterable(ret)) {
            finishCount++;
            pumpToWeb(ret, stream, finish, {
              end
            });
          } else if (isTransformStream(ret)) {
            finishCount++;
            pumpToWeb(ret.readable, stream, finish, {
              end
            });
          } else {
            throw new ERR_INVALID_ARG_TYPE2(
              "val",
              ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"],
              ret
            );
          }
          ret = stream;
        } else {
          ret = Duplex.from(stream);
        }
      }
      if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) {
        process2.nextTick(abort);
      }
      return ret;
    }
    function pipe(src, dst, finish, { end }) {
      let ended = false;
      dst.on("close", () => {
        if (!ended) {
          finish(new ERR_STREAM_PREMATURE_CLOSE());
        }
      });
      src.pipe(dst, {
        end: false
      });
      if (end) {
        let endFn2 = function() {
          ended = true;
          dst.end();
        };
        var endFn = endFn2;
        if (isReadableFinished(src)) {
          process2.nextTick(endFn2);
        } else {
          src.once("end", endFn2);
        }
      } else {
        finish();
      }
      eos2(
        src,
        {
          readable: true,
          writable: false
        },
        (err) => {
          const rState = src._readableState;
          if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted) {
            src.once("end", finish).once("error", finish);
          } else {
            finish(err);
          }
        }
      );
      return eos2(
        dst,
        {
          readable: false,
          writable: true
        },
        finish
      );
    }
    module2.exports = {
      pipelineImpl,
      pipeline
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/compose.js
var require_compose = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/compose.js"(exports, module2) {
    "use strict";
    var { pipeline } = require_pipeline();
    var Duplex = require_duplex();
    var { destroyer } = require_destroy();
    var {
      isNodeStream,
      isReadable,
      isWritable,
      isWebStream,
      isTransformStream,
      isWritableStream,
      isReadableStream: isReadableStream2
    } = require_utils();
    var {
      AbortError,
      codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }
    } = require_errors3();
    var eos2 = require_end_of_stream();
    module2.exports = function compose(...streams) {
      if (streams.length === 0) {
        throw new ERR_MISSING_ARGS("streams");
      }
      if (streams.length === 1) {
        return Duplex.from(streams[0]);
      }
      const orgStreams = [...streams];
      if (typeof streams[0] === "function") {
        streams[0] = Duplex.from(streams[0]);
      }
      if (typeof streams[streams.length - 1] === "function") {
        const idx = streams.length - 1;
        streams[idx] = Duplex.from(streams[idx]);
      }
      for (let n4 = 0; n4 < streams.length; ++n4) {
        if (!isNodeStream(streams[n4]) && !isWebStream(streams[n4])) {
          continue;
        }
        if (n4 < streams.length - 1 && !(isReadable(streams[n4]) || isReadableStream2(streams[n4]) || isTransformStream(streams[n4]))) {
          throw new ERR_INVALID_ARG_VALUE(`streams[${n4}]`, orgStreams[n4], "must be readable");
        }
        if (n4 > 0 && !(isWritable(streams[n4]) || isWritableStream(streams[n4]) || isTransformStream(streams[n4]))) {
          throw new ERR_INVALID_ARG_VALUE(`streams[${n4}]`, orgStreams[n4], "must be writable");
        }
      }
      let ondrain;
      let onfinish;
      let onreadable;
      let onclose;
      let d3;
      function onfinished(err) {
        const cb = onclose;
        onclose = null;
        if (cb) {
          cb(err);
        } else if (err) {
          d3.destroy(err);
        } else if (!readable && !writable) {
          d3.destroy();
        }
      }
      const head = streams[0];
      const tail = pipeline(streams, onfinished);
      const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head));
      const readable = !!(isReadable(tail) || isReadableStream2(tail) || isTransformStream(tail));
      d3 = new Duplex({
        // TODO (ronag): highWaterMark?
        writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode),
        readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode),
        writable,
        readable
      });
      if (writable) {
        if (isNodeStream(head)) {
          d3._write = function(chunk, encoding, callback) {
            if (head.write(chunk, encoding)) {
              callback();
            } else {
              ondrain = callback;
            }
          };
          d3._final = function(callback) {
            head.end();
            onfinish = callback;
          };
          head.on("drain", function() {
            if (ondrain) {
              const cb = ondrain;
              ondrain = null;
              cb();
            }
          });
        } else if (isWebStream(head)) {
          const writable2 = isTransformStream(head) ? head.writable : head;
          const writer = writable2.getWriter();
          d3._write = async function(chunk, encoding, callback) {
            try {
              await writer.ready;
              writer.write(chunk).catch(() => {
              });
              callback();
            } catch (err) {
              callback(err);
            }
          };
          d3._final = async function(callback) {
            try {
              await writer.ready;
              writer.close().catch(() => {
              });
              onfinish = callback;
            } catch (err) {
              callback(err);
            }
          };
        }
        const toRead = isTransformStream(tail) ? tail.readable : tail;
        eos2(toRead, () => {
          if (onfinish) {
            const cb = onfinish;
            onfinish = null;
            cb();
          }
        });
      }
      if (readable) {
        if (isNodeStream(tail)) {
          tail.on("readable", function() {
            if (onreadable) {
              const cb = onreadable;
              onreadable = null;
              cb();
            }
          });
          tail.on("end", function() {
            d3.push(null);
          });
          d3._read = function() {
            while (true) {
              const buf = tail.read();
              if (buf === null) {
                onreadable = d3._read;
                return;
              }
              if (!d3.push(buf)) {
                return;
              }
            }
          };
        } else if (isWebStream(tail)) {
          const readable2 = isTransformStream(tail) ? tail.readable : tail;
          const reader = readable2.getReader();
          d3._read = async function() {
            while (true) {
              try {
                const { value, done } = await reader.read();
                if (!d3.push(value)) {
                  return;
                }
                if (done) {
                  d3.push(null);
                  return;
                }
              } catch {
                return;
              }
            }
          };
        }
      }
      d3._destroy = function(err, callback) {
        if (!err && onclose !== null) {
          err = new AbortError();
        }
        onreadable = null;
        ondrain = null;
        onfinish = null;
        if (onclose === null) {
          callback(err);
        } else {
          onclose = callback;
          if (isNodeStream(tail)) {
            destroyer(tail, err);
          }
        }
      };
      return d3;
    };
  }
});

// node_modules/readable-stream/lib/internal/streams/operators.js
var require_operators = __commonJS({
  "node_modules/readable-stream/lib/internal/streams/operators.js"(exports, module2) {
    "use strict";
    var AbortController2 = globalThis.AbortController || require_browser().AbortController;
    var {
      codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },
      AbortError
    } = require_errors3();
    var { validateAbortSignal, validateInteger, validateObject } = require_validators();
    var kWeakHandler = require_primordials().Symbol("kWeak");
    var kResistStopPropagation = require_primordials().Symbol("kResistStopPropagation");
    var { finished } = require_end_of_stream();
    var staticCompose = require_compose();
    var { addAbortSignalNoValidate } = require_add_abort_signal();
    var { isWritable, isNodeStream } = require_utils();
    var { deprecate } = require_util3();
    var {
      ArrayPrototypePush,
      Boolean: Boolean2,
      MathFloor,
      Number: Number2,
      NumberIsNaN,
      Promise: Promise2,
      PromiseReject,
      PromiseResolve,
      PromisePrototypeThen,
      Symbol: Symbol2
    } = require_primordials();
    var kEmpty = Symbol2("kEmpty");
    var kEof = Symbol2("kEof");
    function compose(stream, options) {
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      if (isNodeStream(stream) && !isWritable(stream)) {
        throw new ERR_INVALID_ARG_VALUE("stream", stream, "must be writable");
      }
      const composedStream = staticCompose(this, stream);
      if (options !== null && options !== void 0 && options.signal) {
        addAbortSignalNoValidate(options.signal, composedStream);
      }
      return composedStream;
    }
    function map(fn, options) {
      if (typeof fn !== "function") {
        throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
      }
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      let concurrency = 1;
      if ((options === null || options === void 0 ? void 0 : options.concurrency) != null) {
        concurrency = MathFloor(options.concurrency);
      }
      let highWaterMark = concurrency - 1;
      if ((options === null || options === void 0 ? void 0 : options.highWaterMark) != null) {
        highWaterMark = MathFloor(options.highWaterMark);
      }
      validateInteger(concurrency, "options.concurrency", 1);
      validateInteger(highWaterMark, "options.highWaterMark", 0);
      highWaterMark += concurrency;
      return async function* map2() {
        const signal = require_util3().AbortSignalAny(
          [options === null || options === void 0 ? void 0 : options.signal].filter(Boolean2)
        );
        const stream = this;
        const queue2 = [];
        const signalOpt = {
          signal
        };
        let next;
        let resume;
        let done = false;
        let cnt = 0;
        function onCatch() {
          done = true;
          afterItemProcessed();
        }
        function afterItemProcessed() {
          cnt -= 1;
          maybeResume();
        }
        function maybeResume() {
          if (resume && !done && cnt < concurrency && queue2.length < highWaterMark) {
            resume();
            resume = null;
          }
        }
        async function pump() {
          try {
            for await (let val2 of stream) {
              if (done) {
                return;
              }
              if (signal.aborted) {
                throw new AbortError();
              }
              try {
                val2 = fn(val2, signalOpt);
                if (val2 === kEmpty) {
                  continue;
                }
                val2 = PromiseResolve(val2);
              } catch (err) {
                val2 = PromiseReject(err);
              }
              cnt += 1;
              PromisePrototypeThen(val2, afterItemProcessed, onCatch);
              queue2.push(val2);
              if (next) {
                next();
                next = null;
              }
              if (!done && (queue2.length >= highWaterMark || cnt >= concurrency)) {
                await new Promise2((resolve) => {
                  resume = resolve;
                });
              }
            }
            queue2.push(kEof);
          } catch (err) {
            const val2 = PromiseReject(err);
            PromisePrototypeThen(val2, afterItemProcessed, onCatch);
            queue2.push(val2);
          } finally {
            done = true;
            if (next) {
              next();
              next = null;
            }
          }
        }
        pump();
        try {
          while (true) {
            while (queue2.length > 0) {
              const val2 = await queue2[0];
              if (val2 === kEof) {
                return;
              }
              if (signal.aborted) {
                throw new AbortError();
              }
              if (val2 !== kEmpty) {
                yield val2;
              }
              queue2.shift();
              maybeResume();
            }
            await new Promise2((resolve) => {
              next = resolve;
            });
          }
        } finally {
          done = true;
          if (resume) {
            resume();
            resume = null;
          }
        }
      }.call(this);
    }
    function asIndexedPairs(options = void 0) {
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      return async function* asIndexedPairs2() {
        let index2 = 0;
        for await (const val2 of this) {
          var _options$signal;
          if (options !== null && options !== void 0 && (_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) {
            throw new AbortError({
              cause: options.signal.reason
            });
          }
          yield [index2++, val2];
        }
      }.call(this);
    }
    async function some(fn, options = void 0) {
      for await (const unused of filter2.call(this, fn, options)) {
        return true;
      }
      return false;
    }
    async function every(fn, options = void 0) {
      if (typeof fn !== "function") {
        throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
      }
      return !await some.call(
        this,
        async (...args) => {
          return !await fn(...args);
        },
        options
      );
    }
    async function find3(fn, options) {
      for await (const result of filter2.call(this, fn, options)) {
        return result;
      }
      return void 0;
    }
    async function forEach(fn, options) {
      if (typeof fn !== "function") {
        throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
      }
      async function forEachFn(value, options2) {
        await fn(value, options2);
        return kEmpty;
      }
      for await (const unused of map.call(this, forEachFn, options))
        ;
    }
    function filter2(fn, options) {
      if (typeof fn !== "function") {
        throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
      }
      async function filterFn(value, options2) {
        if (await fn(value, options2)) {
          return value;
        }
        return kEmpty;
      }
      return map.call(this, filterFn, options);
    }
    var ReduceAwareErrMissingArgs = class extends ERR_MISSING_ARGS {
      constructor() {
        super("reduce");
        this.message = "Reduce of an empty stream requires an initial value";
      }
    };
    async function reduce(reducer2, initialValue, options) {
      var _options$signal2;
      if (typeof reducer2 !== "function") {
        throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer2);
      }
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      let hasInitialValue2 = arguments.length > 1;
      if (options !== null && options !== void 0 && (_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) {
        const err = new AbortError(void 0, {
          cause: options.signal.reason
        });
        this.once("error", () => {
        });
        await finished(this.destroy(err));
        throw err;
      }
      const ac = new AbortController2();
      const signal = ac.signal;
      if (options !== null && options !== void 0 && options.signal) {
        const opts = {
          once: true,
          [kWeakHandler]: this,
          [kResistStopPropagation]: true
        };
        options.signal.addEventListener("abort", () => ac.abort(), opts);
      }
      let gotAnyItemFromStream = false;
      try {
        for await (const value of this) {
          var _options$signal3;
          gotAnyItemFromStream = true;
          if (options !== null && options !== void 0 && (_options$signal3 = options.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) {
            throw new AbortError();
          }
          if (!hasInitialValue2) {
            initialValue = value;
            hasInitialValue2 = true;
          } else {
            initialValue = await reducer2(initialValue, value, {
              signal
            });
          }
        }
        if (!gotAnyItemFromStream && !hasInitialValue2) {
          throw new ReduceAwareErrMissingArgs();
        }
      } finally {
        ac.abort();
      }
      return initialValue;
    }
    async function toArray2(options) {
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      const result = [];
      for await (const val2 of this) {
        var _options$signal4;
        if (options !== null && options !== void 0 && (_options$signal4 = options.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) {
          throw new AbortError(void 0, {
            cause: options.signal.reason
          });
        }
        ArrayPrototypePush(result, val2);
      }
      return result;
    }
    function flatMap(fn, options) {
      const values = map.call(this, fn, options);
      return async function* flatMap2() {
        for await (const val2 of values) {
          yield* val2;
        }
      }.call(this);
    }
    function toIntegerOrInfinity(number) {
      number = Number2(number);
      if (NumberIsNaN(number)) {
        return 0;
      }
      if (number < 0) {
        throw new ERR_OUT_OF_RANGE("number", ">= 0", number);
      }
      return number;
    }
    function drop(number, options = void 0) {
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      number = toIntegerOrInfinity(number);
      return async function* drop2() {
        var _options$signal5;
        if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) {
          throw new AbortError();
        }
        for await (const val2 of this) {
          var _options$signal6;
          if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) {
            throw new AbortError();
          }
          if (number-- <= 0) {
            yield val2;
          }
        }
      }.call(this);
    }
    function take2(number, options = void 0) {
      if (options != null) {
        validateObject(options, "options");
      }
      if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
        validateAbortSignal(options.signal, "options.signal");
      }
      number = toIntegerOrInfinity(number);
      return async function* take3() {
        var _options$signal7;
        if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) {
          throw new AbortError();
        }
        for await (const val2 of this) {
          var _options$signal8;
          if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) {
            throw new AbortError();
          }
          if (number-- > 0) {
            yield val2;
          }
          if (number <= 0) {
            return;
          }
        }
      }.call(this);
    }
    module2.exports.streamReturningOperators = {
      asIndexedPairs: deprecate(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."),
      drop,
      filter: filter2,
      flatMap,
      map,
      take: take2,
      compose
    };
    module2.exports.promiseReturningOperators = {
      every,
      forEach,
      reduce,
      toArray: toArray2,
      some,
      find: find3
    };
  }
});

// node_modules/readable-stream/lib/stream/promises.js
var require_promises = __commonJS({
  "node_modules/readable-stream/lib/stream/promises.js"(exports, module2) {
    "use strict";
    var { ArrayPrototypePop, Promise: Promise2 } = require_primordials();
    var { isIterable, isNodeStream, isWebStream } = require_utils();
    var { pipelineImpl: pl } = require_pipeline();
    var { finished } = require_end_of_stream();
    require_stream2();
    function pipeline(...streams) {
      return new Promise2((resolve, reject) => {
        let signal;
        let end;
        const lastArg = streams[streams.length - 1];
        if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) {
          const options = ArrayPrototypePop(streams);
          signal = options.signal;
          end = options.end;
        }
        pl(
          streams,
          (err, value) => {
            if (err) {
              reject(err);
            } else {
              resolve(value);
            }
          },
          {
            signal,
            end
          }
        );
      });
    }
    module2.exports = {
      finished,
      pipeline
    };
  }
});

// node_modules/readable-stream/lib/stream.js
var require_stream2 = __commonJS({
  "node_modules/readable-stream/lib/stream.js"(exports, module2) {
    var { Buffer: Buffer2 } = require_buffer();
    var { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials();
    var {
      promisify: { custom: customPromisify }
    } = require_util3();
    var { streamReturningOperators, promiseReturningOperators } = require_operators();
    var {
      codes: { ERR_ILLEGAL_CONSTRUCTOR }
    } = require_errors3();
    var compose = require_compose();
    var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state();
    var { pipeline } = require_pipeline();
    var { destroyer } = require_destroy();
    var eos2 = require_end_of_stream();
    var promises = require_promises();
    var utils = require_utils();
    var Stream4 = module2.exports = require_legacy().Stream;
    Stream4.isDestroyed = utils.isDestroyed;
    Stream4.isDisturbed = utils.isDisturbed;
    Stream4.isErrored = utils.isErrored;
    Stream4.isReadable = utils.isReadable;
    Stream4.isWritable = utils.isWritable;
    Stream4.Readable = require_readable();
    for (const key of ObjectKeys(streamReturningOperators)) {
      let fn2 = function(...args) {
        if (new.target) {
          throw ERR_ILLEGAL_CONSTRUCTOR();
        }
        return Stream4.Readable.from(ReflectApply(op, this, args));
      };
      fn = fn2;
      const op = streamReturningOperators[key];
      ObjectDefineProperty(fn2, "name", {
        __proto__: null,
        value: op.name
      });
      ObjectDefineProperty(fn2, "length", {
        __proto__: null,
        value: op.length
      });
      ObjectDefineProperty(Stream4.Readable.prototype, key, {
        __proto__: null,
        value: fn2,
        enumerable: false,
        configurable: true,
        writable: true
      });
    }
    var fn;
    for (const key of ObjectKeys(promiseReturningOperators)) {
      let fn2 = function(...args) {
        if (new.target) {
          throw ERR_ILLEGAL_CONSTRUCTOR();
        }
        return ReflectApply(op, this, args);
      };
      fn = fn2;
      const op = promiseReturningOperators[key];
      ObjectDefineProperty(fn2, "name", {
        __proto__: null,
        value: op.name
      });
      ObjectDefineProperty(fn2, "length", {
        __proto__: null,
        value: op.length
      });
      ObjectDefineProperty(Stream4.Readable.prototype, key, {
        __proto__: null,
        value: fn2,
        enumerable: false,
        configurable: true,
        writable: true
      });
    }
    var fn;
    Stream4.Writable = require_writable();
    Stream4.Duplex = require_duplex();
    Stream4.Transform = require_transform();
    Stream4.PassThrough = require_passthrough();
    Stream4.pipeline = pipeline;
    var { addAbortSignal } = require_add_abort_signal();
    Stream4.addAbortSignal = addAbortSignal;
    Stream4.finished = eos2;
    Stream4.destroy = destroyer;
    Stream4.compose = compose;
    Stream4.setDefaultHighWaterMark = setDefaultHighWaterMark;
    Stream4.getDefaultHighWaterMark = getDefaultHighWaterMark;
    ObjectDefineProperty(Stream4, "promises", {
      __proto__: null,
      configurable: true,
      enumerable: true,
      get() {
        return promises;
      }
    });
    ObjectDefineProperty(pipeline, customPromisify, {
      __proto__: null,
      enumerable: true,
      get() {
        return promises.pipeline;
      }
    });
    ObjectDefineProperty(eos2, customPromisify, {
      __proto__: null,
      enumerable: true,
      get() {
        return promises.finished;
      }
    });
    Stream4.Stream = Stream4;
    Stream4._isUint8Array = function isUint8Array(value) {
      return value instanceof Uint8Array;
    };
    Stream4._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {
      return Buffer2.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
    };
  }
});

// node_modules/readable-stream/lib/ours/browser.js
var require_browser3 = __commonJS({
  "node_modules/readable-stream/lib/ours/browser.js"(exports, module2) {
    "use strict";
    var CustomStream = require_stream2();
    var promises = require_promises();
    var originalDestroy = CustomStream.Readable.destroy;
    module2.exports = CustomStream.Readable;
    module2.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer;
    module2.exports._isUint8Array = CustomStream._isUint8Array;
    module2.exports.isDisturbed = CustomStream.isDisturbed;
    module2.exports.isErrored = CustomStream.isErrored;
    module2.exports.isReadable = CustomStream.isReadable;
    module2.exports.Readable = CustomStream.Readable;
    module2.exports.Writable = CustomStream.Writable;
    module2.exports.Duplex = CustomStream.Duplex;
    module2.exports.Transform = CustomStream.Transform;
    module2.exports.PassThrough = CustomStream.PassThrough;
    module2.exports.addAbortSignal = CustomStream.addAbortSignal;
    module2.exports.finished = CustomStream.finished;
    module2.exports.destroy = CustomStream.destroy;
    module2.exports.destroy = originalDestroy;
    module2.exports.pipeline = CustomStream.pipeline;
    module2.exports.compose = CustomStream.compose;
    Object.defineProperty(CustomStream, "promises", {
      configurable: true,
      enumerable: true,
      get() {
        return promises;
      }
    });
    module2.exports.Stream = CustomStream.Stream;
    module2.exports.default = module2.exports;
  }
});

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

// (disabled):node_modules/object-inspect/util.inspect
var require_util4 = __commonJS({
  "(disabled):node_modules/object-inspect/util.inspect"() {
  }
});

// node_modules/object-inspect/index.js
var require_object_inspect = __commonJS({
  "node_modules/object-inspect/index.js"(exports, module2) {
    var hasMap = typeof Map === "function" && Map.prototype;
    var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
    var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
    var mapForEach = hasMap && Map.prototype.forEach;
    var hasSet = typeof Set === "function" && Set.prototype;
    var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
    var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
    var setForEach = hasSet && Set.prototype.forEach;
    var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
    var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
    var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
    var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
    var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
    var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
    var booleanValueOf = Boolean.prototype.valueOf;
    var objectToString2 = Object.prototype.toString;
    var functionToString = Function.prototype.toString;
    var $match = String.prototype.match;
    var $slice = String.prototype.slice;
    var $replace = String.prototype.replace;
    var $toUpperCase = String.prototype.toUpperCase;
    var $toLowerCase = String.prototype.toLowerCase;
    var $test = RegExp.prototype.test;
    var $concat = Array.prototype.concat;
    var $join = Array.prototype.join;
    var $arrSlice = Array.prototype.slice;
    var $floor = Math.floor;
    var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
    var gOPS = Object.getOwnPropertySymbols;
    var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
    var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
    var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
    var isEnumerable = Object.prototype.propertyIsEnumerable;
    var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
      return O.__proto__;
    } : null);
    function addNumericSeparator(num, str2) {
      if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str2)) {
        return str2;
      }
      var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
      if (typeof num === "number") {
        var int2 = num < 0 ? -$floor(-num) : $floor(num);
        if (int2 !== num) {
          var intStr = String(int2);
          var dec = $slice.call(str2, intStr.length + 1);
          return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
        }
      }
      return $replace.call(str2, sepRegex, "$&_");
    }
    var utilInspect = require_util4();
    var inspectCustom = utilInspect.custom;
    var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
    var quotes = {
      __proto__: null,
      "double": '"',
      single: "'"
    };
    var quoteREs = {
      __proto__: null,
      "double": /(["\\])/g,
      single: /(['\\])/g
    };
    module2.exports = function inspect_(obj, options, depth, seen) {
      var opts = options || {};
      if (has2(opts, "quoteStyle") && !has2(quotes, opts.quoteStyle)) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
      }
      if (has2(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
      }
      var customInspect = has2(opts, "customInspect") ? opts.customInspect : true;
      if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
        throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
      }
      if (has2(opts, "indent") && opts.indent !== null && opts.indent !== "	" && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
      }
      if (has2(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
      }
      var numericSeparator = opts.numericSeparator;
      if (typeof obj === "undefined") {
        return "undefined";
      }
      if (obj === null) {
        return "null";
      }
      if (typeof obj === "boolean") {
        return obj ? "true" : "false";
      }
      if (typeof obj === "string") {
        return inspectString(obj, opts);
      }
      if (typeof obj === "number") {
        if (obj === 0) {
          return Infinity / obj > 0 ? "0" : "-0";
        }
        var str2 = String(obj);
        return numericSeparator ? addNumericSeparator(obj, str2) : str2;
      }
      if (typeof obj === "bigint") {
        var bigIntStr = String(obj) + "n";
        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
      }
      var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
      if (typeof depth === "undefined") {
        depth = 0;
      }
      if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
        return isArray2(obj) ? "[Array]" : "[Object]";
      }
      var indent = getIndent(opts, depth);
      if (typeof seen === "undefined") {
        seen = [];
      } else if (indexOf(seen, obj) >= 0) {
        return "[Circular]";
      }
      function inspect(value, from, noIndent) {
        if (from) {
          seen = $arrSlice.call(seen);
          seen.push(from);
        }
        if (noIndent) {
          var newOpts = {
            depth: opts.depth
          };
          if (has2(opts, "quoteStyle")) {
            newOpts.quoteStyle = opts.quoteStyle;
          }
          return inspect_(value, newOpts, depth + 1, seen);
        }
        return inspect_(value, opts, depth + 1, seen);
      }
      if (typeof obj === "function" && !isRegExp(obj)) {
        var name = nameOf(obj);
        var keys = arrObjKeys(obj, inspect);
        return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : "");
      }
      if (isSymbol(obj)) {
        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
        return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
      }
      if (isElement2(obj)) {
        var s4 = "<" + $toLowerCase.call(String(obj.nodeName));
        var attrs = obj.attributes || [];
        for (var i3 = 0; i3 < attrs.length; i3++) {
          s4 += " " + attrs[i3].name + "=" + wrapQuotes(quote(attrs[i3].value), "double", opts);
        }
        s4 += ">";
        if (obj.childNodes && obj.childNodes.length) {
          s4 += "...";
        }
        s4 += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
        return s4;
      }
      if (isArray2(obj)) {
        if (obj.length === 0) {
          return "[]";
        }
        var xs = arrObjKeys(obj, inspect);
        if (indent && !singleLineValues(xs)) {
          return "[" + indentedJoin(xs, indent) + "]";
        }
        return "[ " + $join.call(xs, ", ") + " ]";
      }
      if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
          return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }";
        }
        if (parts.length === 0) {
          return "[" + String(obj) + "]";
        }
        return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
      }
      if (typeof obj === "object" && customInspect) {
        if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
          return utilInspect(obj, { depth: maxDepth - depth });
        } else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
          return obj.inspect();
        }
      }
      if (isMap(obj)) {
        var mapParts = [];
        if (mapForEach) {
          mapForEach.call(obj, function(value, key) {
            mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj));
          });
        }
        return collectionOf("Map", mapSize.call(obj), mapParts, indent);
      }
      if (isSet2(obj)) {
        var setParts = [];
        if (setForEach) {
          setForEach.call(obj, function(value) {
            setParts.push(inspect(value, obj));
          });
        }
        return collectionOf("Set", setSize.call(obj), setParts, indent);
      }
      if (isWeakMap(obj)) {
        return weakCollectionOf("WeakMap");
      }
      if (isWeakSet(obj)) {
        return weakCollectionOf("WeakSet");
      }
      if (isWeakRef(obj)) {
        return weakCollectionOf("WeakRef");
      }
      if (isNumber3(obj)) {
        return markBoxed(inspect(Number(obj)));
      }
      if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
      }
      if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
      }
      if (isString2(obj)) {
        return markBoxed(inspect(String(obj)));
      }
      if (typeof window !== "undefined" && obj === window) {
        return "{ [object Window] }";
      }
      if (typeof globalThis !== "undefined" && obj === globalThis || typeof window !== "undefined" && obj === window) {
        return "{ [object globalThis] }";
      }
      if (!isDate2(obj) && !isRegExp(obj)) {
        var ys = arrObjKeys(obj, inspect);
        var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
        var protoTag = obj instanceof Object ? "" : "null prototype";
        var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
        var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
        var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
        if (ys.length === 0) {
          return tag + "{}";
        }
        if (indent) {
          return tag + "{" + indentedJoin(ys, indent) + "}";
        }
        return tag + "{ " + $join.call(ys, ", ") + " }";
      }
      return String(obj);
    };
    function wrapQuotes(s4, defaultStyle, opts) {
      var style = opts.quoteStyle || defaultStyle;
      var quoteChar = quotes[style];
      return quoteChar + s4 + quoteChar;
    }
    function quote(s4) {
      return $replace.call(String(s4), /"/g, "&quot;");
    }
    function isArray2(obj) {
      return toStr(obj) === "[object Array]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isDate2(obj) {
      return toStr(obj) === "[object Date]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isRegExp(obj) {
      return toStr(obj) === "[object RegExp]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isError(obj) {
      return toStr(obj) === "[object Error]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isString2(obj) {
      return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isNumber3(obj) {
      return toStr(obj) === "[object Number]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isBoolean(obj) {
      return toStr(obj) === "[object Boolean]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
    }
    function isSymbol(obj) {
      if (hasShammedSymbols) {
        return obj && typeof obj === "object" && obj instanceof Symbol;
      }
      if (typeof obj === "symbol") {
        return true;
      }
      if (!obj || typeof obj !== "object" || !symToString) {
        return false;
      }
      try {
        symToString.call(obj);
        return true;
      } catch (e3) {
      }
      return false;
    }
    function isBigInt(obj) {
      if (!obj || typeof obj !== "object" || !bigIntValueOf) {
        return false;
      }
      try {
        bigIntValueOf.call(obj);
        return true;
      } catch (e3) {
      }
      return false;
    }
    var hasOwn4 = Object.prototype.hasOwnProperty || function(key) {
      return key in this;
    };
    function has2(obj, key) {
      return hasOwn4.call(obj, key);
    }
    function toStr(obj) {
      return objectToString2.call(obj);
    }
    function nameOf(f3) {
      if (f3.name) {
        return f3.name;
      }
      var m3 = $match.call(functionToString.call(f3), /^function\s*([\w$]+)/);
      if (m3) {
        return m3[1];
      }
      return null;
    }
    function indexOf(xs, x2) {
      if (xs.indexOf) {
        return xs.indexOf(x2);
      }
      for (var i3 = 0, l4 = xs.length; i3 < l4; i3++) {
        if (xs[i3] === x2) {
          return i3;
        }
      }
      return -1;
    }
    function isMap(x2) {
      if (!mapSize || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        mapSize.call(x2);
        try {
          setSize.call(x2);
        } catch (s4) {
          return true;
        }
        return x2 instanceof Map;
      } catch (e3) {
      }
      return false;
    }
    function isWeakMap(x2) {
      if (!weakMapHas || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakMapHas.call(x2, weakMapHas);
        try {
          weakSetHas.call(x2, weakSetHas);
        } catch (s4) {
          return true;
        }
        return x2 instanceof WeakMap;
      } catch (e3) {
      }
      return false;
    }
    function isWeakRef(x2) {
      if (!weakRefDeref || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakRefDeref.call(x2);
        return true;
      } catch (e3) {
      }
      return false;
    }
    function isSet2(x2) {
      if (!setSize || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        setSize.call(x2);
        try {
          mapSize.call(x2);
        } catch (m3) {
          return true;
        }
        return x2 instanceof Set;
      } catch (e3) {
      }
      return false;
    }
    function isWeakSet(x2) {
      if (!weakSetHas || !x2 || typeof x2 !== "object") {
        return false;
      }
      try {
        weakSetHas.call(x2, weakSetHas);
        try {
          weakMapHas.call(x2, weakMapHas);
        } catch (s4) {
          return true;
        }
        return x2 instanceof WeakSet;
      } catch (e3) {
      }
      return false;
    }
    function isElement2(x2) {
      if (!x2 || typeof x2 !== "object") {
        return false;
      }
      if (typeof HTMLElement !== "undefined" && x2 instanceof HTMLElement) {
        return true;
      }
      return typeof x2.nodeName === "string" && typeof x2.getAttribute === "function";
    }
    function inspectString(str2, opts) {
      if (str2.length > opts.maxStringLength) {
        var remaining = str2.length - opts.maxStringLength;
        var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
        return inspectString($slice.call(str2, 0, opts.maxStringLength), opts) + trailer;
      }
      var quoteRE = quoteREs[opts.quoteStyle || "single"];
      quoteRE.lastIndex = 0;
      var s4 = $replace.call($replace.call(str2, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte);
      return wrapQuotes(s4, "single", opts);
    }
    function lowbyte(c4) {
      var n4 = c4.charCodeAt(0);
      var x2 = {
        8: "b",
        9: "t",
        10: "n",
        12: "f",
        13: "r"
      }[n4];
      if (x2) {
        return "\\" + x2;
      }
      return "\\x" + (n4 < 16 ? "0" : "") + $toUpperCase.call(n4.toString(16));
    }
    function markBoxed(str2) {
      return "Object(" + str2 + ")";
    }
    function weakCollectionOf(type) {
      return type + " { ? }";
    }
    function collectionOf(type, size4, entries, indent) {
      var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
      return type + " (" + size4 + ") {" + joinedEntries + "}";
    }
    function singleLineValues(xs) {
      for (var i3 = 0; i3 < xs.length; i3++) {
        if (indexOf(xs[i3], "\n") >= 0) {
          return false;
        }
      }
      return true;
    }
    function getIndent(opts, depth) {
      var baseIndent;
      if (opts.indent === "	") {
        baseIndent = "	";
      } else if (typeof opts.indent === "number" && opts.indent > 0) {
        baseIndent = $join.call(Array(opts.indent + 1), " ");
      } else {
        return null;
      }
      return {
        base: baseIndent,
        prev: $join.call(Array(depth + 1), baseIndent)
      };
    }
    function indentedJoin(xs, indent) {
      if (xs.length === 0) {
        return "";
      }
      var lineJoiner = "\n" + indent.prev + indent.base;
      return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
    }
    function arrObjKeys(obj, inspect) {
      var isArr = isArray2(obj);
      var xs = [];
      if (isArr) {
        xs.length = obj.length;
        for (var i3 = 0; i3 < obj.length; i3++) {
          xs[i3] = has2(obj, i3) ? inspect(obj[i3], obj) : "";
        }
      }
      var syms = typeof gOPS === "function" ? gOPS(obj) : [];
      var symMap;
      if (hasShammedSymbols) {
        symMap = {};
        for (var k3 = 0; k3 < syms.length; k3++) {
          symMap["$" + syms[k3]] = syms[k3];
        }
      }
      for (var key in obj) {
        if (!has2(obj, key)) {
          continue;
        }
        if (isArr && String(Number(key)) === key && key < obj.length) {
          continue;
        }
        if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
          continue;
        } else if ($test.call(/[^\w$]/, key)) {
          xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj));
        } else {
          xs.push(key + ": " + inspect(obj[key], obj));
        }
      }
      if (typeof gOPS === "function") {
        for (var j3 = 0; j3 < syms.length; j3++) {
          if (isEnumerable.call(obj, syms[j3])) {
            xs.push("[" + inspect(syms[j3]) + "]: " + inspect(obj[syms[j3]], obj));
          }
        }
      }
      return xs;
    }
  }
});

// node_modules/side-channel-list/index.js
var require_side_channel_list = __commonJS({
  "node_modules/side-channel-list/index.js"(exports, module2) {
    "use strict";
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var listGetNode = function(list, key, isDelete) {
      var prev = list;
      var curr;
      for (; (curr = prev.next) != null; prev = curr) {
        if (curr.key === key) {
          prev.next = curr.next;
          if (!isDelete) {
            curr.next = /** @type {NonNullable<typeof list.next>} */
            list.next;
            list.next = curr;
          }
          return curr;
        }
      }
    };
    var listGet = function(objects, key) {
      if (!objects) {
        return void 0;
      }
      var node = listGetNode(objects, key);
      return node && node.value;
    };
    var listSet = function(objects, key, value) {
      var node = listGetNode(objects, key);
      if (node) {
        node.value = value;
      } else {
        objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
        {
          // eslint-disable-line no-param-reassign, no-extra-parens
          key,
          next: objects.next,
          value
        };
      }
    };
    var listHas = function(objects, key) {
      if (!objects) {
        return false;
      }
      return !!listGetNode(objects, key);
    };
    var listDelete = function(objects, key) {
      if (objects) {
        return listGetNode(objects, key, true);
      }
    };
    module2.exports = function getSideChannelList() {
      var $o;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          var root2 = $o && $o.next;
          var deletedNode = listDelete($o, key);
          if (deletedNode && root2 && root2 === deletedNode) {
            $o = void 0;
          }
          return !!deletedNode;
        },
        get: function(key) {
          return listGet($o, key);
        },
        has: function(key) {
          return listHas($o, key);
        },
        set: function(key, value) {
          if (!$o) {
            $o = {
              next: void 0
            };
          }
          listSet(
            /** @type {NonNullable<typeof $o>} */
            $o,
            key,
            value
          );
        }
      };
      return channel;
    };
  }
});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// node_modules/side-channel-map/index.js
var require_side_channel_map = __commonJS({
  "node_modules/side-channel-map/index.js"(exports, module2) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var $TypeError = require_type();
    var $Map = GetIntrinsic("%Map%", true);
    var $mapGet = callBound("Map.prototype.get", true);
    var $mapSet = callBound("Map.prototype.set", true);
    var $mapHas = callBound("Map.prototype.has", true);
    var $mapDelete = callBound("Map.prototype.delete", true);
    var $mapSize = callBound("Map.prototype.size", true);
    module2.exports = !!$Map && /** @type {Exclude<import('.'), false>} */
    function getSideChannelMap() {
      var $m;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          if ($m) {
            var result = $mapDelete($m, key);
            if ($mapSize($m) === 0) {
              $m = void 0;
            }
            return result;
          }
          return false;
        },
        get: function(key) {
          if ($m) {
            return $mapGet($m, key);
          }
        },
        has: function(key) {
          if ($m) {
            return $mapHas($m, key);
          }
          return false;
        },
        set: function(key, value) {
          if (!$m) {
            $m = new $Map();
          }
          $mapSet($m, key, value);
        }
      };
      return channel;
    };
  }
});

// node_modules/side-channel-weakmap/index.js
var require_side_channel_weakmap = __commonJS({
  "node_modules/side-channel-weakmap/index.js"(exports, module2) {
    "use strict";
    var GetIntrinsic = require_get_intrinsic();
    var callBound = require_call_bound();
    var inspect = require_object_inspect();
    var getSideChannelMap = require_side_channel_map();
    var $TypeError = require_type();
    var $WeakMap = GetIntrinsic("%WeakMap%", true);
    var $weakMapGet = callBound("WeakMap.prototype.get", true);
    var $weakMapSet = callBound("WeakMap.prototype.set", true);
    var $weakMapHas = callBound("WeakMap.prototype.has", true);
    var $weakMapDelete = callBound("WeakMap.prototype.delete", true);
    module2.exports = $WeakMap ? (
      /** @type {Exclude<import('.'), false>} */
      function getSideChannelWeakMap() {
        var $wm;
        var $m;
        var channel = {
          assert: function(key) {
            if (!channel.has(key)) {
              throw new $TypeError("Side channel does not contain " + inspect(key));
            }
          },
          "delete": function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapDelete($wm, key);
              }
            } else if (getSideChannelMap) {
              if ($m) {
                return $m["delete"](key);
              }
            }
            return false;
          },
          get: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapGet($wm, key);
              }
            }
            return $m && $m.get(key);
          },
          has: function(key) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if ($wm) {
                return $weakMapHas($wm, key);
              }
            }
            return !!$m && $m.has(key);
          },
          set: function(key, value) {
            if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
              if (!$wm) {
                $wm = new $WeakMap();
              }
              $weakMapSet($wm, key, value);
            } else if (getSideChannelMap) {
              if (!$m) {
                $m = getSideChannelMap();
              }
              $m.set(key, value);
            }
          }
        };
        return channel;
      }
    ) : getSideChannelMap;
  }
});

// node_modules/side-channel/index.js
var require_side_channel = __commonJS({
  "node_modules/side-channel/index.js"(exports, module2) {
    "use strict";
    var $TypeError = require_type();
    var inspect = require_object_inspect();
    var getSideChannelList = require_side_channel_list();
    var getSideChannelMap = require_side_channel_map();
    var getSideChannelWeakMap = require_side_channel_weakmap();
    var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList;
    module2.exports = function getSideChannel() {
      var $channelData;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          return !!$channelData && $channelData["delete"](key);
        },
        get: function(key) {
          return $channelData && $channelData.get(key);
        },
        has: function(key) {
          return !!$channelData && $channelData.has(key);
        },
        set: function(key, value) {
          if (!$channelData) {
            $channelData = makeChannel();
          }
          $channelData.set(key, value);
        }
      };
      return channel;
    };
  }
});

// node_modules/qs/lib/formats.js
var require_formats = __commonJS({
  "node_modules/qs/lib/formats.js"(exports, module2) {
    "use strict";
    var replace = String.prototype.replace;
    var percentTwenties = /%20/g;
    var Format = {
      RFC1738: "RFC1738",
      RFC3986: "RFC3986"
    };
    module2.exports = {
      "default": Format.RFC3986,
      formatters: {
        RFC1738: function(value) {
          return replace.call(value, percentTwenties, "+");
        },
        RFC3986: function(value) {
          return String(value);
        }
      },
      RFC1738: Format.RFC1738,
      RFC3986: Format.RFC3986
    };
  }
});

// node_modules/qs/lib/utils.js
var require_utils2 = __commonJS({
  "node_modules/qs/lib/utils.js"(exports, module2) {
    "use strict";
    var formats = require_formats();
    var has2 = Object.prototype.hasOwnProperty;
    var isArray2 = Array.isArray;
    var hexTable = function() {
      var array = [];
      for (var i3 = 0; i3 < 256; ++i3) {
        array.push("%" + ((i3 < 16 ? "0" : "") + i3.toString(16)).toUpperCase());
      }
      return array;
    }();
    var compactQueue = function compactQueue2(queue2) {
      while (queue2.length > 1) {
        var item = queue2.pop();
        var obj = item.obj[item.prop];
        if (isArray2(obj)) {
          var compacted = [];
          for (var j3 = 0; j3 < obj.length; ++j3) {
            if (typeof obj[j3] !== "undefined") {
              compacted.push(obj[j3]);
            }
          }
          item.obj[item.prop] = compacted;
        }
      }
    };
    var arrayToObject = function arrayToObject2(source, options) {
      var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      for (var i3 = 0; i3 < source.length; ++i3) {
        if (typeof source[i3] !== "undefined") {
          obj[i3] = source[i3];
        }
      }
      return obj;
    };
    var merge = function merge2(target, source, options) {
      if (!source) {
        return target;
      }
      if (typeof source !== "object") {
        if (isArray2(target)) {
          target.push(source);
        } else if (target && typeof target === "object") {
          if (options && (options.plainObjects || options.allowPrototypes) || !has2.call(Object.prototype, source)) {
            target[source] = true;
          }
        } else {
          return [target, source];
        }
        return target;
      }
      if (!target || typeof target !== "object") {
        return [target].concat(source);
      }
      var mergeTarget = target;
      if (isArray2(target) && !isArray2(source)) {
        mergeTarget = arrayToObject(target, options);
      }
      if (isArray2(target) && isArray2(source)) {
        source.forEach(function(item, i3) {
          if (has2.call(target, i3)) {
            var targetItem = target[i3];
            if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
              target[i3] = merge2(targetItem, item, options);
            } else {
              target.push(item);
            }
          } else {
            target[i3] = item;
          }
        });
        return target;
      }
      return Object.keys(source).reduce(function(acc, key) {
        var value = source[key];
        if (has2.call(acc, key)) {
          acc[key] = merge2(acc[key], value, options);
        } else {
          acc[key] = value;
        }
        return acc;
      }, mergeTarget);
    };
    var assign = function assignSingleSource(target, source) {
      return Object.keys(source).reduce(function(acc, key) {
        acc[key] = source[key];
        return acc;
      }, target);
    };
    var decode2 = function(str2, decoder, charset) {
      var strWithoutPlus = str2.replace(/\+/g, " ");
      if (charset === "iso-8859-1") {
        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
      }
      try {
        return decodeURIComponent(strWithoutPlus);
      } catch (e3) {
        return strWithoutPlus;
      }
    };
    var encode2 = function encode3(str2, defaultEncoder, charset, kind4, format) {
      if (str2.length === 0) {
        return str2;
      }
      var string = str2;
      if (typeof str2 === "symbol") {
        string = Symbol.prototype.toString.call(str2);
      } else if (typeof str2 !== "string") {
        string = String(str2);
      }
      if (charset === "iso-8859-1") {
        return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
          return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
        });
      }
      var out = "";
      for (var i3 = 0; i3 < string.length; ++i3) {
        var c4 = string.charCodeAt(i3);
        if (c4 === 45 || c4 === 46 || c4 === 95 || c4 === 126 || c4 >= 48 && c4 <= 57 || c4 >= 65 && c4 <= 90 || c4 >= 97 && c4 <= 122 || format === formats.RFC1738 && (c4 === 40 || c4 === 41)) {
          out += string.charAt(i3);
          continue;
        }
        if (c4 < 128) {
          out = out + hexTable[c4];
          continue;
        }
        if (c4 < 2048) {
          out = out + (hexTable[192 | c4 >> 6] + hexTable[128 | c4 & 63]);
          continue;
        }
        if (c4 < 55296 || c4 >= 57344) {
          out = out + (hexTable[224 | c4 >> 12] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63]);
          continue;
        }
        i3 += 1;
        c4 = 65536 + ((c4 & 1023) << 10 | string.charCodeAt(i3) & 1023);
        out += hexTable[240 | c4 >> 18] + hexTable[128 | c4 >> 12 & 63] + hexTable[128 | c4 >> 6 & 63] + hexTable[128 | c4 & 63];
      }
      return out;
    };
    var compact = function compact2(value) {
      var queue2 = [{ obj: { o: value }, prop: "o" }];
      var refs = [];
      for (var i3 = 0; i3 < queue2.length; ++i3) {
        var item = queue2[i3];
        var obj = item.obj[item.prop];
        var keys = Object.keys(obj);
        for (var j3 = 0; j3 < keys.length; ++j3) {
          var key = keys[j3];
          var val2 = obj[key];
          if (typeof val2 === "object" && val2 !== null && refs.indexOf(val2) === -1) {
            queue2.push({ obj, prop: key });
            refs.push(val2);
          }
        }
      }
      compactQueue(queue2);
      return value;
    };
    var isRegExp = function isRegExp2(obj) {
      return Object.prototype.toString.call(obj) === "[object RegExp]";
    };
    var isBuffer = function isBuffer2(obj) {
      if (!obj || typeof obj !== "object") {
        return false;
      }
      return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
    };
    var combine = function combine2(a3, b3) {
      return [].concat(a3, b3);
    };
    var maybeMap = function maybeMap2(val2, fn) {
      if (isArray2(val2)) {
        var mapped = [];
        for (var i3 = 0; i3 < val2.length; i3 += 1) {
          mapped.push(fn(val2[i3]));
        }
        return mapped;
      }
      return fn(val2);
    };
    module2.exports = {
      arrayToObject,
      assign,
      combine,
      compact,
      decode: decode2,
      encode: encode2,
      isBuffer,
      isRegExp,
      maybeMap,
      merge
    };
  }
});

// node_modules/qs/lib/stringify.js
var require_stringify = __commonJS({
  "node_modules/qs/lib/stringify.js"(exports, module2) {
    "use strict";
    var getSideChannel = require_side_channel();
    var utils = require_utils2();
    var formats = require_formats();
    var has2 = Object.prototype.hasOwnProperty;
    var arrayPrefixGenerators = {
      brackets: function brackets(prefix) {
        return prefix + "[]";
      },
      comma: "comma",
      indices: function indices(prefix, key) {
        return prefix + "[" + key + "]";
      },
      repeat: function repeat(prefix) {
        return prefix;
      }
    };
    var isArray2 = Array.isArray;
    var push3 = Array.prototype.push;
    var pushToArray = function(arr2, valueOrArray) {
      push3.apply(arr2, isArray2(valueOrArray) ? valueOrArray : [valueOrArray]);
    };
    var toISO = Date.prototype.toISOString;
    var defaultFormat = formats["default"];
    var defaults2 = {
      addQueryPrefix: false,
      allowDots: false,
      charset: "utf-8",
      charsetSentinel: false,
      delimiter: "&",
      encode: true,
      encoder: utils.encode,
      encodeValuesOnly: false,
      format: defaultFormat,
      formatter: formats.formatters[defaultFormat],
      // deprecated
      indices: false,
      serializeDate: function serializeDate(date2) {
        return toISO.call(date2);
      },
      skipNulls: false,
      strictNullHandling: false
    };
    var isNonNullishPrimitive = function isNonNullishPrimitive2(v5) {
      return typeof v5 === "string" || typeof v5 === "number" || typeof v5 === "boolean" || typeof v5 === "symbol" || typeof v5 === "bigint";
    };
    var sentinel2 = {};
    var stringify3 = function stringify4(object, prefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
      var obj = object;
      var tmpSc = sideChannel;
      var step = 0;
      var findFlag = false;
      while ((tmpSc = tmpSc.get(sentinel2)) !== void 0 && !findFlag) {
        var pos = tmpSc.get(object);
        step += 1;
        if (typeof pos !== "undefined") {
          if (pos === step) {
            throw new RangeError("Cyclic object value");
          } else {
            findFlag = true;
          }
        }
        if (typeof tmpSc.get(sentinel2) === "undefined") {
          step = 0;
        }
      }
      if (typeof filter2 === "function") {
        obj = filter2(prefix, obj);
      } else if (obj instanceof Date) {
        obj = serializeDate(obj);
      } else if (generateArrayPrefix === "comma" && isArray2(obj)) {
        obj = utils.maybeMap(obj, function(value2) {
          if (value2 instanceof Date) {
            return serializeDate(value2);
          }
          return value2;
        });
      }
      if (obj === null) {
        if (strictNullHandling) {
          return encoder && !encodeValuesOnly ? encoder(prefix, defaults2.encoder, charset, "key", format) : prefix;
        }
        obj = "";
      }
      if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
        if (encoder) {
          var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format);
          return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults2.encoder, charset, "value", format))];
        }
        return [formatter(prefix) + "=" + formatter(String(obj))];
      }
      var values = [];
      if (typeof obj === "undefined") {
        return values;
      }
      var objKeys;
      if (generateArrayPrefix === "comma" && isArray2(obj)) {
        if (encodeValuesOnly && encoder) {
          obj = utils.maybeMap(obj, encoder);
        }
        objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
      } else if (isArray2(filter2)) {
        objKeys = filter2;
      } else {
        var keys = Object.keys(obj);
        objKeys = sort ? keys.sort(sort) : keys;
      }
      var adjustedPrefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? prefix + "[]" : prefix;
      for (var j3 = 0; j3 < objKeys.length; ++j3) {
        var key = objKeys[j3];
        var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key];
        if (skipNulls && value === null) {
          continue;
        }
        var keyPrefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + key : "[" + key + "]");
        sideChannel.set(object, step);
        var valueSideChannel = getSideChannel();
        valueSideChannel.set(sentinel2, sideChannel);
        pushToArray(values, stringify4(
          value,
          keyPrefix,
          generateArrayPrefix,
          commaRoundTrip,
          strictNullHandling,
          skipNulls,
          generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder,
          filter2,
          sort,
          allowDots,
          serializeDate,
          format,
          formatter,
          encodeValuesOnly,
          charset,
          valueSideChannel
        ));
      }
      return values;
    };
    var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) {
      if (!opts) {
        return defaults2;
      }
      if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
        throw new TypeError("Encoder has to be a function.");
      }
      var charset = opts.charset || defaults2.charset;
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      var format = formats["default"];
      if (typeof opts.format !== "undefined") {
        if (!has2.call(formats.formatters, opts.format)) {
          throw new TypeError("Unknown format option provided.");
        }
        format = opts.format;
      }
      var formatter = formats.formatters[format];
      var filter2 = defaults2.filter;
      if (typeof opts.filter === "function" || isArray2(opts.filter)) {
        filter2 = opts.filter;
      }
      return {
        addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix,
        allowDots: typeof opts.allowDots === "undefined" ? defaults2.allowDots : !!opts.allowDots,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
        delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter,
        encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode,
        encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder,
        encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly,
        filter: filter2,
        format,
        formatter,
        serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate,
        skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls,
        sort: typeof opts.sort === "function" ? opts.sort : null,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
      };
    };
    module2.exports = function(object, opts) {
      var obj = object;
      var options = normalizeStringifyOptions(opts);
      var objKeys;
      var filter2;
      if (typeof options.filter === "function") {
        filter2 = options.filter;
        obj = filter2("", obj);
      } else if (isArray2(options.filter)) {
        filter2 = options.filter;
        objKeys = filter2;
      }
      var keys = [];
      if (typeof obj !== "object" || obj === null) {
        return "";
      }
      var arrayFormat;
      if (opts && opts.arrayFormat in arrayPrefixGenerators) {
        arrayFormat = opts.arrayFormat;
      } else if (opts && "indices" in opts) {
        arrayFormat = opts.indices ? "indices" : "repeat";
      } else {
        arrayFormat = "indices";
      }
      var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
      if (opts && "commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
        throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
      }
      var commaRoundTrip = generateArrayPrefix === "comma" && opts && opts.commaRoundTrip;
      if (!objKeys) {
        objKeys = Object.keys(obj);
      }
      if (options.sort) {
        objKeys.sort(options.sort);
      }
      var sideChannel = getSideChannel();
      for (var i3 = 0; i3 < objKeys.length; ++i3) {
        var key = objKeys[i3];
        if (options.skipNulls && obj[key] === null) {
          continue;
        }
        pushToArray(keys, stringify3(
          obj[key],
          key,
          generateArrayPrefix,
          commaRoundTrip,
          options.strictNullHandling,
          options.skipNulls,
          options.encode ? options.encoder : null,
          options.filter,
          options.sort,
          options.allowDots,
          options.serializeDate,
          options.format,
          options.formatter,
          options.encodeValuesOnly,
          options.charset,
          sideChannel
        ));
      }
      var joined = keys.join(options.delimiter);
      var prefix = options.addQueryPrefix === true ? "?" : "";
      if (options.charsetSentinel) {
        if (options.charset === "iso-8859-1") {
          prefix += "utf8=%26%2310003%3B&";
        } else {
          prefix += "utf8=%E2%9C%93&";
        }
      }
      return joined.length > 0 ? prefix + joined : "";
    };
  }
});

// node_modules/qs/lib/parse.js
var require_parse2 = __commonJS({
  "node_modules/qs/lib/parse.js"(exports, module2) {
    "use strict";
    var utils = require_utils2();
    var has2 = Object.prototype.hasOwnProperty;
    var isArray2 = Array.isArray;
    var defaults2 = {
      allowDots: false,
      allowPrototypes: false,
      allowSparse: false,
      arrayLimit: 20,
      charset: "utf-8",
      charsetSentinel: false,
      comma: false,
      decoder: utils.decode,
      delimiter: "&",
      depth: 5,
      ignoreQueryPrefix: false,
      interpretNumericEntities: false,
      parameterLimit: 1e3,
      parseArrays: true,
      plainObjects: false,
      strictNullHandling: false
    };
    var interpretNumericEntities = function(str2) {
      return str2.replace(/&#(\d+);/g, function($0, numberStr) {
        return String.fromCharCode(parseInt(numberStr, 10));
      });
    };
    var parseArrayValue = function(val2, options) {
      if (val2 && typeof val2 === "string" && options.comma && val2.indexOf(",") > -1) {
        return val2.split(",");
      }
      return val2;
    };
    var isoSentinel = "utf8=%26%2310003%3B";
    var charsetSentinel = "utf8=%E2%9C%93";
    var parseValues = function parseQueryStringValues(str2, options) {
      var obj = { __proto__: null };
      var cleanStr = options.ignoreQueryPrefix ? str2.replace(/^\?/, "") : str2;
      var limit2 = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
      var parts = cleanStr.split(options.delimiter, limit2);
      var skipIndex = -1;
      var i3;
      var charset = options.charset;
      if (options.charsetSentinel) {
        for (i3 = 0; i3 < parts.length; ++i3) {
          if (parts[i3].indexOf("utf8=") === 0) {
            if (parts[i3] === charsetSentinel) {
              charset = "utf-8";
            } else if (parts[i3] === isoSentinel) {
              charset = "iso-8859-1";
            }
            skipIndex = i3;
            i3 = parts.length;
          }
        }
      }
      for (i3 = 0; i3 < parts.length; ++i3) {
        if (i3 === skipIndex) {
          continue;
        }
        var part = parts[i3];
        var bracketEqualsPos = part.indexOf("]=");
        var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
        var key, val2;
        if (pos === -1) {
          key = options.decoder(part, defaults2.decoder, charset, "key");
          val2 = options.strictNullHandling ? null : "";
        } else {
          key = options.decoder(part.slice(0, pos), defaults2.decoder, charset, "key");
          val2 = utils.maybeMap(
            parseArrayValue(part.slice(pos + 1), options),
            function(encodedVal) {
              return options.decoder(encodedVal, defaults2.decoder, charset, "value");
            }
          );
        }
        if (val2 && options.interpretNumericEntities && charset === "iso-8859-1") {
          val2 = interpretNumericEntities(val2);
        }
        if (part.indexOf("[]=") > -1) {
          val2 = isArray2(val2) ? [val2] : val2;
        }
        if (has2.call(obj, key)) {
          obj[key] = utils.combine(obj[key], val2);
        } else {
          obj[key] = val2;
        }
      }
      return obj;
    };
    var parseObject = function(chain, val2, options, valuesParsed) {
      var leaf = valuesParsed ? val2 : parseArrayValue(val2, options);
      for (var i3 = chain.length - 1; i3 >= 0; --i3) {
        var obj;
        var root2 = chain[i3];
        if (root2 === "[]" && options.parseArrays) {
          obj = [].concat(leaf);
        } else {
          obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
          var cleanRoot = root2.charAt(0) === "[" && root2.charAt(root2.length - 1) === "]" ? root2.slice(1, -1) : root2;
          var index2 = parseInt(cleanRoot, 10);
          if (!options.parseArrays && cleanRoot === "") {
            obj = { 0: leaf };
          } else if (!isNaN(index2) && root2 !== cleanRoot && String(index2) === cleanRoot && index2 >= 0 && (options.parseArrays && index2 <= options.arrayLimit)) {
            obj = [];
            obj[index2] = leaf;
          } else if (cleanRoot !== "__proto__") {
            obj[cleanRoot] = leaf;
          }
        }
        leaf = obj;
      }
      return leaf;
    };
    var parseKeys = function parseQueryStringKeys(givenKey, val2, options, valuesParsed) {
      if (!givenKey) {
        return;
      }
      var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey;
      var brackets = /(\[[^[\]]*])/;
      var child = /(\[[^[\]]*])/g;
      var segment = options.depth > 0 && brackets.exec(key);
      var parent = segment ? key.slice(0, segment.index) : key;
      var keys = [];
      if (parent) {
        if (!options.plainObjects && has2.call(Object.prototype, parent)) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        keys.push(parent);
      }
      var i3 = 0;
      while (options.depth > 0 && (segment = child.exec(key)) !== null && i3 < options.depth) {
        i3 += 1;
        if (!options.plainObjects && has2.call(Object.prototype, segment[1].slice(1, -1))) {
          if (!options.allowPrototypes) {
            return;
          }
        }
        keys.push(segment[1]);
      }
      if (segment) {
        keys.push("[" + key.slice(segment.index) + "]");
      }
      return parseObject(keys, val2, options, valuesParsed);
    };
    var normalizeParseOptions = function normalizeParseOptions2(opts) {
      if (!opts) {
        return defaults2;
      }
      if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") {
        throw new TypeError("Decoder has to be a function.");
      }
      if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
        throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
      }
      var charset = typeof opts.charset === "undefined" ? defaults2.charset : opts.charset;
      return {
        allowDots: typeof opts.allowDots === "undefined" ? defaults2.allowDots : !!opts.allowDots,
        allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults2.allowPrototypes,
        allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults2.allowSparse,
        arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults2.arrayLimit,
        charset,
        charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
        comma: typeof opts.comma === "boolean" ? opts.comma : defaults2.comma,
        decoder: typeof opts.decoder === "function" ? opts.decoder : defaults2.decoder,
        delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults2.delimiter,
        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
        depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults2.depth,
        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
        interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults2.interpretNumericEntities,
        parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults2.parameterLimit,
        parseArrays: opts.parseArrays !== false,
        plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults2.plainObjects,
        strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
      };
    };
    module2.exports = function(str2, opts) {
      var options = normalizeParseOptions(opts);
      if (str2 === "" || str2 === null || typeof str2 === "undefined") {
        return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      }
      var tempObj = typeof str2 === "string" ? parseValues(str2, options) : str2;
      var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
      var keys = Object.keys(tempObj);
      for (var i3 = 0; i3 < keys.length; ++i3) {
        var key = keys[i3];
        var newObj = parseKeys(key, tempObj[key], options, typeof str2 === "string");
        obj = utils.merge(obj, newObj, options);
      }
      if (options.allowSparse === true) {
        return obj;
      }
      return utils.compact(obj);
    };
  }
});

// node_modules/qs/lib/index.js
var require_lib = __commonJS({
  "node_modules/qs/lib/index.js"(exports, module2) {
    "use strict";
    var stringify3 = require_stringify();
    var parse6 = require_parse2();
    var formats = require_formats();
    module2.exports = {
      formats,
      parse: parse6,
      stringify: stringify3
    };
  }
});

// node_modules/cohere-ai/core/fetcher/createRequestUrl.js
var require_createRequestUrl = __commonJS({
  "node_modules/cohere-ai/core/fetcher/createRequestUrl.js"(exports) {
    "use strict";
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createRequestUrl = void 0;
    var qs_1 = __importDefault5(require_lib());
    function createRequestUrl(baseUrl, queryParameters) {
      return Object.keys(queryParameters !== null && queryParameters !== void 0 ? queryParameters : {}).length > 0 ? `${baseUrl}?${qs_1.default.stringify(queryParameters, { arrayFormat: "repeat" })}` : baseUrl;
    }
    exports.createRequestUrl = createRequestUrl;
  }
});

// node_modules/cohere-ai/core/runtime/runtime.js
var require_runtime = __commonJS({
  "node_modules/cohere-ai/core/runtime/runtime.js"(exports) {
    "use strict";
    var _a5;
    var _b;
    var _c;
    var _d;
    var _e;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RUNTIME = void 0;
    var isBrowser3 = typeof window !== "undefined" && typeof window.document !== "undefined";
    var isWebWorker3 = typeof self === "object" && // @ts-ignore
    typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && (((_a5 = self.constructor) === null || _a5 === void 0 ? void 0 : _a5.name) === "DedicatedWorkerGlobalScope" || ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
    var isDeno3 = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
    var isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
    var isNode4 = typeof process !== "undefined" && Boolean(process.version) && Boolean((_d = process.versions) === null || _d === void 0 ? void 0 : _d.node) && // Deno spoofs process.versions.node, see https://deno.land/std@0.177.0/node/process.ts?s=versions
    !isDeno3 && !isBun;
    var isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
    var isCloudflare = typeof globalThis !== "undefined" && ((_e = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _e === void 0 ? void 0 : _e.userAgent) === "Cloudflare-Workers";
    exports.RUNTIME = evaluateRuntime();
    function evaluateRuntime() {
      if (isBrowser3) {
        return {
          type: "browser",
          version: window.navigator.userAgent
        };
      }
      if (isCloudflare) {
        return {
          type: "workerd"
        };
      }
      if (isWebWorker3) {
        return {
          type: "web-worker"
        };
      }
      if (isDeno3) {
        return {
          type: "deno",
          version: Deno.version.deno
        };
      }
      if (isBun) {
        return {
          type: "bun",
          version: Bun.version
        };
      }
      if (isNode4) {
        return {
          type: "node",
          version: process.versions.node,
          parsedVersion: Number(process.versions.node.split(".")[0])
        };
      }
      if (isReactNative) {
        return {
          type: "react-native"
        };
      }
      return {
        type: "unknown"
      };
    }
  }
});

// node_modules/cohere-ai/core/runtime/index.js
var require_runtime2 = __commonJS({
  "node_modules/cohere-ai/core/runtime/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RUNTIME = void 0;
    var runtime_1 = require_runtime();
    Object.defineProperty(exports, "RUNTIME", { enumerable: true, get: function() {
      return runtime_1.RUNTIME;
    } });
  }
});

// node_modules/node-fetch/browser.js
var require_browser4 = __commonJS({
  "node_modules/node-fetch/browser.js"(exports, module2) {
    "use strict";
    var getGlobal = function() {
      if (typeof self !== "undefined") {
        return self;
      }
      if (typeof window !== "undefined") {
        return window;
      }
      if (typeof window !== "undefined") {
        return window;
      }
      throw new Error("unable to locate global object");
    };
    var globalObject = getGlobal();
    module2.exports = exports = globalObject.fetch;
    if (globalObject.fetch) {
      exports.default = globalObject.fetch.bind(globalObject);
    }
    exports.Headers = globalObject.Headers;
    exports.Request = globalObject.Request;
    exports.Response = globalObject.Response;
  }
});

// node_modules/cohere-ai/core/fetcher/getFetchFn.js
var require_getFetchFn = __commonJS({
  "node_modules/cohere-ai/core/fetcher/getFetchFn.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getFetchFn = void 0;
    var runtime_1 = require_runtime2();
    function getFetchFn() {
      return __awaiter6(this, void 0, void 0, function* () {
        if (runtime_1.RUNTIME.type === "node" && runtime_1.RUNTIME.parsedVersion != null && runtime_1.RUNTIME.parsedVersion >= 18) {
          return fetch;
        }
        if (runtime_1.RUNTIME.type === "node") {
          return (yield Promise.resolve().then(() => __importStar5(require_browser4()))).default;
        }
        if (typeof fetch == "function") {
          return fetch;
        }
        return (yield Promise.resolve().then(() => __importStar5(require_browser4()))).default;
      });
    }
    exports.getFetchFn = getFetchFn;
  }
});

// node_modules/cohere-ai/core/fetcher/getRequestBody.js
var require_getRequestBody = __commonJS({
  "node_modules/cohere-ai/core/fetcher/getRequestBody.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRequestBody = void 0;
    function getRequestBody({ body, type }) {
      return __awaiter6(this, void 0, void 0, function* () {
        if (type.includes("json")) {
          return JSON.stringify(body);
        } else {
          return body;
        }
      });
    }
    exports.getRequestBody = getRequestBody;
  }
});

// node_modules/cohere-ai/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.js
var require_Node18UniversalStreamWrapper = __commonJS({
  "node_modules/cohere-ai/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Node18UniversalStreamWrapper = void 0;
    var Node18UniversalStreamWrapper = class {
      constructor(readableStream) {
        this.readableStream = readableStream;
        this.reader = this.readableStream.getReader();
        this.events = {
          data: [],
          end: [],
          error: [],
          readable: [],
          close: [],
          pause: [],
          resume: []
        };
        this.paused = false;
        this.resumeCallback = null;
        this.encoding = null;
      }
      on(event, callback) {
        var _a5;
        (_a5 = this.events[event]) === null || _a5 === void 0 ? void 0 : _a5.push(callback);
      }
      off(event, callback) {
        var _a5;
        this.events[event] = (_a5 = this.events[event]) === null || _a5 === void 0 ? void 0 : _a5.filter((cb) => cb !== callback);
      }
      pipe(dest) {
        this.on("data", (chunk) => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._write(chunk);
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.write(chunk).then(() => writer.releaseLock());
          } else {
            dest.write(chunk);
          }
        }));
        this.on("end", () => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._end();
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.close();
          } else {
            dest.end();
          }
        }));
        this.on("error", (error) => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._error(error);
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.abort(error);
          } else {
            dest.destroy(error);
          }
        }));
        this._startReading();
        return dest;
      }
      pipeTo(dest) {
        return this.pipe(dest);
      }
      unpipe(dest) {
        this.off("data", (chunk) => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._write(chunk);
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.write(chunk).then(() => writer.releaseLock());
          } else {
            dest.write(chunk);
          }
        }));
        this.off("end", () => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._end();
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.close();
          } else {
            dest.end();
          }
        }));
        this.off("error", (error) => __awaiter6(this, void 0, void 0, function* () {
          if (dest instanceof Node18UniversalStreamWrapper) {
            dest._error(error);
          } else if (dest instanceof WritableStream) {
            const writer = dest.getWriter();
            writer.abort(error);
          } else {
            dest.destroy(error);
          }
        }));
      }
      destroy(error) {
        this.reader.cancel(error).then(() => {
          this._emit("close");
        }).catch((err) => {
          this._emit("error", err);
        });
      }
      pause() {
        this.paused = true;
        this._emit("pause");
      }
      resume() {
        if (this.paused) {
          this.paused = false;
          this._emit("resume");
          if (this.resumeCallback) {
            this.resumeCallback();
            this.resumeCallback = null;
          }
        }
      }
      get isPaused() {
        return this.paused;
      }
      read() {
        return __awaiter6(this, void 0, void 0, function* () {
          if (this.paused) {
            yield new Promise((resolve) => {
              this.resumeCallback = resolve;
            });
          }
          const { done, value } = yield this.reader.read();
          if (done) {
            return void 0;
          }
          return value;
        });
      }
      setEncoding(encoding) {
        this.encoding = encoding;
      }
      text() {
        return __awaiter6(this, void 0, void 0, function* () {
          const chunks = [];
          while (true) {
            const { done, value } = yield this.reader.read();
            if (done)
              break;
            if (value)
              chunks.push(value);
          }
          const decoder = new TextDecoder(this.encoding || "utf-8");
          return decoder.decode(yield new Blob(chunks).arrayBuffer());
        });
      }
      json() {
        return __awaiter6(this, void 0, void 0, function* () {
          const text = yield this.text();
          return JSON.parse(text);
        });
      }
      _write(chunk) {
        this._emit("data", chunk);
      }
      _end() {
        this._emit("end");
      }
      _error(error) {
        this._emit("error", error);
      }
      _emit(event, data) {
        if (this.events[event]) {
          for (const callback of this.events[event] || []) {
            callback(data);
          }
        }
      }
      _startReading() {
        return __awaiter6(this, void 0, void 0, function* () {
          try {
            this._emit("readable");
            while (true) {
              if (this.paused) {
                yield new Promise((resolve) => {
                  this.resumeCallback = resolve;
                });
              }
              const { done, value } = yield this.reader.read();
              if (done) {
                this._emit("end");
                this._emit("close");
                break;
              }
              if (value) {
                this._emit("data", value);
              }
            }
          } catch (error) {
            this._emit("error", error);
          }
        });
      }
      [Symbol.asyncIterator]() {
        return {
          next: () => __awaiter6(this, void 0, void 0, function* () {
            if (this.paused) {
              yield new Promise((resolve) => {
                this.resumeCallback = resolve;
              });
            }
            const { done, value } = yield this.reader.read();
            if (done) {
              return { done: true, value: void 0 };
            }
            return { done: false, value };
          }),
          [Symbol.asyncIterator]() {
            return this;
          }
        };
      }
    };
    exports.Node18UniversalStreamWrapper = Node18UniversalStreamWrapper;
  }
});

// node_modules/cohere-ai/core/fetcher/stream-wrappers/UndiciStreamWrapper.js
var require_UndiciStreamWrapper = __commonJS({
  "node_modules/cohere-ai/core/fetcher/stream-wrappers/UndiciStreamWrapper.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UndiciStreamWrapper = void 0;
    var UndiciStreamWrapper = class {
      constructor(readableStream) {
        this.readableStream = readableStream;
        this.reader = this.readableStream.getReader();
        this.events = {
          data: [],
          end: [],
          error: [],
          readable: [],
          close: [],
          pause: [],
          resume: []
        };
        this.paused = false;
        this.resumeCallback = null;
        this.encoding = null;
      }
      on(event, callback) {
        var _a5;
        (_a5 = this.events[event]) === null || _a5 === void 0 ? void 0 : _a5.push(callback);
      }
      off(event, callback) {
        var _a5;
        this.events[event] = (_a5 = this.events[event]) === null || _a5 === void 0 ? void 0 : _a5.filter((cb) => cb !== callback);
      }
      pipe(dest) {
        this.on("data", (chunk) => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._write(chunk);
          } else {
            const writer = dest.getWriter();
            writer.write(chunk).then(() => writer.releaseLock());
          }
        });
        this.on("end", () => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._end();
          } else {
            const writer = dest.getWriter();
            writer.close();
          }
        });
        this.on("error", (error) => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._error(error);
          } else {
            const writer = dest.getWriter();
            writer.abort(error);
          }
        });
        this._startReading();
        return dest;
      }
      pipeTo(dest) {
        return this.pipe(dest);
      }
      unpipe(dest) {
        this.off("data", (chunk) => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._write(chunk);
          } else {
            const writer = dest.getWriter();
            writer.write(chunk).then(() => writer.releaseLock());
          }
        });
        this.off("end", () => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._end();
          } else {
            const writer = dest.getWriter();
            writer.close();
          }
        });
        this.off("error", (error) => {
          if (dest instanceof UndiciStreamWrapper) {
            dest._error(error);
          } else {
            const writer = dest.getWriter();
            writer.abort(error);
          }
        });
      }
      destroy(error) {
        this.reader.cancel(error).then(() => {
          this._emit("close");
        }).catch((err) => {
          this._emit("error", err);
        });
      }
      pause() {
        this.paused = true;
        this._emit("pause");
      }
      resume() {
        if (this.paused) {
          this.paused = false;
          this._emit("resume");
          if (this.resumeCallback) {
            this.resumeCallback();
            this.resumeCallback = null;
          }
        }
      }
      get isPaused() {
        return this.paused;
      }
      read() {
        return __awaiter6(this, void 0, void 0, function* () {
          if (this.paused) {
            yield new Promise((resolve) => {
              this.resumeCallback = resolve;
            });
          }
          const { done, value } = yield this.reader.read();
          if (done) {
            return void 0;
          }
          return value;
        });
      }
      setEncoding(encoding) {
        this.encoding = encoding;
      }
      text() {
        return __awaiter6(this, void 0, void 0, function* () {
          const chunks = [];
          while (true) {
            const { done, value } = yield this.reader.read();
            if (done)
              break;
            if (value)
              chunks.push(value);
          }
          const decoder = new TextDecoder(this.encoding || "utf-8");
          return decoder.decode(yield new Blob(chunks).arrayBuffer());
        });
      }
      json() {
        return __awaiter6(this, void 0, void 0, function* () {
          const text = yield this.text();
          return JSON.parse(text);
        });
      }
      _write(chunk) {
        this._emit("data", chunk);
      }
      _end() {
        this._emit("end");
      }
      _error(error) {
        this._emit("error", error);
      }
      _emit(event, data) {
        if (this.events[event]) {
          for (const callback of this.events[event] || []) {
            callback(data);
          }
        }
      }
      _startReading() {
        return __awaiter6(this, void 0, void 0, function* () {
          try {
            this._emit("readable");
            while (true) {
              if (this.paused) {
                yield new Promise((resolve) => {
                  this.resumeCallback = resolve;
                });
              }
              const { done, value } = yield this.reader.read();
              if (done) {
                this._emit("end");
                this._emit("close");
                break;
              }
              if (value) {
                this._emit("data", value);
              }
            }
          } catch (error) {
            this._emit("error", error);
          }
        });
      }
      [Symbol.asyncIterator]() {
        return {
          next: () => __awaiter6(this, void 0, void 0, function* () {
            if (this.paused) {
              yield new Promise((resolve) => {
                this.resumeCallback = resolve;
              });
            }
            const { done, value } = yield this.reader.read();
            if (done) {
              return { done: true, value: void 0 };
            }
            return { done: false, value };
          }),
          [Symbol.asyncIterator]() {
            return this;
          }
        };
      }
    };
    exports.UndiciStreamWrapper = UndiciStreamWrapper;
  }
});

// node_modules/cohere-ai/core/fetcher/stream-wrappers/NodePre18StreamWrapper.js
var require_NodePre18StreamWrapper = __commonJS({
  "node_modules/cohere-ai/core/fetcher/stream-wrappers/NodePre18StreamWrapper.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __asyncValues5 = exports && exports.__asyncValues || function(o3) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var m3 = o3[Symbol.asyncIterator], i3;
      return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3);
      function verb(n4) {
        i3[n4] = o3[n4] && function(v5) {
          return new Promise(function(resolve, reject) {
            v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
          });
        };
      }
      function settle(resolve, reject, d3, v5) {
        Promise.resolve(v5).then(function(v6) {
          resolve({ value: v6, done: d3 });
        }, reject);
      }
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodePre18StreamWrapper = void 0;
    var NodePre18StreamWrapper = class {
      constructor(readableStream) {
        this.readableStream = readableStream;
      }
      on(event, callback) {
        this.readableStream.on(event, callback);
      }
      off(event, callback) {
        this.readableStream.off(event, callback);
      }
      pipe(dest) {
        this.readableStream.pipe(dest);
        return dest;
      }
      pipeTo(dest) {
        return this.pipe(dest);
      }
      unpipe(dest) {
        if (dest) {
          this.readableStream.unpipe(dest);
        } else {
          this.readableStream.unpipe();
        }
      }
      destroy(error) {
        this.readableStream.destroy(error);
      }
      pause() {
        this.readableStream.pause();
      }
      resume() {
        this.readableStream.resume();
      }
      get isPaused() {
        return this.readableStream.isPaused();
      }
      read() {
        return __awaiter6(this, void 0, void 0, function* () {
          return new Promise((resolve, reject) => {
            const chunk = this.readableStream.read();
            if (chunk) {
              resolve(chunk);
            } else {
              this.readableStream.once("readable", () => {
                const chunk2 = this.readableStream.read();
                resolve(chunk2);
              });
              this.readableStream.once("error", reject);
            }
          });
        });
      }
      setEncoding(encoding) {
        this.readableStream.setEncoding(encoding);
        this.encoding = encoding;
      }
      text() {
        var e_1, _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const chunks = [];
          const encoder = new TextEncoder();
          this.readableStream.setEncoding(this.encoding || "utf-8");
          try {
            for (var _b = __asyncValues5(this.readableStream), _c; _c = yield _b.next(), !_c.done; ) {
              const chunk = _c.value;
              chunks.push(encoder.encode(chunk));
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (_c && !_c.done && (_a5 = _b.return))
                yield _a5.call(_b);
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
          const decoder = new TextDecoder(this.encoding || "utf-8");
          return decoder.decode(Buffer.concat(chunks));
        });
      }
      json() {
        return __awaiter6(this, void 0, void 0, function* () {
          const text = yield this.text();
          return JSON.parse(text);
        });
      }
      [Symbol.asyncIterator]() {
        const readableStream = this.readableStream;
        const iterator = readableStream[Symbol.asyncIterator]();
        return {
          next() {
            return __awaiter6(this, void 0, void 0, function* () {
              const { value, done } = yield iterator.next();
              return { value, done };
            });
          },
          [Symbol.asyncIterator]() {
            return this;
          }
        };
      }
    };
    exports.NodePre18StreamWrapper = NodePre18StreamWrapper;
  }
});

// node_modules/cohere-ai/core/fetcher/stream-wrappers/chooseStreamWrapper.js
var require_chooseStreamWrapper = __commonJS({
  "node_modules/cohere-ai/core/fetcher/stream-wrappers/chooseStreamWrapper.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.chooseStreamWrapper = void 0;
    var runtime_1 = require_runtime2();
    function chooseStreamWrapper(responseBody) {
      return __awaiter6(this, void 0, void 0, function* () {
        if (runtime_1.RUNTIME.type === "node" && runtime_1.RUNTIME.parsedVersion != null && runtime_1.RUNTIME.parsedVersion >= 18) {
          return new (yield Promise.resolve().then(() => __importStar5(require_Node18UniversalStreamWrapper()))).Node18UniversalStreamWrapper(responseBody);
        } else if (runtime_1.RUNTIME.type !== "node" && typeof fetch == "function") {
          return new (yield Promise.resolve().then(() => __importStar5(require_UndiciStreamWrapper()))).UndiciStreamWrapper(responseBody);
        } else {
          return new (yield Promise.resolve().then(() => __importStar5(require_NodePre18StreamWrapper()))).NodePre18StreamWrapper(responseBody);
        }
      });
    }
    exports.chooseStreamWrapper = chooseStreamWrapper;
  }
});

// node_modules/cohere-ai/core/fetcher/getResponseBody.js
var require_getResponseBody = __commonJS({
  "node_modules/cohere-ai/core/fetcher/getResponseBody.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getResponseBody = void 0;
    var chooseStreamWrapper_1 = require_chooseStreamWrapper();
    function getResponseBody(response, responseType) {
      return __awaiter6(this, void 0, void 0, function* () {
        if (response.body != null && responseType === "blob") {
          return yield response.blob();
        } else if (response.body != null && responseType === "sse") {
          return response.body;
        } else if (response.body != null && responseType === "streaming") {
          return (0, chooseStreamWrapper_1.chooseStreamWrapper)(response.body);
        } else if (response.body != null && responseType === "text") {
          return yield response.text();
        } else {
          const text = yield response.text();
          if (text.length > 0) {
            try {
              let responseBody = JSON.parse(text);
              return responseBody;
            } catch (err) {
              return {
                ok: false,
                error: {
                  reason: "non-json",
                  statusCode: response.status,
                  rawBody: text
                }
              };
            }
          } else {
            return void 0;
          }
        }
      });
    }
    exports.getResponseBody = getResponseBody;
  }
});

// node_modules/cohere-ai/core/fetcher/signals.js
var require_signals = __commonJS({
  "node_modules/cohere-ai/core/fetcher/signals.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.anySignal = exports.getTimeoutSignal = void 0;
    var TIMEOUT = "timeout";
    function getTimeoutSignal(timeoutMs) {
      const controller = new AbortController();
      const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
      return { signal: controller.signal, abortId };
    }
    exports.getTimeoutSignal = getTimeoutSignal;
    function anySignal(...args) {
      const signals = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
      const controller = new AbortController();
      for (const signal of signals) {
        if (signal.aborted) {
          controller.abort(signal === null || signal === void 0 ? void 0 : signal.reason);
          break;
        }
        signal.addEventListener("abort", () => controller.abort(signal === null || signal === void 0 ? void 0 : signal.reason), {
          signal: controller.signal
        });
      }
      return controller.signal;
    }
    exports.anySignal = anySignal;
  }
});

// node_modules/cohere-ai/core/fetcher/makeRequest.js
var require_makeRequest = __commonJS({
  "node_modules/cohere-ai/core/fetcher/makeRequest.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.makeRequest = void 0;
    var signals_1 = require_signals();
    var makeRequest2 = (fetchFn, url, method, headers, requestBody, timeoutMs, abortSignal, withCredentials, duplex) => __awaiter6(void 0, void 0, void 0, function* () {
      const signals = [];
      let timeoutAbortId = void 0;
      if (timeoutMs != null) {
        const { signal, abortId } = (0, signals_1.getTimeoutSignal)(timeoutMs);
        timeoutAbortId = abortId;
        signals.push(signal);
      }
      if (abortSignal != null) {
        signals.push(abortSignal);
      }
      let newSignals = (0, signals_1.anySignal)(signals);
      const response = yield fetchFn(url, {
        method,
        headers,
        body: requestBody,
        signal: newSignals,
        credentials: withCredentials ? "include" : void 0,
        // @ts-ignore
        duplex
      });
      if (timeoutAbortId != null) {
        clearTimeout(timeoutAbortId);
      }
      return response;
    });
    exports.makeRequest = makeRequest2;
  }
});

// node_modules/cohere-ai/core/fetcher/requestWithRetries.js
var require_requestWithRetries = __commonJS({
  "node_modules/cohere-ai/core/fetcher/requestWithRetries.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.requestWithRetries = void 0;
    var INITIAL_RETRY_DELAY = 1;
    var MAX_RETRY_DELAY = 60;
    var DEFAULT_MAX_RETRIES = 2;
    function requestWithRetries(requestFn, maxRetries = DEFAULT_MAX_RETRIES) {
      return __awaiter6(this, void 0, void 0, function* () {
        let response = yield requestFn();
        for (let i3 = 0; i3 < maxRetries; ++i3) {
          if ([408, 409, 429].includes(response.status) || response.status >= 500) {
            const delay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i3), MAX_RETRY_DELAY);
            yield new Promise((resolve) => setTimeout(resolve, delay));
            response = yield requestFn();
          } else {
            break;
          }
        }
        return response;
      });
    }
    exports.requestWithRetries = requestWithRetries;
  }
});

// node_modules/cohere-ai/core/fetcher/Fetcher.js
var require_Fetcher = __commonJS({
  "node_modules/cohere-ai/core/fetcher/Fetcher.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fetcher = exports.fetcherImpl = void 0;
    var createRequestUrl_1 = require_createRequestUrl();
    var getFetchFn_1 = require_getFetchFn();
    var getRequestBody_1 = require_getRequestBody();
    var getResponseBody_1 = require_getResponseBody();
    var makeRequest_1 = require_makeRequest();
    var requestWithRetries_1 = require_requestWithRetries();
    function fetcherImpl(args) {
      return __awaiter6(this, void 0, void 0, function* () {
        const headers = {};
        if (args.body !== void 0 && args.contentType != null) {
          headers["Content-Type"] = args.contentType;
        }
        if (args.headers != null) {
          for (const [key, value] of Object.entries(args.headers)) {
            if (value != null) {
              headers[key] = value;
            }
          }
        }
        const url = (0, createRequestUrl_1.createRequestUrl)(args.url, args.queryParameters);
        let requestBody = yield (0, getRequestBody_1.getRequestBody)({
          body: args.body,
          type: args.requestType === "json" ? "json" : "other"
        });
        const fetchFn = yield (0, getFetchFn_1.getFetchFn)();
        try {
          const response = yield (0, requestWithRetries_1.requestWithRetries)(() => __awaiter6(this, void 0, void 0, function* () {
            return (0, makeRequest_1.makeRequest)(fetchFn, url, args.method, headers, requestBody, args.timeoutMs, args.abortSignal, args.withCredentials, args.duplex);
          }), args.maxRetries);
          let responseBody = yield (0, getResponseBody_1.getResponseBody)(response, args.responseType);
          if (response.status >= 200 && response.status < 400) {
            return {
              ok: true,
              body: responseBody,
              headers: response.headers
            };
          } else {
            return {
              ok: false,
              error: {
                reason: "status-code",
                statusCode: response.status,
                body: responseBody
              }
            };
          }
        } catch (error) {
          if (args.abortSignal != null && args.abortSignal.aborted) {
            return {
              ok: false,
              error: {
                reason: "unknown",
                errorMessage: "The user aborted a request"
              }
            };
          } else if (error instanceof Error && error.name === "AbortError") {
            return {
              ok: false,
              error: {
                reason: "timeout"
              }
            };
          } else if (error instanceof Error) {
            return {
              ok: false,
              error: {
                reason: "unknown",
                errorMessage: error.message
              }
            };
          }
          return {
            ok: false,
            error: {
              reason: "unknown",
              errorMessage: JSON.stringify(error)
            }
          };
        }
      });
    }
    exports.fetcherImpl = fetcherImpl;
    exports.fetcher = fetcherImpl;
  }
});

// node_modules/cohere-ai/core/fetcher/getHeader.js
var require_getHeader = __commonJS({
  "node_modules/cohere-ai/core/fetcher/getHeader.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getHeader = void 0;
    function getHeader2(headers, header) {
      for (const [headerKey, headerValue] of Object.entries(headers)) {
        if (headerKey.toLowerCase() === header.toLowerCase()) {
          return headerValue;
        }
      }
      return void 0;
    }
    exports.getHeader = getHeader2;
  }
});

// node_modules/cohere-ai/core/fetcher/Supplier.js
var require_Supplier = __commonJS({
  "node_modules/cohere-ai/core/fetcher/Supplier.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Supplier = void 0;
    exports.Supplier = {
      get: (supplier) => __awaiter6(void 0, void 0, void 0, function* () {
        if (typeof supplier === "function") {
          return supplier();
        } else {
          return supplier;
        }
      })
    };
  }
});

// node_modules/cohere-ai/core/fetcher/index.js
var require_fetcher = __commonJS({
  "node_modules/cohere-ai/core/fetcher/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Supplier = exports.getHeader = exports.fetcher = void 0;
    var Fetcher_1 = require_Fetcher();
    Object.defineProperty(exports, "fetcher", { enumerable: true, get: function() {
      return Fetcher_1.fetcher;
    } });
    var getHeader_1 = require_getHeader();
    Object.defineProperty(exports, "getHeader", { enumerable: true, get: function() {
      return getHeader_1.getHeader;
    } });
    var Supplier_1 = require_Supplier();
    Object.defineProperty(exports, "Supplier", { enumerable: true, get: function() {
      return Supplier_1.Supplier;
    } });
  }
});

// node_modules/js-base64/base64.js
var require_base64 = __commonJS({
  "node_modules/js-base64/base64.js"(exports, module2) {
    (function(global2, factory) {
      typeof exports === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (
        // cf. https://github.com/dankogai/js-base64/issues/119
        function() {
          var _Base64 = global2.Base64;
          var gBase64 = factory();
          gBase64.noConflict = function() {
            global2.Base64 = _Base64;
            return gBase64;
          };
          if (global2.Meteor) {
            Base64 = gBase64;
          }
          global2.Base64 = gBase64;
        }()
      );
    })(typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof window !== "undefined" ? window : exports, function() {
      "use strict";
      var version2 = "3.7.2";
      var VERSION4 = version2;
      var _hasatob = typeof atob === "function";
      var _hasbtoa = typeof btoa === "function";
      var _hasBuffer = typeof Buffer === "function";
      var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
      var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
      var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      var b64chs = Array.prototype.slice.call(b64ch);
      var b64tab = function(a3) {
        var tab = {};
        a3.forEach(function(c4, i3) {
          return tab[c4] = i3;
        });
        return tab;
      }(b64chs);
      var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
      var _fromCC = String.fromCharCode.bind(String);
      var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : function(it, fn) {
        if (fn === void 0) {
          fn = function(x2) {
            return x2;
          };
        }
        return new Uint8Array(Array.prototype.slice.call(it, 0).map(fn));
      };
      var _mkUriSafe = function(src) {
        return src.replace(/=/g, "").replace(/[+\/]/g, function(m0) {
          return m0 == "+" ? "-" : "_";
        });
      };
      var _tidyB64 = function(s4) {
        return s4.replace(/[^A-Za-z0-9\+\/]/g, "");
      };
      var btoaPolyfill = function(bin) {
        var u32, c0, c1, c22, asc = "";
        var pad = bin.length % 3;
        for (var i3 = 0; i3 < bin.length; ) {
          if ((c0 = bin.charCodeAt(i3++)) > 255 || (c1 = bin.charCodeAt(i3++)) > 255 || (c22 = bin.charCodeAt(i3++)) > 255)
            throw new TypeError("invalid character found");
          u32 = c0 << 16 | c1 << 8 | c22;
          asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
        }
        return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
      };
      var _btoa = _hasbtoa ? function(bin) {
        return btoa(bin);
      } : _hasBuffer ? function(bin) {
        return Buffer.from(bin, "binary").toString("base64");
      } : btoaPolyfill;
      var _fromUint8Array = _hasBuffer ? function(u8a) {
        return Buffer.from(u8a).toString("base64");
      } : function(u8a) {
        var maxargs = 4096;
        var strs = [];
        for (var i3 = 0, l4 = u8a.length; i3 < l4; i3 += maxargs) {
          strs.push(_fromCC.apply(null, u8a.subarray(i3, i3 + maxargs)));
        }
        return _btoa(strs.join(""));
      };
      var fromUint8Array = function(u8a, urlsafe) {
        if (urlsafe === void 0) {
          urlsafe = false;
        }
        return urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
      };
      var cb_utob = function(c4) {
        if (c4.length < 2) {
          var cc = c4.charCodeAt(0);
          return cc < 128 ? c4 : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
        } else {
          var cc = 65536 + (c4.charCodeAt(0) - 55296) * 1024 + (c4.charCodeAt(1) - 56320);
          return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
        }
      };
      var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
      var utob = function(u3) {
        return u3.replace(re_utob, cb_utob);
      };
      var _encode = _hasBuffer ? function(s4) {
        return Buffer.from(s4, "utf8").toString("base64");
      } : _TE ? function(s4) {
        return _fromUint8Array(_TE.encode(s4));
      } : function(s4) {
        return _btoa(utob(s4));
      };
      var encode2 = function(src, urlsafe) {
        if (urlsafe === void 0) {
          urlsafe = false;
        }
        return urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
      };
      var encodeURI2 = function(src) {
        return encode2(src, true);
      };
      var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
      var cb_btou = function(cccc) {
        switch (cccc.length) {
          case 4:
            var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset5 = cp - 65536;
            return _fromCC((offset5 >>> 10) + 55296) + _fromCC((offset5 & 1023) + 56320);
          case 3:
            return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
          default:
            return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
        }
      };
      var btou = function(b3) {
        return b3.replace(re_btou, cb_btou);
      };
      var atobPolyfill = function(asc) {
        asc = asc.replace(/\s+/g, "");
        if (!b64re.test(asc))
          throw new TypeError("malformed base64.");
        asc += "==".slice(2 - (asc.length & 3));
        var u24, bin = "", r1, r22;
        for (var i3 = 0; i3 < asc.length; ) {
          u24 = b64tab[asc.charAt(i3++)] << 18 | b64tab[asc.charAt(i3++)] << 12 | (r1 = b64tab[asc.charAt(i3++)]) << 6 | (r22 = b64tab[asc.charAt(i3++)]);
          bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r22 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
        }
        return bin;
      };
      var _atob = _hasatob ? function(asc) {
        return atob(_tidyB64(asc));
      } : _hasBuffer ? function(asc) {
        return Buffer.from(asc, "base64").toString("binary");
      } : atobPolyfill;
      var _toUint8Array = _hasBuffer ? function(a3) {
        return _U8Afrom(Buffer.from(a3, "base64"));
      } : function(a3) {
        return _U8Afrom(_atob(a3), function(c4) {
          return c4.charCodeAt(0);
        });
      };
      var toUint8Array2 = function(a3) {
        return _toUint8Array(_unURI(a3));
      };
      var _decode = _hasBuffer ? function(a3) {
        return Buffer.from(a3, "base64").toString("utf8");
      } : _TD ? function(a3) {
        return _TD.decode(_toUint8Array(a3));
      } : function(a3) {
        return btou(_atob(a3));
      };
      var _unURI = function(a3) {
        return _tidyB64(a3.replace(/[-_]/g, function(m0) {
          return m0 == "-" ? "+" : "/";
        }));
      };
      var decode2 = function(src) {
        return _decode(_unURI(src));
      };
      var isValid2 = function(src) {
        if (typeof src !== "string")
          return false;
        var s4 = src.replace(/\s+/g, "").replace(/={0,2}$/, "");
        return !/[^\s0-9a-zA-Z\+/]/.test(s4) || !/[^\s0-9a-zA-Z\-_]/.test(s4);
      };
      var _noEnum = function(v5) {
        return {
          value: v5,
          enumerable: false,
          writable: true,
          configurable: true
        };
      };
      var extendString = function() {
        var _add = function(name, body) {
          return Object.defineProperty(String.prototype, name, _noEnum(body));
        };
        _add("fromBase64", function() {
          return decode2(this);
        });
        _add("toBase64", function(urlsafe) {
          return encode2(this, urlsafe);
        });
        _add("toBase64URI", function() {
          return encode2(this, true);
        });
        _add("toBase64URL", function() {
          return encode2(this, true);
        });
        _add("toUint8Array", function() {
          return toUint8Array2(this);
        });
      };
      var extendUint8Array = function() {
        var _add = function(name, body) {
          return Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
        };
        _add("toBase64", function(urlsafe) {
          return fromUint8Array(this, urlsafe);
        });
        _add("toBase64URI", function() {
          return fromUint8Array(this, true);
        });
        _add("toBase64URL", function() {
          return fromUint8Array(this, true);
        });
      };
      var extendBuiltins = function() {
        extendString();
        extendUint8Array();
      };
      var gBase64 = {
        version: version2,
        VERSION: VERSION4,
        atob: _atob,
        atobPolyfill,
        btoa: _btoa,
        btoaPolyfill,
        fromBase64: decode2,
        toBase64: encode2,
        encode: encode2,
        encodeURI: encodeURI2,
        encodeURL: encodeURI2,
        utob,
        btou,
        decode: decode2,
        isValid: isValid2,
        fromUint8Array,
        toUint8Array: toUint8Array2,
        extendString,
        extendUint8Array,
        extendBuiltins
      };
      gBase64.Base64 = {};
      Object.keys(gBase64).forEach(function(k3) {
        return gBase64.Base64[k3] = gBase64[k3];
      });
      return gBase64;
    });
  }
});

// node_modules/cohere-ai/core/auth/BasicAuth.js
var require_BasicAuth = __commonJS({
  "node_modules/cohere-ai/core/auth/BasicAuth.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BasicAuth = void 0;
    var js_base64_1 = require_base64();
    var BASIC_AUTH_HEADER_PREFIX = /^Basic /i;
    exports.BasicAuth = {
      toAuthorizationHeader: (basicAuth) => {
        if (basicAuth == null) {
          return void 0;
        }
        const token = js_base64_1.Base64.encode(`${basicAuth.username}:${basicAuth.password}`);
        return `Basic ${token}`;
      },
      fromAuthorizationHeader: (header) => {
        const credentials = header.replace(BASIC_AUTH_HEADER_PREFIX, "");
        const decoded = js_base64_1.Base64.decode(credentials);
        const [username, password] = decoded.split(":", 2);
        if (username == null || password == null) {
          throw new Error("Invalid basic auth");
        }
        return {
          username,
          password
        };
      }
    };
  }
});

// node_modules/cohere-ai/core/auth/BearerToken.js
var require_BearerToken = __commonJS({
  "node_modules/cohere-ai/core/auth/BearerToken.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BearerToken = void 0;
    var BEARER_AUTH_HEADER_PREFIX = /^Bearer /i;
    exports.BearerToken = {
      toAuthorizationHeader: (token) => {
        if (token == null) {
          return void 0;
        }
        return `Bearer ${token}`;
      },
      fromAuthorizationHeader: (header) => {
        return header.replace(BEARER_AUTH_HEADER_PREFIX, "").trim();
      }
    };
  }
});

// node_modules/cohere-ai/core/auth/index.js
var require_auth2 = __commonJS({
  "node_modules/cohere-ai/core/auth/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BearerToken = exports.BasicAuth = void 0;
    var BasicAuth_1 = require_BasicAuth();
    Object.defineProperty(exports, "BasicAuth", { enumerable: true, get: function() {
      return BasicAuth_1.BasicAuth;
    } });
    var BearerToken_1 = require_BearerToken();
    Object.defineProperty(exports, "BearerToken", { enumerable: true, get: function() {
      return BearerToken_1.BearerToken;
    } });
  }
});

// node_modules/cohere-ai/core/streaming-fetcher/Stream.js
var require_Stream = __commonJS({
  "node_modules/cohere-ai/core/streaming-fetcher/Stream.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __asyncValues5 = exports && exports.__asyncValues || function(o3) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var m3 = o3[Symbol.asyncIterator], i3;
      return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3);
      function verb(n4) {
        i3[n4] = o3[n4] && function(v5) {
          return new Promise(function(resolve, reject) {
            v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
          });
        };
      }
      function settle(resolve, reject, d3, v5) {
        Promise.resolve(v5).then(function(v6) {
          resolve({ value: v6, done: d3 });
        }, reject);
      }
    };
    var __await6 = exports && exports.__await || function(v5) {
      return this instanceof __await6 ? (this.v = v5, this) : new __await6(v5);
    };
    var __asyncGenerator6 = exports && exports.__asyncGenerator || function(thisArg, _arguments, generator) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
      return i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3;
      function verb(n4) {
        if (g4[n4])
          i3[n4] = function(v5) {
            return new Promise(function(a3, b3) {
              q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
            });
          };
      }
      function resume(n4, v5) {
        try {
          step(g4[n4](v5));
        } catch (e3) {
          settle(q3[0][3], e3);
        }
      }
      function step(r4) {
        r4.value instanceof __await6 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
      }
      function fulfill(value) {
        resume("next", value);
      }
      function reject(value) {
        resume("throw", value);
      }
      function settle(f3, v5) {
        if (f3(v5), q3.shift(), q3.length)
          resume(q3[0][0], q3[0][1]);
      }
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readableStreamAsyncIterable = exports.Stream = void 0;
    var runtime_1 = require_runtime2();
    var DATA_PREFIX = "data:";
    var Stream4 = class {
      constructor({ stream, parse: parse6, eventShape, signal }) {
        this.controller = new AbortController();
        this.stream = stream;
        this.parse = parse6;
        if (eventShape.type === "sse") {
          this.prefix = DATA_PREFIX;
          this.messageTerminator = "\n";
          this.streamTerminator = eventShape.streamTerminator;
        } else {
          this.messageTerminator = eventShape.messageTerminator;
        }
        signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", () => this.controller.abort());
      }
      iterMessages() {
        return __asyncGenerator6(this, arguments, function* iterMessages_1() {
          var e_1, _a5;
          this.controller.signal;
          const stream = readableStreamAsyncIterable4(this.stream);
          let buf = "";
          let prefixSeen = false;
          try {
            for (var stream_1 = __asyncValues5(stream), stream_1_1; stream_1_1 = yield __await6(stream_1.next()), !stream_1_1.done; ) {
              const chunk = stream_1_1.value;
              buf += this.decodeChunk(chunk);
              let terminatorIndex;
              while ((terminatorIndex = buf.indexOf(this.messageTerminator)) >= 0) {
                let line = buf.slice(0, terminatorIndex + 1);
                buf = buf.slice(terminatorIndex + 1);
                if (line.length === 0) {
                  continue;
                }
                if (!prefixSeen && this.prefix != null) {
                  const prefixIndex = line.indexOf(this.prefix);
                  if (prefixIndex === -1) {
                    continue;
                  }
                  prefixSeen = true;
                  line = line.slice(prefixIndex + this.prefix.length);
                }
                if (this.streamTerminator != null && line.includes(this.streamTerminator)) {
                  return yield __await6(void 0);
                }
                const message = yield __await6(this.parse(JSON.parse(line)));
                yield yield __await6(message);
                prefixSeen = false;
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (stream_1_1 && !stream_1_1.done && (_a5 = stream_1.return))
                yield __await6(_a5.call(stream_1));
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
        });
      }
      [Symbol.asyncIterator]() {
        return __asyncGenerator6(this, arguments, function* _a5() {
          var e_2, _b;
          try {
            for (var _c = __asyncValues5(this.iterMessages()), _d; _d = yield __await6(_c.next()), !_d.done; ) {
              const message = _d.value;
              yield yield __await6(message);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_d && !_d.done && (_b = _c.return))
                yield __await6(_b.call(_c));
            } finally {
              if (e_2)
                throw e_2.error;
            }
          }
        });
      }
      decodeChunk(chunk) {
        let decoded = "";
        if (typeof TextDecoder !== "undefined") {
          const decoder = new TextDecoder("utf8");
          decoded += decoder.decode(chunk);
        } else if (runtime_1.RUNTIME.type === "node" && typeof chunk != "undefined") {
          decoded += Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        }
        return decoded;
      }
    };
    exports.Stream = Stream4;
    function readableStreamAsyncIterable4(stream) {
      if (stream[Symbol.asyncIterator]) {
        return stream;
      }
      const reader = stream.getReader();
      return {
        next() {
          return __awaiter6(this, void 0, void 0, function* () {
            try {
              const result = yield reader.read();
              if (result === null || result === void 0 ? void 0 : result.done) {
                reader.releaseLock();
              }
              return result;
            } catch (e3) {
              reader.releaseLock();
              throw e3;
            }
          });
        },
        return() {
          return __awaiter6(this, void 0, void 0, function* () {
            const cancelPromise2 = reader.cancel();
            reader.releaseLock();
            yield cancelPromise2;
            return { done: true, value: void 0 };
          });
        },
        [Symbol.asyncIterator]() {
          return this;
        }
      };
    }
    exports.readableStreamAsyncIterable = readableStreamAsyncIterable4;
  }
});

// node_modules/cohere-ai/core/streaming-fetcher/index.js
var require_streaming_fetcher = __commonJS({
  "node_modules/cohere-ai/core/streaming-fetcher/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Stream = void 0;
    var Stream_1 = require_Stream();
    Object.defineProperty(exports, "Stream", { enumerable: true, get: function() {
      return Stream_1.Stream;
    } });
  }
});

// node_modules/cohere-ai/node_modules/formdata-node/lib/browser.cjs
var require_browser5 = __commonJS({
  "node_modules/cohere-ai/node_modules/formdata-node/lib/browser.cjs"(exports, module2) {
    "use strict";
    var __defProp4 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp4(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp4({}, "__esModule", { value: true }), mod);
    var browser_exports = {};
    __export2(browser_exports, {
      Blob: () => Blob5,
      File: () => File5,
      FormData: () => FormData5
    });
    module2.exports = __toCommonJS2(browser_exports);
    var globalObject = function() {
      if (typeof globalThis !== "undefined") {
        return globalThis;
      }
      if (typeof self !== "undefined") {
        return self;
      }
      return window;
    }();
    var { FormData: FormData5, Blob: Blob5, File: File5 } = globalObject;
  }
});

// node_modules/cohere-ai/node_modules/form-data-encoder/lib/index.cjs
var require_lib2 = __commonJS({
  "node_modules/cohere-ai/node_modules/form-data-encoder/lib/index.cjs"(exports, module2) {
    "use strict";
    var __defProp4 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames2 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp4(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp4(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp4({}, "__esModule", { value: true }), mod);
    var __accessCheck = (obj, member, msg) => {
      if (!member.has(obj))
        throw TypeError("Cannot " + msg);
    };
    var __privateGet = (obj, member, getter) => {
      __accessCheck(obj, member, "read from private field");
      return getter ? getter.call(obj) : member.get(obj);
    };
    var __privateAdd = (obj, member, value) => {
      if (member.has(obj))
        throw 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");
      setter ? setter.call(obj, value) : member.set(obj, value);
      return value;
    };
    var __privateMethod = (obj, member, method) => {
      __accessCheck(obj, member, "access private method");
      return method;
    };
    var src_exports = {};
    __export2(src_exports, {
      FormDataEncoder: () => FormDataEncoder,
      isFile: () => isFile,
      isFormData: () => isFormData
    });
    module2.exports = __toCommonJS2(src_exports);
    var isFunction2 = (value) => typeof value === "function";
    var isAsyncIterable2 = (value) => isFunction2(value[Symbol.asyncIterator]);
    var MAX_CHUNK_SIZE = 65536;
    function* chunk(value) {
      if (value.byteLength <= MAX_CHUNK_SIZE) {
        yield value;
        return;
      }
      let offset5 = 0;
      while (offset5 < value.byteLength) {
        const size4 = Math.min(value.byteLength - offset5, MAX_CHUNK_SIZE);
        const buffer = value.buffer.slice(offset5, offset5 + size4);
        offset5 += buffer.byteLength;
        yield new Uint8Array(buffer);
      }
    }
    async function* readStream(readable) {
      const reader = readable.getReader();
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          break;
        }
        yield value;
      }
    }
    async function* chunkStream(stream) {
      for await (const value of stream) {
        yield* chunk(value);
      }
    }
    var getStreamIterator = (source) => {
      if (isAsyncIterable2(source)) {
        return chunkStream(source);
      }
      if (isFunction2(source.getReader)) {
        return chunkStream(readStream(source));
      }
      throw new TypeError(
        "Unsupported data source: Expected either ReadableStream or async iterable."
      );
    };
    var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
    function createBoundary() {
      let size4 = 16;
      let res = "";
      while (size4--) {
        res += alphabet[Math.random() * alphabet.length << 0];
      }
      return res;
    }
    var normalizeValue2 = (value) => String(value).replace(/\r|\n/g, (match2, i3, str2) => {
      if (match2 === "\r" && str2[i3 + 1] !== "\n" || match2 === "\n" && str2[i3 - 1] !== "\r") {
        return "\r\n";
      }
      return match2;
    });
    var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
    function isPlainObject(value) {
      if (getType(value) !== "object") {
        return false;
      }
      const pp = Object.getPrototypeOf(value);
      if (pp === null || pp === void 0) {
        return true;
      }
      const Ctor = pp.constructor && pp.constructor.toString();
      return Ctor === Object.toString();
    }
    function getProperty(target, prop) {
      if (typeof prop === "string") {
        for (const [name, value] of Object.entries(target)) {
          if (prop.toLowerCase() === name.toLowerCase()) {
            return value;
          }
        }
      }
      return void 0;
    }
    var proxyHeaders = (object) => new Proxy(
      object,
      {
        get: (target, prop) => getProperty(target, prop),
        has: (target, prop) => getProperty(target, prop) !== void 0
      }
    );
    var isFormData = (value) => Boolean(
      value && isFunction2(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction2(value.append) && isFunction2(value.getAll) && isFunction2(value.entries) && isFunction2(value[Symbol.iterator])
    );
    var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22");
    var isFile = (value) => Boolean(
      value && typeof value === "object" && isFunction2(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction2(value.stream) && value.name != null
    );
    var defaultOptions4 = {
      enableAdditionalHeaders: false
    };
    var readonlyProp = { writable: false, configurable: false };
    var _CRLF;
    var _CRLF_BYTES;
    var _CRLF_BYTES_LENGTH;
    var _DASHES;
    var _encoder;
    var _footer;
    var _form;
    var _options;
    var _getFieldHeader;
    var getFieldHeader_fn;
    var _getContentLength;
    var getContentLength_fn;
    var FormDataEncoder = class {
      constructor(form, boundaryOrOptions, options) {
        __privateAdd(this, _getFieldHeader);
        __privateAdd(this, _getContentLength);
        __privateAdd(this, _CRLF, "\r\n");
        __privateAdd(this, _CRLF_BYTES, void 0);
        __privateAdd(this, _CRLF_BYTES_LENGTH, void 0);
        __privateAdd(this, _DASHES, "-".repeat(2));
        __privateAdd(this, _encoder, new TextEncoder());
        __privateAdd(this, _footer, void 0);
        __privateAdd(this, _form, void 0);
        __privateAdd(this, _options, void 0);
        if (!isFormData(form)) {
          throw new TypeError("Expected first argument to be a FormData instance.");
        }
        let boundary;
        if (isPlainObject(boundaryOrOptions)) {
          options = boundaryOrOptions;
        } else {
          boundary = boundaryOrOptions;
        }
        if (!boundary) {
          boundary = createBoundary();
        }
        if (typeof boundary !== "string") {
          throw new TypeError("Expected boundary argument to be a string.");
        }
        if (options && !isPlainObject(options)) {
          throw new TypeError("Expected options argument to be an object.");
        }
        __privateSet(this, _form, Array.from(form.entries()));
        __privateSet(this, _options, { ...defaultOptions4, ...options });
        __privateSet(this, _CRLF_BYTES, __privateGet(this, _encoder).encode(__privateGet(this, _CRLF)));
        __privateSet(this, _CRLF_BYTES_LENGTH, __privateGet(this, _CRLF_BYTES).byteLength);
        this.boundary = `form-data-boundary-${boundary}`;
        this.contentType = `multipart/form-data; boundary=${this.boundary}`;
        __privateSet(this, _footer, __privateGet(this, _encoder).encode(
          `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _DASHES)}${__privateGet(this, _CRLF).repeat(2)}`
        ));
        const headers = {
          "Content-Type": this.contentType
        };
        const contentLength = __privateMethod(this, _getContentLength, getContentLength_fn).call(this);
        if (contentLength) {
          this.contentLength = contentLength;
          headers["Content-Length"] = contentLength;
        }
        this.headers = proxyHeaders(Object.freeze(headers));
        Object.defineProperties(this, {
          boundary: readonlyProp,
          contentType: readonlyProp,
          contentLength: readonlyProp,
          headers: readonlyProp
        });
      }
      /**
       * Creates an iterator allowing to go through form-data parts (with metadata).
       * This method **will not** read the files and **will not** split values big into smaller chunks.
       *
       * Using this method, you can convert form-data content into Blob:
       *
       * @example
       *
       * ```ts
       * import {Readable} from "stream"
       *
       * import {FormDataEncoder} from "form-data-encoder"
       *
       * import {FormData} from "formdata-polyfill/esm-min.js"
       * import {fileFrom} from "fetch-blob/form.js"
       * import {File} from "fetch-blob/file.js"
       * import {Blob} from "fetch-blob"
       *
       * import fetch from "node-fetch"
       *
       * const form = new FormData()
       *
       * form.set("field", "Just a random string")
       * form.set("file", new File(["Using files is class amazing"]))
       * form.set("fileFromPath", await fileFrom("path/to/a/file.txt"))
       *
       * const encoder = new FormDataEncoder(form)
       *
       * const options = {
       *   method: "post",
       *   body: new Blob(encoder, {type: encoder.contentType})
       * }
       *
       * const response = await fetch("https://httpbin.org/post", options)
       *
       * console.log(await response.json())
       * ```
       */
      *values() {
        for (const [name, raw] of __privateGet(this, _form)) {
          const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode(
            normalizeValue2(raw)
          );
          yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value);
          yield value;
          yield __privateGet(this, _CRLF_BYTES);
        }
        yield __privateGet(this, _footer);
      }
      /**
       * Creates an async iterator allowing to perform the encoding by portions.
       * This method reads through files and splits big values into smaller pieces (65536 bytes per each).
       *
       * @example
       *
       * ```ts
       * import {Readable} from "stream"
       *
       * import {FormData, File, fileFromPath} from "formdata-node"
       * import {FormDataEncoder} from "form-data-encoder"
       *
       * import fetch from "node-fetch"
       *
       * const form = new FormData()
       *
       * form.set("field", "Just a random string")
       * form.set("file", new File(["Using files is class amazing"], "file.txt"))
       * form.set("fileFromPath", await fileFromPath("path/to/a/file.txt"))
       *
       * const encoder = new FormDataEncoder(form)
       *
       * const options = {
       *   method: "post",
       *   headers: encoder.headers,
       *   body: Readable.from(encoder.encode()) // or Readable.from(encoder)
       * }
       *
       * const response = await fetch("https://httpbin.org/post", options)
       *
       * console.log(await response.json())
       * ```
       */
      async *encode() {
        for (const part of this.values()) {
          if (isFile(part)) {
            yield* getStreamIterator(part.stream());
          } else {
            yield* chunk(part);
          }
        }
      }
      /**
       * Creates an iterator allowing to read through the encoder data using for...of loops
       */
      [Symbol.iterator]() {
        return this.values();
      }
      /**
       * Creates an **async** iterator allowing to read through the encoder data using for-await...of loops
       */
      [Symbol.asyncIterator]() {
        return this.encode();
      }
    };
    _CRLF = /* @__PURE__ */ new WeakMap();
    _CRLF_BYTES = /* @__PURE__ */ new WeakMap();
    _CRLF_BYTES_LENGTH = /* @__PURE__ */ new WeakMap();
    _DASHES = /* @__PURE__ */ new WeakMap();
    _encoder = /* @__PURE__ */ new WeakMap();
    _footer = /* @__PURE__ */ new WeakMap();
    _form = /* @__PURE__ */ new WeakMap();
    _options = /* @__PURE__ */ new WeakMap();
    _getFieldHeader = /* @__PURE__ */ new WeakSet();
    getFieldHeader_fn = function(name, value) {
      let header = "";
      header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`;
      header += `Content-Disposition: form-data; name="${escapeName(name)}"`;
      if (isFile(value)) {
        header += `; filename="${escapeName(value.name)}"${__privateGet(this, _CRLF)}`;
        header += `Content-Type: ${value.type || "application/octet-stream"}`;
      }
      if (__privateGet(this, _options).enableAdditionalHeaders === true) {
        const size4 = isFile(value) ? value.size : value.byteLength;
        if (size4 != null && !isNaN(size4)) {
          header += `${__privateGet(this, _CRLF)}Content-Length: ${size4}`;
        }
      }
      return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`);
    };
    _getContentLength = /* @__PURE__ */ new WeakSet();
    getContentLength_fn = function() {
      let length = 0;
      for (const [name, raw] of __privateGet(this, _form)) {
        const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode(
          normalizeValue2(raw)
        );
        const size4 = isFile(value) ? value.size : value.byteLength;
        if (size4 == null || isNaN(size4)) {
          return void 0;
        }
        length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name, value).byteLength;
        length += size4;
        length += __privateGet(this, _CRLF_BYTES_LENGTH);
      }
      return String(length + __privateGet(this, _footer).byteLength);
    };
  }
});

// node_modules/form-data/lib/browser.js
var require_browser6 = __commonJS({
  "node_modules/form-data/lib/browser.js"(exports, module2) {
    module2.exports = typeof self == "object" ? self.FormData : window.FormData;
  }
});

// node_modules/cohere-ai/core/form-data-utils/FormDataWrapper.js
var require_FormDataWrapper = __commonJS({
  "node_modules/cohere-ai/core/form-data-utils/FormDataWrapper.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WebFormData = exports.Node16FormData = exports.Node18FormData = exports.newFormData = void 0;
    var runtime_1 = require_runtime2();
    function isNamedValue(value) {
      return typeof value === "object" && value != null && "name" in value;
    }
    function newFormData() {
      return __awaiter6(this, void 0, void 0, function* () {
        let formdata;
        if (runtime_1.RUNTIME.type === "node" && runtime_1.RUNTIME.parsedVersion != null && runtime_1.RUNTIME.parsedVersion >= 18) {
          formdata = new Node18FormData();
        } else if (runtime_1.RUNTIME.type === "node") {
          formdata = new Node16FormData();
        } else {
          formdata = new WebFormData();
        }
        yield formdata.setup();
        return formdata;
      });
    }
    exports.newFormData = newFormData;
    var Node18FormData = class {
      setup() {
        return __awaiter6(this, void 0, void 0, function* () {
          this.fd = new (yield Promise.resolve().then(() => __importStar5(require_browser5()))).FormData();
        });
      }
      append(key, value) {
        var _a5;
        (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, value);
      }
      appendFile(key, value, fileName) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          if (fileName == null && isNamedValue(value)) {
            fileName = value.name;
          }
          if (value instanceof (yield Promise.resolve().then(() => __importStar5(require_browser3()))).Readable) {
            (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, {
              type: void 0,
              name: fileName,
              [Symbol.toStringTag]: "File",
              stream() {
                return value;
              }
            });
          } else {
            (_b = this.fd) === null || _b === void 0 ? void 0 : _b.append(key, value, fileName);
          }
        });
      }
      getRequest() {
        return __awaiter6(this, void 0, void 0, function* () {
          const encoder = new (yield Promise.resolve().then(() => __importStar5(require_lib2()))).FormDataEncoder(this.fd);
          return {
            body: yield (yield Promise.resolve().then(() => __importStar5(require_browser3()))).Readable.from(encoder),
            headers: encoder.headers,
            duplex: "half"
          };
        });
      }
    };
    exports.Node18FormData = Node18FormData;
    var Node16FormData = class {
      setup() {
        return __awaiter6(this, void 0, void 0, function* () {
          this.fd = new (yield Promise.resolve().then(() => __importStar5(require_browser6()))).default();
        });
      }
      append(key, value) {
        var _a5;
        (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, value);
      }
      appendFile(key, value, fileName) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          if (fileName == null && isNamedValue(value)) {
            fileName = value.name;
          }
          let bufferedValue;
          if (!(value instanceof (yield Promise.resolve().then(() => __importStar5(require_browser3()))).Readable)) {
            bufferedValue = Buffer.from(yield value.arrayBuffer());
          } else {
            bufferedValue = value;
          }
          if (fileName == null) {
            (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, bufferedValue);
          } else {
            (_b = this.fd) === null || _b === void 0 ? void 0 : _b.append(key, bufferedValue, { filename: fileName });
          }
        });
      }
      getRequest() {
        return {
          body: this.fd,
          headers: this.fd ? this.fd.getHeaders() : {}
        };
      }
    };
    exports.Node16FormData = Node16FormData;
    var WebFormData = class {
      setup() {
        return __awaiter6(this, void 0, void 0, function* () {
          this.fd = new FormData();
        });
      }
      append(key, value) {
        var _a5;
        (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, value);
      }
      appendFile(key, value, fileName) {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          if (fileName == null && isNamedValue(value)) {
            fileName = value.name;
          }
          (_a5 = this.fd) === null || _a5 === void 0 ? void 0 : _a5.append(key, new Blob([value]), fileName);
        });
      }
      getRequest() {
        return {
          body: this.fd,
          headers: {}
        };
      }
    };
    exports.WebFormData = WebFormData;
  }
});

// node_modules/cohere-ai/core/form-data-utils/index.js
var require_form_data_utils = __commonJS({
  "node_modules/cohere-ai/core/form-data-utils/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_FormDataWrapper(), exports);
  }
});

// node_modules/cohere-ai/core/schemas/Schema.js
var require_Schema = __commonJS({
  "node_modules/cohere-ai/core/schemas/Schema.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SchemaType = void 0;
    exports.SchemaType = {
      DATE: "date",
      ENUM: "enum",
      LIST: "list",
      STRING_LITERAL: "stringLiteral",
      BOOLEAN_LITERAL: "booleanLiteral",
      OBJECT: "object",
      ANY: "any",
      BOOLEAN: "boolean",
      NUMBER: "number",
      STRING: "string",
      UNKNOWN: "unknown",
      RECORD: "record",
      SET: "set",
      UNION: "union",
      UNDISCRIMINATED_UNION: "undiscriminatedUnion",
      OPTIONAL: "optional"
    };
  }
});

// node_modules/cohere-ai/core/schemas/utils/getErrorMessageForIncorrectType.js
var require_getErrorMessageForIncorrectType = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/getErrorMessageForIncorrectType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getErrorMessageForIncorrectType = void 0;
    function getErrorMessageForIncorrectType(value, expectedType) {
      return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`;
    }
    exports.getErrorMessageForIncorrectType = getErrorMessageForIncorrectType;
    function getTypeAsString(value) {
      if (Array.isArray(value)) {
        return "list";
      }
      if (value === null) {
        return "null";
      }
      switch (typeof value) {
        case "string":
          return `"${value}"`;
        case "number":
        case "boolean":
        case "undefined":
          return `${value}`;
      }
      return typeof value;
    }
  }
});

// node_modules/cohere-ai/core/schemas/utils/maybeSkipValidation.js
var require_maybeSkipValidation = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/maybeSkipValidation.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.maybeSkipValidation = void 0;
    function maybeSkipValidation(schema) {
      return Object.assign(Object.assign({}, schema), { json: transformAndMaybeSkipValidation(schema.json), parse: transformAndMaybeSkipValidation(schema.parse) });
    }
    exports.maybeSkipValidation = maybeSkipValidation;
    function transformAndMaybeSkipValidation(transform) {
      return (value, opts) => {
        const transformed = transform(value, opts);
        const { skipValidation = false } = opts !== null && opts !== void 0 ? opts : {};
        if (!transformed.ok && skipValidation) {
          console.warn([
            "Failed to validate.",
            ...transformed.errors.map((error) => "  - " + (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message))
          ].join("\n"));
          return {
            ok: true,
            value
          };
        } else {
          return transformed;
        }
      };
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/schema-utils/stringifyValidationErrors.js
var require_stringifyValidationErrors = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/schema-utils/stringifyValidationErrors.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.stringifyValidationError = void 0;
    function stringifyValidationError(error) {
      if (error.path.length === 0) {
        return error.message;
      }
      return `${error.path.join(" -> ")}: ${error.message}`;
    }
    exports.stringifyValidationError = stringifyValidationError;
  }
});

// node_modules/cohere-ai/core/schemas/builders/schema-utils/JsonError.js
var require_JsonError = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/schema-utils/JsonError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonError = void 0;
    var stringifyValidationErrors_1 = require_stringifyValidationErrors();
    var JsonError = class extends Error {
      constructor(errors2) {
        super(errors2.map(stringifyValidationErrors_1.stringifyValidationError).join("; "));
        this.errors = errors2;
        Object.setPrototypeOf(this, JsonError.prototype);
      }
    };
    exports.JsonError = JsonError;
  }
});

// node_modules/cohere-ai/core/schemas/builders/schema-utils/ParseError.js
var require_ParseError = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/schema-utils/ParseError.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParseError = void 0;
    var stringifyValidationErrors_1 = require_stringifyValidationErrors();
    var ParseError = class extends Error {
      constructor(errors2) {
        super(errors2.map(stringifyValidationErrors_1.stringifyValidationError).join("; "));
        this.errors = errors2;
        Object.setPrototypeOf(this, ParseError.prototype);
      }
    };
    exports.ParseError = ParseError;
  }
});

// node_modules/cohere-ai/core/schemas/builders/schema-utils/getSchemaUtils.js
var require_getSchemaUtils = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/schema-utils/getSchemaUtils.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.transform = exports.optional = exports.getSchemaUtils = void 0;
    var Schema_1 = require_Schema();
    var JsonError_1 = require_JsonError();
    var ParseError_1 = require_ParseError();
    function getSchemaUtils(schema) {
      return {
        optional: () => optional(schema),
        transform: (transformer) => transform(schema, transformer),
        parseOrThrow: (raw, opts) => {
          const parsed = schema.parse(raw, opts);
          if (parsed.ok) {
            return parsed.value;
          }
          throw new ParseError_1.ParseError(parsed.errors);
        },
        jsonOrThrow: (parsed, opts) => {
          const raw = schema.json(parsed, opts);
          if (raw.ok) {
            return raw.value;
          }
          throw new JsonError_1.JsonError(raw.errors);
        }
      };
    }
    exports.getSchemaUtils = getSchemaUtils;
    function optional(schema) {
      const baseSchema = {
        parse: (raw, opts) => {
          if (raw == null) {
            return {
              ok: true,
              value: void 0
            };
          }
          return schema.parse(raw, opts);
        },
        json: (parsed, opts) => {
          if ((opts === null || opts === void 0 ? void 0 : opts.omitUndefined) && parsed === void 0) {
            return {
              ok: true,
              value: void 0
            };
          }
          if (parsed == null) {
            return {
              ok: true,
              value: null
            };
          }
          return schema.json(parsed, opts);
        },
        getType: () => Schema_1.SchemaType.OPTIONAL
      };
      return Object.assign(Object.assign({}, baseSchema), getSchemaUtils(baseSchema));
    }
    exports.optional = optional;
    function transform(schema, transformer) {
      const baseSchema = {
        parse: (raw, opts) => {
          const parsed = schema.parse(raw, opts);
          if (!parsed.ok) {
            return parsed;
          }
          return {
            ok: true,
            value: transformer.transform(parsed.value)
          };
        },
        json: (transformed, opts) => {
          const parsed = transformer.untransform(transformed);
          return schema.json(parsed, opts);
        },
        getType: () => schema.getType()
      };
      return Object.assign(Object.assign({}, baseSchema), getSchemaUtils(baseSchema));
    }
    exports.transform = transform;
  }
});

// node_modules/cohere-ai/core/schemas/builders/schema-utils/index.js
var require_schema_utils = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/schema-utils/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParseError = exports.JsonError = exports.transform = exports.optional = exports.getSchemaUtils = void 0;
    var getSchemaUtils_1 = require_getSchemaUtils();
    Object.defineProperty(exports, "getSchemaUtils", { enumerable: true, get: function() {
      return getSchemaUtils_1.getSchemaUtils;
    } });
    Object.defineProperty(exports, "optional", { enumerable: true, get: function() {
      return getSchemaUtils_1.optional;
    } });
    Object.defineProperty(exports, "transform", { enumerable: true, get: function() {
      return getSchemaUtils_1.transform;
    } });
    var JsonError_1 = require_JsonError();
    Object.defineProperty(exports, "JsonError", { enumerable: true, get: function() {
      return JsonError_1.JsonError;
    } });
    var ParseError_1 = require_ParseError();
    Object.defineProperty(exports, "ParseError", { enumerable: true, get: function() {
      return ParseError_1.ParseError;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/date/date.js
var require_date = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/date/date.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.date = void 0;
    var Schema_1 = require_Schema();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var schema_utils_1 = require_schema_utils();
    var ISO_8601_REGEX = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
    function date2() {
      const baseSchema = {
        parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
          if (typeof raw !== "string") {
            return {
              ok: false,
              errors: [
                {
                  path: breadcrumbsPrefix,
                  message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(raw, "string")
                }
              ]
            };
          }
          if (!ISO_8601_REGEX.test(raw)) {
            return {
              ok: false,
              errors: [
                {
                  path: breadcrumbsPrefix,
                  message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(raw, "ISO 8601 date string")
                }
              ]
            };
          }
          return {
            ok: true,
            value: new Date(raw)
          };
        },
        json: (date3, { breadcrumbsPrefix = [] } = {}) => {
          if (date3 instanceof Date) {
            return {
              ok: true,
              value: date3.toISOString()
            };
          } else {
            return {
              ok: false,
              errors: [
                {
                  path: breadcrumbsPrefix,
                  message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(date3, "Date object")
                }
              ]
            };
          }
        },
        getType: () => Schema_1.SchemaType.DATE
      };
      return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.date = date2;
  }
});

// node_modules/cohere-ai/core/schemas/builders/date/index.js
var require_date2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/date/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.date = void 0;
    var date_1 = require_date();
    Object.defineProperty(exports, "date", { enumerable: true, get: function() {
      return date_1.date;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/utils/createIdentitySchemaCreator.js
var require_createIdentitySchemaCreator = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/createIdentitySchemaCreator.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createIdentitySchemaCreator = void 0;
    var schema_utils_1 = require_schema_utils();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    function createIdentitySchemaCreator(schemaType, validate5) {
      return () => {
        const baseSchema = {
          parse: validate5,
          json: validate5,
          getType: () => schemaType
        };
        return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
      };
    }
    exports.createIdentitySchemaCreator = createIdentitySchemaCreator;
  }
});

// node_modules/cohere-ai/core/schemas/builders/enum/enum.js
var require_enum = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/enum/enum.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.enum_ = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    function enum_(values) {
      const validValues = new Set(values);
      const schemaCreator = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.ENUM, (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => {
        if (typeof value !== "string") {
          return {
            ok: false,
            errors: [
              {
                path: breadcrumbsPrefix,
                message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "string")
              }
            ]
          };
        }
        if (!validValues.has(value) && !allowUnrecognizedEnumValues) {
          return {
            ok: false,
            errors: [
              {
                path: breadcrumbsPrefix,
                message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "enum")
              }
            ]
          };
        }
        return {
          ok: true,
          value
        };
      });
      return schemaCreator();
    }
    exports.enum_ = enum_;
  }
});

// node_modules/cohere-ai/core/schemas/builders/enum/index.js
var require_enum2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/enum/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.enum_ = void 0;
    var enum_1 = require_enum();
    Object.defineProperty(exports, "enum_", { enumerable: true, get: function() {
      return enum_1.enum_;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/lazy/lazy.js
var require_lazy = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/lazy/lazy.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getMemoizedSchema = exports.constructLazyBaseSchema = exports.lazy = void 0;
    var schema_utils_1 = require_schema_utils();
    function lazy(getter) {
      const baseSchema = constructLazyBaseSchema(getter);
      return Object.assign(Object.assign({}, baseSchema), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.lazy = lazy;
    function constructLazyBaseSchema(getter) {
      return {
        parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts),
        json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts),
        getType: () => getMemoizedSchema(getter).getType()
      };
    }
    exports.constructLazyBaseSchema = constructLazyBaseSchema;
    function getMemoizedSchema(getter) {
      const castedGetter = getter;
      if (castedGetter.__zurg_memoized == null) {
        castedGetter.__zurg_memoized = getter();
      }
      return castedGetter.__zurg_memoized;
    }
    exports.getMemoizedSchema = getMemoizedSchema;
  }
});

// node_modules/cohere-ai/core/schemas/utils/entries.js
var require_entries = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/entries.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.entries = void 0;
    function entries(object) {
      return Object.entries(object);
    }
    exports.entries = entries;
  }
});

// node_modules/cohere-ai/core/schemas/utils/filterObject.js
var require_filterObject = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/filterObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.filterObject = void 0;
    function filterObject(obj, keysToInclude) {
      const keysToIncludeSet = new Set(keysToInclude);
      return Object.entries(obj).reduce((acc, [key, value]) => {
        if (keysToIncludeSet.has(key)) {
          acc[key] = value;
        }
        return acc;
      }, {});
    }
    exports.filterObject = filterObject;
  }
});

// node_modules/cohere-ai/core/schemas/utils/isPlainObject.js
var require_isPlainObject = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/isPlainObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isPlainObject = void 0;
    function isPlainObject(value) {
      if (typeof value !== "object" || value === null) {
        return false;
      }
      if (Object.getPrototypeOf(value) === null) {
        return true;
      }
      let proto = value;
      while (Object.getPrototypeOf(proto) !== null) {
        proto = Object.getPrototypeOf(proto);
      }
      return Object.getPrototypeOf(value) === proto;
    }
    exports.isPlainObject = isPlainObject;
  }
});

// node_modules/cohere-ai/core/schemas/utils/keys.js
var require_keys = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/keys.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.keys = void 0;
    function keys(object) {
      return Object.keys(object);
    }
    exports.keys = keys;
  }
});

// node_modules/cohere-ai/core/schemas/utils/partition.js
var require_partition = __commonJS({
  "node_modules/cohere-ai/core/schemas/utils/partition.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.partition = void 0;
    function partition5(items, predicate) {
      const trueItems = [], falseItems = [];
      for (const item of items) {
        if (predicate(item)) {
          trueItems.push(item);
        } else {
          falseItems.push(item);
        }
      }
      return [trueItems, falseItems];
    }
    exports.partition = partition5;
  }
});

// node_modules/cohere-ai/core/schemas/builders/object-like/getObjectLikeUtils.js
var require_getObjectLikeUtils = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object-like/getObjectLikeUtils.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.withParsedProperties = exports.getObjectLikeUtils = void 0;
    var filterObject_1 = require_filterObject();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var isPlainObject_1 = require_isPlainObject();
    var schema_utils_1 = require_schema_utils();
    function getObjectLikeUtils(schema) {
      return {
        withParsedProperties: (properties) => withParsedProperties(schema, properties)
      };
    }
    exports.getObjectLikeUtils = getObjectLikeUtils;
    function withParsedProperties(objectLike, properties) {
      const objectSchema = {
        parse: (raw, opts) => {
          const parsedObject = objectLike.parse(raw, opts);
          if (!parsedObject.ok) {
            return parsedObject;
          }
          const additionalProperties = Object.entries(properties).reduce((processed, [key, value]) => {
            return Object.assign(Object.assign({}, processed), { [key]: typeof value === "function" ? value(parsedObject.value) : value });
          }, {});
          return {
            ok: true,
            value: Object.assign(Object.assign({}, parsedObject.value), additionalProperties)
          };
        },
        json: (parsed, opts) => {
          var _a5;
          if (!(0, isPlainObject_1.isPlainObject)(parsed)) {
            return {
              ok: false,
              errors: [
                {
                  path: (_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [],
                  message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(parsed, "object")
                }
              ]
            };
          }
          const addedPropertyKeys = new Set(Object.keys(properties));
          const parsedWithoutAddedProperties = (0, filterObject_1.filterObject)(parsed, Object.keys(parsed).filter((key) => !addedPropertyKeys.has(key)));
          return objectLike.json(parsedWithoutAddedProperties, opts);
        },
        getType: () => objectLike.getType()
      };
      return Object.assign(Object.assign(Object.assign({}, objectSchema), (0, schema_utils_1.getSchemaUtils)(objectSchema)), getObjectLikeUtils(objectSchema));
    }
    exports.withParsedProperties = withParsedProperties;
  }
});

// node_modules/cohere-ai/core/schemas/builders/object-like/index.js
var require_object_like = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object-like/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.withParsedProperties = exports.getObjectLikeUtils = void 0;
    var getObjectLikeUtils_1 = require_getObjectLikeUtils();
    Object.defineProperty(exports, "getObjectLikeUtils", { enumerable: true, get: function() {
      return getObjectLikeUtils_1.getObjectLikeUtils;
    } });
    Object.defineProperty(exports, "withParsedProperties", { enumerable: true, get: function() {
      return getObjectLikeUtils_1.withParsedProperties;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/object/property.js
var require_property = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object/property.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isProperty = exports.property = void 0;
    function property(rawKey, valueSchema) {
      return {
        rawKey,
        valueSchema,
        isProperty: true
      };
    }
    exports.property = property;
    function isProperty(maybeProperty) {
      return maybeProperty.isProperty;
    }
    exports.isProperty = isProperty;
  }
});

// node_modules/cohere-ai/core/schemas/builders/object/object.js
var require_object = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object/object.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getObjectUtils = exports.object = void 0;
    var Schema_1 = require_Schema();
    var entries_1 = require_entries();
    var filterObject_1 = require_filterObject();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var isPlainObject_1 = require_isPlainObject();
    var keys_1 = require_keys();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var partition_1 = require_partition();
    var object_like_1 = require_object_like();
    var schema_utils_1 = require_schema_utils();
    var property_1 = require_property();
    function object(schemas) {
      const baseSchema = {
        _getRawProperties: () => Object.entries(schemas).map(([parsedKey, propertySchema]) => (0, property_1.isProperty)(propertySchema) ? propertySchema.rawKey : parsedKey),
        _getParsedProperties: () => (0, keys_1.keys)(schemas),
        parse: (raw, opts) => {
          const rawKeyToProperty = {};
          const requiredKeys = [];
          for (const [parsedKey, schemaOrObjectProperty] of (0, entries_1.entries)(schemas)) {
            const rawKey = (0, property_1.isProperty)(schemaOrObjectProperty) ? schemaOrObjectProperty.rawKey : parsedKey;
            const valueSchema = (0, property_1.isProperty)(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
            const property = {
              rawKey,
              parsedKey,
              valueSchema
            };
            rawKeyToProperty[rawKey] = property;
            if (isSchemaRequired(valueSchema)) {
              requiredKeys.push(rawKey);
            }
          }
          return validateAndTransformObject({
            value: raw,
            requiredKeys,
            getProperty: (rawKey) => {
              const property = rawKeyToProperty[rawKey];
              if (property == null) {
                return void 0;
              }
              return {
                transformedKey: property.parsedKey,
                transform: (propertyValue) => {
                  var _a5;
                  return property.valueSchema.parse(propertyValue, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], rawKey] }));
                }
              };
            },
            unrecognizedObjectKeys: opts === null || opts === void 0 ? void 0 : opts.unrecognizedObjectKeys,
            skipValidation: opts === null || opts === void 0 ? void 0 : opts.skipValidation,
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix,
            omitUndefined: opts === null || opts === void 0 ? void 0 : opts.omitUndefined
          });
        },
        json: (parsed, opts) => {
          const requiredKeys = [];
          for (const [parsedKey, schemaOrObjectProperty] of (0, entries_1.entries)(schemas)) {
            const valueSchema = (0, property_1.isProperty)(schemaOrObjectProperty) ? schemaOrObjectProperty.valueSchema : schemaOrObjectProperty;
            if (isSchemaRequired(valueSchema)) {
              requiredKeys.push(parsedKey);
            }
          }
          return validateAndTransformObject({
            value: parsed,
            requiredKeys,
            getProperty: (parsedKey) => {
              const property = schemas[parsedKey];
              if (property == null) {
                return void 0;
              }
              if ((0, property_1.isProperty)(property)) {
                return {
                  transformedKey: property.rawKey,
                  transform: (propertyValue) => {
                    var _a5;
                    return property.valueSchema.json(propertyValue, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], parsedKey] }));
                  }
                };
              } else {
                return {
                  transformedKey: parsedKey,
                  transform: (propertyValue) => {
                    var _a5;
                    return property.json(propertyValue, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], parsedKey] }));
                  }
                };
              }
            },
            unrecognizedObjectKeys: opts === null || opts === void 0 ? void 0 : opts.unrecognizedObjectKeys,
            skipValidation: opts === null || opts === void 0 ? void 0 : opts.skipValidation,
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix,
            omitUndefined: opts === null || opts === void 0 ? void 0 : opts.omitUndefined
          });
        },
        getType: () => Schema_1.SchemaType.OBJECT
      };
      return Object.assign(Object.assign(Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema)), (0, object_like_1.getObjectLikeUtils)(baseSchema)), getObjectUtils(baseSchema));
    }
    exports.object = object;
    function validateAndTransformObject({ value, requiredKeys, getProperty, unrecognizedObjectKeys = "fail", skipValidation = false, breadcrumbsPrefix = [] }) {
      if (!(0, isPlainObject_1.isPlainObject)(value)) {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "object")
            }
          ]
        };
      }
      const missingRequiredKeys = new Set(requiredKeys);
      const errors2 = [];
      const transformed = {};
      for (const [preTransformedKey, preTransformedItemValue] of Object.entries(value)) {
        const property = getProperty(preTransformedKey);
        if (property != null) {
          missingRequiredKeys.delete(preTransformedKey);
          const value2 = property.transform(preTransformedItemValue);
          if (value2.ok) {
            transformed[property.transformedKey] = value2.value;
          } else {
            transformed[preTransformedKey] = preTransformedItemValue;
            errors2.push(...value2.errors);
          }
        } else {
          switch (unrecognizedObjectKeys) {
            case "fail":
              errors2.push({
                path: [...breadcrumbsPrefix, preTransformedKey],
                message: `Unexpected key "${preTransformedKey}"`
              });
              break;
            case "strip":
              break;
            case "passthrough":
              transformed[preTransformedKey] = preTransformedItemValue;
              break;
          }
        }
      }
      errors2.push(...requiredKeys.filter((key) => missingRequiredKeys.has(key)).map((key) => ({
        path: breadcrumbsPrefix,
        message: `Missing required key "${key}"`
      })));
      if (errors2.length === 0 || skipValidation) {
        return {
          ok: true,
          value: transformed
        };
      } else {
        return {
          ok: false,
          errors: errors2
        };
      }
    }
    function getObjectUtils(schema) {
      return {
        extend: (extension) => {
          const baseSchema = {
            _getParsedProperties: () => [...schema._getParsedProperties(), ...extension._getParsedProperties()],
            _getRawProperties: () => [...schema._getRawProperties(), ...extension._getRawProperties()],
            parse: (raw, opts) => {
              return validateAndTransformExtendedObject({
                extensionKeys: extension._getRawProperties(),
                value: raw,
                transformBase: (rawBase) => schema.parse(rawBase, opts),
                transformExtension: (rawExtension) => extension.parse(rawExtension, opts)
              });
            },
            json: (parsed, opts) => {
              return validateAndTransformExtendedObject({
                extensionKeys: extension._getParsedProperties(),
                value: parsed,
                transformBase: (parsedBase) => schema.json(parsedBase, opts),
                transformExtension: (parsedExtension) => extension.json(parsedExtension, opts)
              });
            },
            getType: () => Schema_1.SchemaType.OBJECT
          };
          return Object.assign(Object.assign(Object.assign(Object.assign({}, baseSchema), (0, schema_utils_1.getSchemaUtils)(baseSchema)), (0, object_like_1.getObjectLikeUtils)(baseSchema)), getObjectUtils(baseSchema));
        }
      };
    }
    exports.getObjectUtils = getObjectUtils;
    function validateAndTransformExtendedObject({ extensionKeys, value, transformBase, transformExtension }) {
      const extensionPropertiesSet = new Set(extensionKeys);
      const [extensionProperties, baseProperties] = (0, partition_1.partition)((0, keys_1.keys)(value), (key) => extensionPropertiesSet.has(key));
      const transformedBase = transformBase((0, filterObject_1.filterObject)(value, baseProperties));
      const transformedExtension = transformExtension((0, filterObject_1.filterObject)(value, extensionProperties));
      if (transformedBase.ok && transformedExtension.ok) {
        return {
          ok: true,
          value: Object.assign(Object.assign({}, transformedBase.value), transformedExtension.value)
        };
      } else {
        return {
          ok: false,
          errors: [
            ...transformedBase.ok ? [] : transformedBase.errors,
            ...transformedExtension.ok ? [] : transformedExtension.errors
          ]
        };
      }
    }
    function isSchemaRequired(schema) {
      return !isSchemaOptional(schema);
    }
    function isSchemaOptional(schema) {
      switch (schema.getType()) {
        case Schema_1.SchemaType.ANY:
        case Schema_1.SchemaType.UNKNOWN:
        case Schema_1.SchemaType.OPTIONAL:
          return true;
        default:
          return false;
      }
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/object/objectWithoutOptionalProperties.js
var require_objectWithoutOptionalProperties = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object/objectWithoutOptionalProperties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.objectWithoutOptionalProperties = void 0;
    var object_1 = require_object();
    function objectWithoutOptionalProperties(schemas) {
      return (0, object_1.object)(schemas);
    }
    exports.objectWithoutOptionalProperties = objectWithoutOptionalProperties;
  }
});

// node_modules/cohere-ai/core/schemas/builders/object/index.js
var require_object2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/object/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.property = exports.isProperty = exports.objectWithoutOptionalProperties = exports.object = exports.getObjectUtils = void 0;
    var object_1 = require_object();
    Object.defineProperty(exports, "getObjectUtils", { enumerable: true, get: function() {
      return object_1.getObjectUtils;
    } });
    Object.defineProperty(exports, "object", { enumerable: true, get: function() {
      return object_1.object;
    } });
    var objectWithoutOptionalProperties_1 = require_objectWithoutOptionalProperties();
    Object.defineProperty(exports, "objectWithoutOptionalProperties", { enumerable: true, get: function() {
      return objectWithoutOptionalProperties_1.objectWithoutOptionalProperties;
    } });
    var property_1 = require_property();
    Object.defineProperty(exports, "isProperty", { enumerable: true, get: function() {
      return property_1.isProperty;
    } });
    Object.defineProperty(exports, "property", { enumerable: true, get: function() {
      return property_1.property;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/lazy/lazyObject.js
var require_lazyObject = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/lazy/lazyObject.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.lazyObject = void 0;
    var object_1 = require_object2();
    var object_like_1 = require_object_like();
    var schema_utils_1 = require_schema_utils();
    var lazy_1 = require_lazy();
    function lazyObject(getter) {
      const baseSchema = Object.assign(Object.assign({}, (0, lazy_1.constructLazyBaseSchema)(getter)), { _getRawProperties: () => (0, lazy_1.getMemoizedSchema)(getter)._getRawProperties(), _getParsedProperties: () => (0, lazy_1.getMemoizedSchema)(getter)._getParsedProperties() });
      return Object.assign(Object.assign(Object.assign(Object.assign({}, baseSchema), (0, schema_utils_1.getSchemaUtils)(baseSchema)), (0, object_like_1.getObjectLikeUtils)(baseSchema)), (0, object_1.getObjectUtils)(baseSchema));
    }
    exports.lazyObject = lazyObject;
  }
});

// node_modules/cohere-ai/core/schemas/builders/lazy/index.js
var require_lazy2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/lazy/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.lazyObject = exports.lazy = void 0;
    var lazy_1 = require_lazy();
    Object.defineProperty(exports, "lazy", { enumerable: true, get: function() {
      return lazy_1.lazy;
    } });
    var lazyObject_1 = require_lazyObject();
    Object.defineProperty(exports, "lazyObject", { enumerable: true, get: function() {
      return lazyObject_1.lazyObject;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/list/list.js
var require_list = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/list/list.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.list = void 0;
    var Schema_1 = require_Schema();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var schema_utils_1 = require_schema_utils();
    function list(schema) {
      const baseSchema = {
        parse: (raw, opts) => validateAndTransformArray(raw, (item, index2) => {
          var _a5;
          return schema.parse(item, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `[${index2}]`] }));
        }),
        json: (parsed, opts) => validateAndTransformArray(parsed, (item, index2) => {
          var _a5;
          return schema.json(item, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `[${index2}]`] }));
        }),
        getType: () => Schema_1.SchemaType.LIST
      };
      return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.list = list;
    function validateAndTransformArray(value, transformItem) {
      if (!Array.isArray(value)) {
        return {
          ok: false,
          errors: [
            {
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "list"),
              path: []
            }
          ]
        };
      }
      const maybeValidItems = value.map((item, index2) => transformItem(item, index2));
      return maybeValidItems.reduce((acc, item) => {
        if (acc.ok && item.ok) {
          return {
            ok: true,
            value: [...acc.value, item.value]
          };
        }
        const errors2 = [];
        if (!acc.ok) {
          errors2.push(...acc.errors);
        }
        if (!item.ok) {
          errors2.push(...item.errors);
        }
        return {
          ok: false,
          errors: errors2
        };
      }, { ok: true, value: [] });
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/list/index.js
var require_list2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/list/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.list = void 0;
    var list_1 = require_list();
    Object.defineProperty(exports, "list", { enumerable: true, get: function() {
      return list_1.list;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/literals/stringLiteral.js
var require_stringLiteral = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/literals/stringLiteral.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.stringLiteral = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    function stringLiteral(literal) {
      const schemaCreator = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.STRING_LITERAL, (value, { breadcrumbsPrefix = [] } = {}) => {
        if (value === literal) {
          return {
            ok: true,
            value: literal
          };
        } else {
          return {
            ok: false,
            errors: [
              {
                path: breadcrumbsPrefix,
                message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, `"${literal}"`)
              }
            ]
          };
        }
      });
      return schemaCreator();
    }
    exports.stringLiteral = stringLiteral;
  }
});

// node_modules/cohere-ai/core/schemas/builders/literals/booleanLiteral.js
var require_booleanLiteral = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/literals/booleanLiteral.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.booleanLiteral = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    function booleanLiteral(literal) {
      const schemaCreator = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.BOOLEAN_LITERAL, (value, { breadcrumbsPrefix = [] } = {}) => {
        if (value === literal) {
          return {
            ok: true,
            value: literal
          };
        } else {
          return {
            ok: false,
            errors: [
              {
                path: breadcrumbsPrefix,
                message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, `${literal.toString()}`)
              }
            ]
          };
        }
      });
      return schemaCreator();
    }
    exports.booleanLiteral = booleanLiteral;
  }
});

// node_modules/cohere-ai/core/schemas/builders/literals/index.js
var require_literals = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/literals/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.booleanLiteral = exports.stringLiteral = void 0;
    var stringLiteral_1 = require_stringLiteral();
    Object.defineProperty(exports, "stringLiteral", { enumerable: true, get: function() {
      return stringLiteral_1.stringLiteral;
    } });
    var booleanLiteral_1 = require_booleanLiteral();
    Object.defineProperty(exports, "booleanLiteral", { enumerable: true, get: function() {
      return booleanLiteral_1.booleanLiteral;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/any.js
var require_any = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/any.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.any = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    exports.any = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.ANY, (value) => ({ ok: true, value }));
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/boolean.js
var require_boolean = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/boolean.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.boolean = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    exports.boolean = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.BOOLEAN, (value, { breadcrumbsPrefix = [] } = {}) => {
      if (typeof value === "boolean") {
        return {
          ok: true,
          value
        };
      } else {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "boolean")
            }
          ]
        };
      }
    });
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/number.js
var require_number = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/number.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.number = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    exports.number = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.NUMBER, (value, { breadcrumbsPrefix = [] } = {}) => {
      if (typeof value === "number") {
        return {
          ok: true,
          value
        };
      } else {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "number")
            }
          ]
        };
      }
    });
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/string.js
var require_string = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/string.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.string = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    exports.string = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.STRING, (value, { breadcrumbsPrefix = [] } = {}) => {
      if (typeof value === "string") {
        return {
          ok: true,
          value
        };
      } else {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "string")
            }
          ]
        };
      }
    });
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/unknown.js
var require_unknown = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/unknown.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.unknown = void 0;
    var Schema_1 = require_Schema();
    var createIdentitySchemaCreator_1 = require_createIdentitySchemaCreator();
    exports.unknown = (0, createIdentitySchemaCreator_1.createIdentitySchemaCreator)(Schema_1.SchemaType.UNKNOWN, (value) => ({ ok: true, value }));
  }
});

// node_modules/cohere-ai/core/schemas/builders/primitives/index.js
var require_primitives = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/primitives/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.unknown = exports.string = exports.number = exports.boolean = exports.any = void 0;
    var any_1 = require_any();
    Object.defineProperty(exports, "any", { enumerable: true, get: function() {
      return any_1.any;
    } });
    var boolean_1 = require_boolean();
    Object.defineProperty(exports, "boolean", { enumerable: true, get: function() {
      return boolean_1.boolean;
    } });
    var number_1 = require_number();
    Object.defineProperty(exports, "number", { enumerable: true, get: function() {
      return number_1.number;
    } });
    var string_1 = require_string();
    Object.defineProperty(exports, "string", { enumerable: true, get: function() {
      return string_1.string;
    } });
    var unknown_1 = require_unknown();
    Object.defineProperty(exports, "unknown", { enumerable: true, get: function() {
      return unknown_1.unknown;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/record/record.js
var require_record = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/record/record.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.record = void 0;
    var Schema_1 = require_Schema();
    var entries_1 = require_entries();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var isPlainObject_1 = require_isPlainObject();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var schema_utils_1 = require_schema_utils();
    function record(keySchema, valueSchema) {
      const baseSchema = {
        parse: (raw, opts) => {
          return validateAndTransformRecord({
            value: raw,
            isKeyNumeric: keySchema.getType() === Schema_1.SchemaType.NUMBER,
            transformKey: (key) => {
              var _a5;
              return keySchema.parse(key, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `${key} (key)`] }));
            },
            transformValue: (value, key) => {
              var _a5;
              return valueSchema.parse(value, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `${key}`] }));
            },
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix
          });
        },
        json: (parsed, opts) => {
          return validateAndTransformRecord({
            value: parsed,
            isKeyNumeric: keySchema.getType() === Schema_1.SchemaType.NUMBER,
            transformKey: (key) => {
              var _a5;
              return keySchema.json(key, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `${key} (key)`] }));
            },
            transformValue: (value, key) => {
              var _a5;
              return valueSchema.json(value, Object.assign(Object.assign({}, opts), { breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], `${key}`] }));
            },
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix
          });
        },
        getType: () => Schema_1.SchemaType.RECORD
      };
      return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.record = record;
    function validateAndTransformRecord({ value, isKeyNumeric, transformKey, transformValue, breadcrumbsPrefix = [] }) {
      if (!(0, isPlainObject_1.isPlainObject)(value)) {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "object")
            }
          ]
        };
      }
      return (0, entries_1.entries)(value).reduce((accPromise, [stringKey, value2]) => {
        if (value2 == null) {
          return accPromise;
        }
        const acc = accPromise;
        let key = stringKey;
        if (isKeyNumeric) {
          const numberKey = stringKey.length > 0 ? Number(stringKey) : NaN;
          if (!isNaN(numberKey)) {
            key = numberKey;
          }
        }
        const transformedKey = transformKey(key);
        const transformedValue = transformValue(value2, key);
        if (acc.ok && transformedKey.ok && transformedValue.ok) {
          return {
            ok: true,
            value: Object.assign(Object.assign({}, acc.value), { [transformedKey.value]: transformedValue.value })
          };
        }
        const errors2 = [];
        if (!acc.ok) {
          errors2.push(...acc.errors);
        }
        if (!transformedKey.ok) {
          errors2.push(...transformedKey.errors);
        }
        if (!transformedValue.ok) {
          errors2.push(...transformedValue.errors);
        }
        return {
          ok: false,
          errors: errors2
        };
      }, { ok: true, value: {} });
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/record/index.js
var require_record2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/record/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.record = void 0;
    var record_1 = require_record();
    Object.defineProperty(exports, "record", { enumerable: true, get: function() {
      return record_1.record;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/set/set.js
var require_set = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/set/set.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.set = void 0;
    var Schema_1 = require_Schema();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var list_1 = require_list2();
    var schema_utils_1 = require_schema_utils();
    function set(schema) {
      const listSchema = (0, list_1.list)(schema);
      const baseSchema = {
        parse: (raw, opts) => {
          const parsedList = listSchema.parse(raw, opts);
          if (parsedList.ok) {
            return {
              ok: true,
              value: new Set(parsedList.value)
            };
          } else {
            return parsedList;
          }
        },
        json: (parsed, opts) => {
          var _a5;
          if (!(parsed instanceof Set)) {
            return {
              ok: false,
              errors: [
                {
                  path: (_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [],
                  message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(parsed, "Set")
                }
              ]
            };
          }
          const jsonList = listSchema.json([...parsed], opts);
          return jsonList;
        },
        getType: () => Schema_1.SchemaType.SET
      };
      return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.set = set;
  }
});

// node_modules/cohere-ai/core/schemas/builders/set/index.js
var require_set2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/set/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.set = void 0;
    var set_1 = require_set();
    Object.defineProperty(exports, "set", { enumerable: true, get: function() {
      return set_1.set;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.js
var require_undiscriminatedUnion = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.undiscriminatedUnion = void 0;
    var Schema_1 = require_Schema();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var schema_utils_1 = require_schema_utils();
    function undiscriminatedUnion(schemas) {
      const baseSchema = {
        parse: (raw, opts) => {
          return validateAndTransformUndiscriminatedUnion((schema, opts2) => schema.parse(raw, opts2), schemas, opts);
        },
        json: (parsed, opts) => {
          return validateAndTransformUndiscriminatedUnion((schema, opts2) => schema.json(parsed, opts2), schemas, opts);
        },
        getType: () => Schema_1.SchemaType.UNDISCRIMINATED_UNION
      };
      return Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema));
    }
    exports.undiscriminatedUnion = undiscriminatedUnion;
    function validateAndTransformUndiscriminatedUnion(transform, schemas, opts) {
      const errors2 = [];
      for (const [index2, schema] of schemas.entries()) {
        const transformed = transform(schema, Object.assign(Object.assign({}, opts), { skipValidation: false }));
        if (transformed.ok) {
          return transformed;
        } else {
          for (const error of transformed.errors) {
            errors2.push({
              path: error.path,
              message: `[Variant ${index2}] ${error.message}`
            });
          }
        }
      }
      return {
        ok: false,
        errors: errors2
      };
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/undiscriminated-union/index.js
var require_undiscriminated_union = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/undiscriminated-union/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.undiscriminatedUnion = void 0;
    var undiscriminatedUnion_1 = require_undiscriminatedUnion();
    Object.defineProperty(exports, "undiscriminatedUnion", { enumerable: true, get: function() {
      return undiscriminatedUnion_1.undiscriminatedUnion;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/union/discriminant.js
var require_discriminant = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/union/discriminant.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.discriminant = void 0;
    function discriminant(parsedDiscriminant, rawDiscriminant) {
      return {
        parsedDiscriminant,
        rawDiscriminant
      };
    }
    exports.discriminant = discriminant;
  }
});

// node_modules/cohere-ai/core/schemas/builders/union/union.js
var require_union = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/union/union.js"(exports) {
    "use strict";
    var __rest6 = exports && exports.__rest || function(s4, e3) {
      var t3 = {};
      for (var p3 in s4)
        if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
          t3[p3] = s4[p3];
      if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
          if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
            t3[p3[i3]] = s4[p3[i3]];
        }
      return t3;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.union = void 0;
    var Schema_1 = require_Schema();
    var getErrorMessageForIncorrectType_1 = require_getErrorMessageForIncorrectType();
    var isPlainObject_1 = require_isPlainObject();
    var keys_1 = require_keys();
    var maybeSkipValidation_1 = require_maybeSkipValidation();
    var enum_1 = require_enum2();
    var object_like_1 = require_object_like();
    var schema_utils_1 = require_schema_utils();
    function union(discriminant, union2) {
      const rawDiscriminant = typeof discriminant === "string" ? discriminant : discriminant.rawDiscriminant;
      const parsedDiscriminant = typeof discriminant === "string" ? discriminant : discriminant.parsedDiscriminant;
      const discriminantValueSchema = (0, enum_1.enum_)((0, keys_1.keys)(union2));
      const baseSchema = {
        parse: (raw, opts) => {
          return transformAndValidateUnion({
            value: raw,
            discriminant: rawDiscriminant,
            transformedDiscriminant: parsedDiscriminant,
            transformDiscriminantValue: (discriminantValue) => {
              var _a5;
              return discriminantValueSchema.parse(discriminantValue, {
                allowUnrecognizedEnumValues: opts === null || opts === void 0 ? void 0 : opts.allowUnrecognizedUnionMembers,
                breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], rawDiscriminant]
              });
            },
            getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
            allowUnrecognizedUnionMembers: opts === null || opts === void 0 ? void 0 : opts.allowUnrecognizedUnionMembers,
            transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.parse(additionalProperties, opts),
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix
          });
        },
        json: (parsed, opts) => {
          return transformAndValidateUnion({
            value: parsed,
            discriminant: parsedDiscriminant,
            transformedDiscriminant: rawDiscriminant,
            transformDiscriminantValue: (discriminantValue) => {
              var _a5;
              return discriminantValueSchema.json(discriminantValue, {
                allowUnrecognizedEnumValues: opts === null || opts === void 0 ? void 0 : opts.allowUnrecognizedUnionMembers,
                breadcrumbsPrefix: [...(_a5 = opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix) !== null && _a5 !== void 0 ? _a5 : [], parsedDiscriminant]
              });
            },
            getAdditionalPropertiesSchema: (discriminantValue) => union2[discriminantValue],
            allowUnrecognizedUnionMembers: opts === null || opts === void 0 ? void 0 : opts.allowUnrecognizedUnionMembers,
            transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) => additionalPropertiesSchema.json(additionalProperties, opts),
            breadcrumbsPrefix: opts === null || opts === void 0 ? void 0 : opts.breadcrumbsPrefix
          });
        },
        getType: () => Schema_1.SchemaType.UNION
      };
      return Object.assign(Object.assign(Object.assign({}, (0, maybeSkipValidation_1.maybeSkipValidation)(baseSchema)), (0, schema_utils_1.getSchemaUtils)(baseSchema)), (0, object_like_1.getObjectLikeUtils)(baseSchema));
    }
    exports.union = union;
    function transformAndValidateUnion({ value, discriminant, transformedDiscriminant, transformDiscriminantValue, getAdditionalPropertiesSchema, allowUnrecognizedUnionMembers = false, transformAdditionalProperties, breadcrumbsPrefix = [] }) {
      if (!(0, isPlainObject_1.isPlainObject)(value)) {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: (0, getErrorMessageForIncorrectType_1.getErrorMessageForIncorrectType)(value, "object")
            }
          ]
        };
      }
      const _a5 = value, _b = discriminant, discriminantValue = _a5[_b], additionalProperties = __rest6(_a5, [typeof _b === "symbol" ? _b : _b + ""]);
      if (discriminantValue == null) {
        return {
          ok: false,
          errors: [
            {
              path: breadcrumbsPrefix,
              message: `Missing discriminant ("${discriminant}")`
            }
          ]
        };
      }
      const transformedDiscriminantValue = transformDiscriminantValue(discriminantValue);
      if (!transformedDiscriminantValue.ok) {
        return {
          ok: false,
          errors: transformedDiscriminantValue.errors
        };
      }
      const additionalPropertiesSchema = getAdditionalPropertiesSchema(transformedDiscriminantValue.value);
      if (additionalPropertiesSchema == null) {
        if (allowUnrecognizedUnionMembers) {
          return {
            ok: true,
            value: Object.assign({ [transformedDiscriminant]: transformedDiscriminantValue.value }, additionalProperties)
          };
        } else {
          return {
            ok: false,
            errors: [
              {
                path: [...breadcrumbsPrefix, discriminant],
                message: "Unexpected discriminant value"
              }
            ]
          };
        }
      }
      const transformedAdditionalProperties = transformAdditionalProperties(additionalProperties, additionalPropertiesSchema);
      if (!transformedAdditionalProperties.ok) {
        return transformedAdditionalProperties;
      }
      return {
        ok: true,
        value: Object.assign({ [transformedDiscriminant]: discriminantValue }, transformedAdditionalProperties.value)
      };
    }
  }
});

// node_modules/cohere-ai/core/schemas/builders/union/index.js
var require_union2 = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/union/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.union = exports.discriminant = void 0;
    var discriminant_1 = require_discriminant();
    Object.defineProperty(exports, "discriminant", { enumerable: true, get: function() {
      return discriminant_1.discriminant;
    } });
    var union_1 = require_union();
    Object.defineProperty(exports, "union", { enumerable: true, get: function() {
      return union_1.union;
    } });
  }
});

// node_modules/cohere-ai/core/schemas/builders/index.js
var require_builders = __commonJS({
  "node_modules/cohere-ai/core/schemas/builders/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_date2(), exports);
    __exportStar5(require_enum2(), exports);
    __exportStar5(require_lazy2(), exports);
    __exportStar5(require_list2(), exports);
    __exportStar5(require_literals(), exports);
    __exportStar5(require_object2(), exports);
    __exportStar5(require_object_like(), exports);
    __exportStar5(require_primitives(), exports);
    __exportStar5(require_record2(), exports);
    __exportStar5(require_schema_utils(), exports);
    __exportStar5(require_set2(), exports);
    __exportStar5(require_undiscriminated_union(), exports);
    __exportStar5(require_union2(), exports);
  }
});

// node_modules/cohere-ai/core/schemas/index.js
var require_schemas = __commonJS({
  "node_modules/cohere-ai/core/schemas/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_builders(), exports);
  }
});

// node_modules/cohere-ai/core/index.js
var require_core = __commonJS({
  "node_modules/cohere-ai/core/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.serialization = void 0;
    __exportStar5(require_fetcher(), exports);
    __exportStar5(require_auth2(), exports);
    __exportStar5(require_streaming_fetcher(), exports);
    __exportStar5(require_runtime2(), exports);
    __exportStar5(require_form_data_utils(), exports);
    exports.serialization = __importStar5(require_schemas());
  }
});

// node_modules/cohere-ai/core/streaming-fetcher/streaming-utils.js
var require_streaming_utils = __commonJS({
  "node_modules/cohere-ai/core/streaming-fetcher/streaming-utils.js"(exports) {
    "use strict";
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __asyncValues5 = exports && exports.__asyncValues || function(o3) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var m3 = o3[Symbol.asyncIterator], i3;
      return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3);
      function verb(n4) {
        i3[n4] = o3[n4] && function(v5) {
          return new Promise(function(resolve, reject) {
            v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
          });
        };
      }
      function settle(resolve, reject, d3, v5) {
        Promise.resolve(v5).then(function(v6) {
          resolve({ value: v6, done: d3 });
        }, reject);
      }
    };
    var __await6 = exports && exports.__await || function(v5) {
      return this instanceof __await6 ? (this.v = v5, this) : new __await6(v5);
    };
    var __asyncGenerator6 = exports && exports.__asyncGenerator || function(thisArg, _arguments, generator) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
      return i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3;
      function verb(n4) {
        if (g4[n4])
          i3[n4] = function(v5) {
            return new Promise(function(a3, b3) {
              q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
            });
          };
      }
      function resume(n4, v5) {
        try {
          step(g4[n4](v5));
        } catch (e3) {
          settle(q3[0][3], e3);
        }
      }
      function step(r4) {
        r4.value instanceof __await6 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
      }
      function fulfill(value) {
        resume("next", value);
      }
      function reject(value) {
        resume("throw", value);
      }
      function settle(f3, v5) {
        if (f3(v5), q3.shift(), q3.length)
          resume(q3[0][0], q3[0][1]);
      }
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readableStreamAsyncIterable = exports._decodeChunks = exports.LineDecoder = exports._iterSSEMessages = exports.StreamUtils = void 0;
    var errors_1 = require_errors();
    var StreamUtils = class {
      constructor(iterator, controller) {
        this.iterator = iterator;
        this.controller = controller;
      }
      static fromSSEResponse(response, controller) {
        let consumed2 = false;
        function iterator() {
          return __asyncGenerator6(this, arguments, function* iterator_1() {
            var e_1, _a5;
            if (consumed2) {
              throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
            }
            consumed2 = true;
            let done = false;
            try {
              try {
                for (var _b = __asyncValues5(_iterSSEMessages3(response, controller)), _c; _c = yield __await6(_b.next()), !_c.done; ) {
                  const sse = _c.value;
                  if (done)
                    continue;
                  if (sse.data.startsWith("[DONE]")) {
                    done = true;
                    continue;
                  }
                  if (sse.event === null) {
                    let data;
                    try {
                      data = JSON.parse(sse.data);
                    } catch (e3) {
                      console.error(`Could not parse message into JSON:`, sse.data);
                      console.error(`From chunk:`, sse.raw);
                      throw e3;
                    }
                    if (data && data.error) {
                      throw new errors_1.CohereError({ message: `Error: ${data.error}` });
                    }
                    yield yield __await6(data);
                  } else {
                    let data;
                    try {
                      data = JSON.parse(sse.data);
                    } catch (e3) {
                      console.error(`Could not parse message into JSON:`, sse.data);
                      console.error(`From chunk:`, sse.raw);
                      throw e3;
                    }
                    if (sse.event == "error") {
                      throw new errors_1.CohereError({ message: `Error: ${data.message}, ${data.error}` });
                    }
                    yield yield __await6({ event: sse.event, data });
                  }
                }
              } catch (e_1_1) {
                e_1 = { error: e_1_1 };
              } finally {
                try {
                  if (_c && !_c.done && (_a5 = _b.return))
                    yield __await6(_a5.call(_b));
                } finally {
                  if (e_1)
                    throw e_1.error;
                }
              }
              done = true;
            } catch (e3) {
              if (e3 instanceof Error && e3.name === "AbortError")
                return yield __await6(void 0);
              throw e3;
            } finally {
              if (!done)
                controller === null || controller === void 0 ? void 0 : controller.abort();
            }
          });
        }
        return new StreamUtils(iterator, controller);
      }
      /**
       * Generates a Stream from a newline-separated ReadableStream
       * where each item is a JSON value.
       */
      static fromReadableStream(readableStream, controller) {
        let consumed2 = false;
        function iterLines() {
          return __asyncGenerator6(this, arguments, function* iterLines_1() {
            var e_2, _a5;
            const lineDecoder = new LineDecoder4();
            const iter = readableStreamAsyncIterable4(readableStream);
            try {
              for (var iter_1 = __asyncValues5(iter), iter_1_1; iter_1_1 = yield __await6(iter_1.next()), !iter_1_1.done; ) {
                const chunk = iter_1_1.value;
                for (const line of lineDecoder.decode(chunk)) {
                  yield yield __await6(line);
                }
              }
            } catch (e_2_1) {
              e_2 = { error: e_2_1 };
            } finally {
              try {
                if (iter_1_1 && !iter_1_1.done && (_a5 = iter_1.return))
                  yield __await6(_a5.call(iter_1));
              } finally {
                if (e_2)
                  throw e_2.error;
              }
            }
            for (const line of lineDecoder.flush()) {
              yield yield __await6(line);
            }
          });
        }
        function iterator() {
          return __asyncGenerator6(this, arguments, function* iterator_2() {
            var e_3, _a5;
            if (consumed2) {
              throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
            }
            consumed2 = true;
            let done = false;
            try {
              try {
                for (var _b = __asyncValues5(iterLines()), _c; _c = yield __await6(_b.next()), !_c.done; ) {
                  const line = _c.value;
                  if (done)
                    continue;
                  if (line)
                    yield yield __await6(JSON.parse(line));
                }
              } catch (e_3_1) {
                e_3 = { error: e_3_1 };
              } finally {
                try {
                  if (_c && !_c.done && (_a5 = _b.return))
                    yield __await6(_a5.call(_b));
                } finally {
                  if (e_3)
                    throw e_3.error;
                }
              }
              done = true;
            } catch (e3) {
              if (e3 instanceof Error && e3.name === "AbortError")
                return yield __await6(void 0);
              throw e3;
            } finally {
              if (!done)
                controller === null || controller === void 0 ? void 0 : controller.abort();
            }
          });
        }
        return new StreamUtils(iterator, controller);
      }
      [Symbol.asyncIterator]() {
        return this.iterator();
      }
      /**
       * Splits the stream into two streams which can be
       * independently read from at different speeds.
       */
      tee() {
        const left = [];
        const right = [];
        const iterator = this.iterator();
        const teeIterator = (queue2) => {
          return {
            next: () => {
              if (queue2.length === 0) {
                const result = iterator.next();
                left.push(result);
                right.push(result);
              }
              return queue2.shift();
            }
          };
        };
        return [
          new StreamUtils(() => teeIterator(left), this.controller),
          new StreamUtils(() => teeIterator(right), this.controller)
        ];
      }
      /**
       * Converts this stream to a newline-separated ReadableStream of
       * JSON stringified values in the stream
       * which can be turned back into a Stream with `Stream.fromReadableStream()`.
       */
      toReadableStream() {
        const self2 = this;
        let iter;
        const encoder = new TextEncoder();
        return new ReadableStream({
          start() {
            return __awaiter6(this, void 0, void 0, function* () {
              iter = self2[Symbol.asyncIterator]();
            });
          },
          pull(ctrl) {
            return __awaiter6(this, void 0, void 0, function* () {
              try {
                const { value, done } = yield iter.next();
                if (done)
                  return ctrl.close();
                const bytes = encoder.encode(JSON.stringify(value) + "\n");
                ctrl.enqueue(bytes);
              } catch (err) {
                ctrl.error(err);
              }
            });
          },
          cancel() {
            var _a5;
            return __awaiter6(this, void 0, void 0, function* () {
              yield (_a5 = iter.return) === null || _a5 === void 0 ? void 0 : _a5.call(iter);
            });
          }
        });
      }
    };
    exports.StreamUtils = StreamUtils;
    function _iterSSEMessages3(response, controller) {
      return __asyncGenerator6(this, arguments, function* _iterSSEMessages_1() {
        var e_4, _a5;
        if (!response.body) {
          controller === null || controller === void 0 ? void 0 : controller.abort();
          throw new errors_1.CohereError({ message: `Attempted to iterate over a response with no body` });
        }
        const sseDecoder = new SSEDecoder4();
        const lineDecoder = new LineDecoder4();
        const iter = readableStreamAsyncIterable4(response.body);
        try {
          for (var _b = __asyncValues5(iterSSEChunks3(iter)), _c; _c = yield __await6(_b.next()), !_c.done; ) {
            const sseChunk = _c.value;
            for (const line of lineDecoder.decode(sseChunk)) {
              const sse = sseDecoder.decode(line);
              if (sse)
                yield yield __await6(sse);
            }
          }
        } catch (e_4_1) {
          e_4 = { error: e_4_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a5 = _b.return))
              yield __await6(_a5.call(_b));
          } finally {
            if (e_4)
              throw e_4.error;
          }
        }
        for (const line of lineDecoder.flush()) {
          const sse = sseDecoder.decode(line);
          if (sse)
            yield yield __await6(sse);
        }
      });
    }
    exports._iterSSEMessages = _iterSSEMessages3;
    function iterSSEChunks3(iterator) {
      return __asyncGenerator6(this, arguments, function* iterSSEChunks_1() {
        var e_5, _a5;
        let data = new Uint8Array();
        try {
          for (var iterator_3 = __asyncValues5(iterator), iterator_3_1; iterator_3_1 = yield __await6(iterator_3.next()), !iterator_3_1.done; ) {
            const chunk = iterator_3_1.value;
            if (chunk == null) {
              continue;
            }
            const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
            let newData = new Uint8Array(data.length + binaryChunk.length);
            newData.set(data);
            newData.set(binaryChunk, data.length);
            data = newData;
            let patternIndex;
            while ((patternIndex = findDoubleNewlineIndex3(data)) !== -1) {
              yield yield __await6(data.slice(0, patternIndex));
              data = data.slice(patternIndex);
            }
          }
        } catch (e_5_1) {
          e_5 = { error: e_5_1 };
        } finally {
          try {
            if (iterator_3_1 && !iterator_3_1.done && (_a5 = iterator_3.return))
              yield __await6(_a5.call(iterator_3));
          } finally {
            if (e_5)
              throw e_5.error;
          }
        }
        if (data.length > 0) {
          yield yield __await6(data);
        }
      });
    }
    function findDoubleNewlineIndex3(buffer) {
      const newline = 10;
      const carriage = 13;
      for (let i3 = 0; i3 < buffer.length - 2; i3++) {
        if (buffer[i3] === newline && buffer[i3 + 1] === newline) {
          return i3 + 2;
        }
        if (buffer[i3] === carriage && buffer[i3 + 1] === carriage) {
          return i3 + 2;
        }
        if (buffer[i3] === carriage && buffer[i3 + 1] === newline && i3 + 3 < buffer.length && buffer[i3 + 2] === carriage && buffer[i3 + 3] === newline) {
          return i3 + 4;
        }
      }
      return -1;
    }
    var SSEDecoder4 = class {
      constructor() {
        this.event = null;
        this.data = [];
        this.chunks = [];
      }
      decode(line) {
        if (line.endsWith("\r")) {
          line = line.substring(0, line.length - 1);
        }
        if (!line) {
          if (!this.event && !this.data.length)
            return null;
          const sse = {
            event: this.event,
            data: this.data.join("\n"),
            raw: this.chunks
          };
          this.event = null;
          this.data = [];
          this.chunks = [];
          return sse;
        }
        this.chunks.push(line);
        if (line.startsWith(":")) {
          return null;
        }
        let [fieldname, _2, value] = partition5(line, ":");
        if (value.startsWith(" ")) {
          value = value.substring(1);
        }
        if (fieldname === "event") {
          this.event = value;
        } else if (fieldname === "data") {
          this.data.push(value);
        }
        return null;
      }
    };
    var LineDecoder4 = class {
      constructor() {
        this.buffer = [];
        this.trailingCR = false;
      }
      decode(chunk) {
        let text = this.decodeText(chunk);
        if (this.trailingCR) {
          text = "\r" + text;
          this.trailingCR = false;
        }
        if (text.endsWith("\r")) {
          this.trailingCR = true;
          text = text.slice(0, -1);
        }
        if (!text) {
          return [];
        }
        const trailingNewline = LineDecoder4.NEWLINE_CHARS.has(text[text.length - 1] || "");
        let lines = text.split(LineDecoder4.NEWLINE_REGEXP);
        if (trailingNewline) {
          lines.pop();
        }
        if (lines.length === 1 && !trailingNewline) {
          this.buffer.push(lines[0]);
          return [];
        }
        if (this.buffer.length > 0) {
          lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
          this.buffer = [];
        }
        if (!trailingNewline) {
          this.buffer = [lines.pop() || ""];
        }
        return lines;
      }
      decodeText(bytes) {
        var _a5;
        if (bytes == null)
          return "";
        if (typeof bytes === "string")
          return bytes;
        if (typeof Buffer !== "undefined") {
          if (bytes instanceof Buffer) {
            return bytes.toString();
          }
          if (bytes instanceof Uint8Array) {
            return Buffer.from(bytes).toString();
          }
          throw new errors_1.CohereError({
            message: `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`
          });
        }
        if (typeof TextDecoder !== "undefined") {
          if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
            (_a5 = this.textDecoder) !== null && _a5 !== void 0 ? _a5 : this.textDecoder = new TextDecoder("utf8");
            return this.textDecoder.decode(bytes);
          }
          throw new errors_1.CohereError({
            message: `Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`
          });
        }
        throw new errors_1.CohereError({
          message: `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`
        });
      }
      flush() {
        if (!this.buffer.length && !this.trailingCR) {
          return [];
        }
        const lines = [this.buffer.join("")];
        this.buffer = [];
        this.trailingCR = false;
        return lines;
      }
    };
    exports.LineDecoder = LineDecoder4;
    LineDecoder4.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
    LineDecoder4.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
    function _decodeChunks(chunks) {
      const decoder = new LineDecoder4();
      const lines = [];
      for (const chunk of chunks) {
        lines.push(...decoder.decode(chunk));
      }
      return lines;
    }
    exports._decodeChunks = _decodeChunks;
    function partition5(str2, delimiter) {
      const index2 = str2.indexOf(delimiter);
      if (index2 !== -1) {
        return [str2.substring(0, index2), delimiter, str2.substring(index2 + delimiter.length)];
      }
      return [str2, "", ""];
    }
    function readableStreamAsyncIterable4(stream) {
      if (stream[Symbol.asyncIterator])
        return stream;
      const reader = stream.getReader();
      return {
        next() {
          return __awaiter6(this, void 0, void 0, function* () {
            try {
              const result = yield reader.read();
              if (result === null || result === void 0 ? void 0 : result.done)
                reader.releaseLock();
              return result;
            } catch (e3) {
              reader.releaseLock();
              throw e3;
            }
          });
        },
        return() {
          return __awaiter6(this, void 0, void 0, function* () {
            const cancelPromise2 = reader.cancel();
            reader.releaseLock();
            yield cancelPromise2;
            return { done: true, value: void 0 };
          });
        },
        [Symbol.asyncIterator]() {
          return this;
        }
      };
    }
    exports.readableStreamAsyncIterable = readableStreamAsyncIterable4;
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/V2ChatStreamRequestCitationMode.js
var require_V2ChatStreamRequestCitationMode2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/V2ChatStreamRequestCitationMode.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatStreamRequestCitationMode = void 0;
    var core = __importStar5(require_core());
    exports.V2ChatStreamRequestCitationMode = core.serialization.enum_(["FAST", "ACCURATE", "OFF"]);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/V2ChatRequestCitationMode.js
var require_V2ChatRequestCitationMode2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/V2ChatRequestCitationMode.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatRequestCitationMode = void 0;
    var core = __importStar5(require_core());
    exports.V2ChatRequestCitationMode = core.serialization.enum_(["FAST", "ACCURATE", "OFF"]);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/TextContent.js
var require_TextContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/TextContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextContent = void 0;
    var core = __importStar5(require_core());
    exports.TextContent = core.serialization.object({
      text: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Content.js
var require_Content2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Content.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Content = void 0;
    var core = __importStar5(require_core());
    var TextContent_1 = require_TextContent2();
    exports.Content = core.serialization.union("type", {
      text: TextContent_1.TextContent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/UserMessageContent.js
var require_UserMessageContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/UserMessageContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UserMessageContent = void 0;
    var core = __importStar5(require_core());
    var Content_1 = require_Content2();
    exports.UserMessageContent = core.serialization.undiscriminatedUnion([core.serialization.string(), core.serialization.list(Content_1.Content)]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatDocument.js
var require_ChatDocument2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatDocument.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatDocument = void 0;
    var core = __importStar5(require_core());
    exports.ChatDocument = core.serialization.record(core.serialization.string(), core.serialization.string());
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/UserMessage.js
var require_UserMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/UserMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UserMessage = void 0;
    var core = __importStar5(require_core());
    var UserMessageContent_1 = require_UserMessageContent2();
    var ChatDocument_1 = require_ChatDocument2();
    exports.UserMessage = core.serialization.object({
      content: UserMessageContent_1.UserMessageContent,
      documents: core.serialization.list(ChatDocument_1.ChatDocument).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolCall2Function.js
var require_ToolCall2Function2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolCall2Function.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCall2Function = void 0;
    var core = __importStar5(require_core());
    exports.ToolCall2Function = core.serialization.object({
      name: core.serialization.string().optional(),
      arguments: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolCall2.js
var require_ToolCall22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolCall2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCall2 = void 0;
    var core = __importStar5(require_core());
    var ToolCall2Function_1 = require_ToolCall2Function2();
    exports.ToolCall2 = core.serialization.object({
      id: core.serialization.string().optional(),
      type: core.serialization.stringLiteral("function").optional(),
      function: ToolCall2Function_1.ToolCall2Function.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolSource.js
var require_ToolSource2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolSource.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolSource = void 0;
    var core = __importStar5(require_core());
    exports.ToolSource = core.serialization.object({
      id: core.serialization.string().optional(),
      toolOutput: core.serialization.property("tool_output", core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/DocumentSource.js
var require_DocumentSource2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/DocumentSource.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DocumentSource = void 0;
    var core = __importStar5(require_core());
    exports.DocumentSource = core.serialization.object({
      id: core.serialization.string().optional(),
      document: core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Source.js
var require_Source2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Source.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Source = void 0;
    var core = __importStar5(require_core());
    var ToolSource_1 = require_ToolSource2();
    var DocumentSource_1 = require_DocumentSource2();
    exports.Source = core.serialization.union("type", {
      tool: ToolSource_1.ToolSource,
      document: DocumentSource_1.DocumentSource
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Citation.js
var require_Citation2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Citation.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Citation = void 0;
    var core = __importStar5(require_core());
    var Source_1 = require_Source2();
    exports.Citation = core.serialization.object({
      start: core.serialization.number().optional(),
      end: core.serialization.number().optional(),
      text: core.serialization.string().optional(),
      sources: core.serialization.list(Source_1.Source).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageContentItem.js
var require_AssistantMessageContentItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageContentItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessageContentItem = void 0;
    var core = __importStar5(require_core());
    var TextContent_1 = require_TextContent2();
    exports.AssistantMessageContentItem = core.serialization.union("type", {
      text: TextContent_1.TextContent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageContent.js
var require_AssistantMessageContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessageContent = void 0;
    var core = __importStar5(require_core());
    var AssistantMessageContentItem_1 = require_AssistantMessageContentItem2();
    exports.AssistantMessageContent = core.serialization.undiscriminatedUnion([
      core.serialization.string(),
      core.serialization.list(AssistantMessageContentItem_1.AssistantMessageContentItem)
    ]);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessage.js
var require_AssistantMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessage = void 0;
    var core = __importStar5(require_core());
    var ToolCall2_1 = require_ToolCall22();
    var AssistantMessageContent_1 = require_AssistantMessageContent2();
    var Citation_1 = require_Citation2();
    exports.AssistantMessage = core.serialization.object({
      toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall2_1.ToolCall2).optional()),
      toolPlan: core.serialization.property("tool_plan", core.serialization.string().optional()),
      content: AssistantMessageContent_1.AssistantMessageContent.optional(),
      citations: core.serialization.list(Citation_1.Citation).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/SystemMessageContentItem.js
var require_SystemMessageContentItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/SystemMessageContentItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SystemMessageContentItem = void 0;
    var core = __importStar5(require_core());
    var TextContent_1 = require_TextContent2();
    exports.SystemMessageContentItem = core.serialization.union("type", {
      text: TextContent_1.TextContent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/SystemMessageContent.js
var require_SystemMessageContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/SystemMessageContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SystemMessageContent = void 0;
    var core = __importStar5(require_core());
    var SystemMessageContentItem_1 = require_SystemMessageContentItem2();
    exports.SystemMessageContent = core.serialization.undiscriminatedUnion([
      core.serialization.string(),
      core.serialization.list(SystemMessageContentItem_1.SystemMessageContentItem)
    ]);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/SystemMessage.js
var require_SystemMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/SystemMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SystemMessage = void 0;
    var core = __importStar5(require_core());
    var SystemMessageContent_1 = require_SystemMessageContent2();
    exports.SystemMessage = core.serialization.object({
      content: SystemMessageContent_1.SystemMessageContent
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolContent.js
var require_ToolContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolContent = void 0;
    var core = __importStar5(require_core());
    exports.ToolContent = core.serialization.object({
      output: core.serialization.record(core.serialization.string(), core.serialization.unknown())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolMessage2ToolContentItem.js
var require_ToolMessage2ToolContentItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolMessage2ToolContentItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolMessage2ToolContentItem = void 0;
    var core = __importStar5(require_core());
    var ToolContent_1 = require_ToolContent2();
    exports.ToolMessage2ToolContentItem = core.serialization.union("type", {
      tool_result_object: ToolContent_1.ToolContent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ToolMessage2.js
var require_ToolMessage22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ToolMessage2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolMessage2 = void 0;
    var core = __importStar5(require_core());
    var ToolMessage2ToolContentItem_1 = require_ToolMessage2ToolContentItem2();
    exports.ToolMessage2 = core.serialization.object({
      toolCallId: core.serialization.property("tool_call_id", core.serialization.string()),
      toolContent: core.serialization.property("tool_content", core.serialization.list(ToolMessage2ToolContentItem_1.ToolMessage2ToolContentItem))
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessage2.js
var require_ChatMessage22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessage2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessage2 = void 0;
    var core = __importStar5(require_core());
    var UserMessage_1 = require_UserMessage2();
    var AssistantMessage_1 = require_AssistantMessage2();
    var SystemMessage_1 = require_SystemMessage2();
    var ToolMessage2_1 = require_ToolMessage22();
    exports.ChatMessage2 = core.serialization.union("role", {
      user: UserMessage_1.UserMessage,
      assistant: AssistantMessage_1.AssistantMessage,
      system: SystemMessage_1.SystemMessage,
      tool: ToolMessage2_1.ToolMessage2
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessages.js
var require_ChatMessages2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessages.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessages = void 0;
    var core = __importStar5(require_core());
    var ChatMessage2_1 = require_ChatMessage22();
    exports.ChatMessages = core.serialization.list(ChatMessage2_1.ChatMessage2);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Tool2Function.js
var require_Tool2Function2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Tool2Function.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tool2Function = void 0;
    var core = __importStar5(require_core());
    exports.Tool2Function = core.serialization.object({
      name: core.serialization.string().optional(),
      description: core.serialization.string().optional(),
      parameters: core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Tool2.js
var require_Tool22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Tool2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tool2 = void 0;
    var core = __importStar5(require_core());
    var Tool2Function_1 = require_Tool2Function2();
    exports.Tool2 = core.serialization.object({
      type: core.serialization.stringLiteral("function").optional(),
      function: Tool2Function_1.Tool2Function.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatFinishReason.js
var require_ChatFinishReason2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatFinishReason.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatFinishReason = void 0;
    var core = __importStar5(require_core());
    exports.ChatFinishReason = core.serialization.enum_([
      "complete",
      "stop_sequence",
      "max_tokens",
      "tool_call",
      "error",
      "content_blocked",
      "error_limit"
    ]);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageResponseContentItem.js
var require_AssistantMessageResponseContentItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageResponseContentItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessageResponseContentItem = void 0;
    var core = __importStar5(require_core());
    var TextContent_1 = require_TextContent2();
    exports.AssistantMessageResponseContentItem = core.serialization.union("type", {
      text: TextContent_1.TextContent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageResponse.js
var require_AssistantMessageResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/AssistantMessageResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AssistantMessageResponse = void 0;
    var core = __importStar5(require_core());
    var ToolCall2_1 = require_ToolCall22();
    var AssistantMessageResponseContentItem_1 = require_AssistantMessageResponseContentItem2();
    var Citation_1 = require_Citation2();
    exports.AssistantMessageResponse = core.serialization.object({
      role: core.serialization.stringLiteral("assistant"),
      toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall2_1.ToolCall2).optional()),
      toolPlan: core.serialization.property("tool_plan", core.serialization.string().optional()),
      content: core.serialization.list(AssistantMessageResponseContentItem_1.AssistantMessageResponseContentItem).optional(),
      citations: core.serialization.list(Citation_1.Citation).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/UsageBilledUnits.js
var require_UsageBilledUnits2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/UsageBilledUnits.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UsageBilledUnits = void 0;
    var core = __importStar5(require_core());
    exports.UsageBilledUnits = core.serialization.object({
      inputTokens: core.serialization.property("input_tokens", core.serialization.number().optional()),
      outputTokens: core.serialization.property("output_tokens", core.serialization.number().optional()),
      searchUnits: core.serialization.property("search_units", core.serialization.number().optional()),
      classifications: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/UsageTokens.js
var require_UsageTokens2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/UsageTokens.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UsageTokens = void 0;
    var core = __importStar5(require_core());
    exports.UsageTokens = core.serialization.object({
      inputTokens: core.serialization.property("input_tokens", core.serialization.number().optional()),
      outputTokens: core.serialization.property("output_tokens", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/Usage.js
var require_Usage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/Usage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Usage = void 0;
    var core = __importStar5(require_core());
    var UsageBilledUnits_1 = require_UsageBilledUnits2();
    var UsageTokens_1 = require_UsageTokens2();
    exports.Usage = core.serialization.object({
      billedUnits: core.serialization.property("billed_units", UsageBilledUnits_1.UsageBilledUnits.optional()),
      tokens: UsageTokens_1.UsageTokens.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/NonStreamedChatResponse2.js
var require_NonStreamedChatResponse22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/NonStreamedChatResponse2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NonStreamedChatResponse2 = void 0;
    var core = __importStar5(require_core());
    var ChatFinishReason_1 = require_ChatFinishReason2();
    var AssistantMessageResponse_1 = require_AssistantMessageResponse2();
    var Usage_1 = require_Usage2();
    exports.NonStreamedChatResponse2 = core.serialization.object({
      id: core.serialization.string(),
      finishReason: core.serialization.property("finish_reason", ChatFinishReason_1.ChatFinishReason),
      prompt: core.serialization.string().optional(),
      message: AssistantMessageResponse_1.AssistantMessageResponse.optional(),
      usage: Usage_1.Usage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatStreamEventType.js
var require_ChatStreamEventType2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatStreamEventType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamEventType = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamEventType = core.serialization.object({});
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEventDeltaMessage.js
var require_ChatMessageStartEventDeltaMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEventDeltaMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessageStartEventDeltaMessage = void 0;
    var core = __importStar5(require_core());
    exports.ChatMessageStartEventDeltaMessage = core.serialization.object({
      role: core.serialization.stringLiteral("assistant").optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEventDelta.js
var require_ChatMessageStartEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessageStartEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatMessageStartEventDeltaMessage_1 = require_ChatMessageStartEventDeltaMessage2();
    exports.ChatMessageStartEventDelta = core.serialization.object({
      message: ChatMessageStartEventDeltaMessage_1.ChatMessageStartEventDeltaMessage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEvent.js
var require_ChatMessageStartEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageStartEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessageStartEvent = void 0;
    var core = __importStar5(require_core());
    var ChatMessageStartEventDelta_1 = require_ChatMessageStartEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatMessageStartEvent = core.serialization.object({
      id: core.serialization.string().optional(),
      delta: ChatMessageStartEventDelta_1.ChatMessageStartEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDeltaMessageContent.js
var require_ChatContentStartEventDeltaMessageContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDeltaMessageContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentStartEventDeltaMessageContent = void 0;
    var core = __importStar5(require_core());
    exports.ChatContentStartEventDeltaMessageContent = core.serialization.object({
      text: core.serialization.string().optional(),
      type: core.serialization.stringLiteral("text").optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDeltaMessage.js
var require_ChatContentStartEventDeltaMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDeltaMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentStartEventDeltaMessage = void 0;
    var core = __importStar5(require_core());
    var ChatContentStartEventDeltaMessageContent_1 = require_ChatContentStartEventDeltaMessageContent2();
    exports.ChatContentStartEventDeltaMessage = core.serialization.object({
      content: ChatContentStartEventDeltaMessageContent_1.ChatContentStartEventDeltaMessageContent.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDelta.js
var require_ChatContentStartEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentStartEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatContentStartEventDeltaMessage_1 = require_ChatContentStartEventDeltaMessage2();
    exports.ChatContentStartEventDelta = core.serialization.object({
      message: ChatContentStartEventDeltaMessage_1.ChatContentStartEventDeltaMessage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEvent.js
var require_ChatContentStartEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentStartEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentStartEvent = void 0;
    var core = __importStar5(require_core());
    var ChatContentStartEventDelta_1 = require_ChatContentStartEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatContentStartEvent = core.serialization.object({
      index: core.serialization.number().optional(),
      delta: ChatContentStartEventDelta_1.ChatContentStartEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDeltaMessageContent.js
var require_ChatContentDeltaEventDeltaMessageContent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDeltaMessageContent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentDeltaEventDeltaMessageContent = void 0;
    var core = __importStar5(require_core());
    exports.ChatContentDeltaEventDeltaMessageContent = core.serialization.object({
      text: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDeltaMessage.js
var require_ChatContentDeltaEventDeltaMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDeltaMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentDeltaEventDeltaMessage = void 0;
    var core = __importStar5(require_core());
    var ChatContentDeltaEventDeltaMessageContent_1 = require_ChatContentDeltaEventDeltaMessageContent2();
    exports.ChatContentDeltaEventDeltaMessage = core.serialization.object({
      content: ChatContentDeltaEventDeltaMessageContent_1.ChatContentDeltaEventDeltaMessageContent.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDelta.js
var require_ChatContentDeltaEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentDeltaEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatContentDeltaEventDeltaMessage_1 = require_ChatContentDeltaEventDeltaMessage2();
    exports.ChatContentDeltaEventDelta = core.serialization.object({
      message: ChatContentDeltaEventDeltaMessage_1.ChatContentDeltaEventDeltaMessage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEvent.js
var require_ChatContentDeltaEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentDeltaEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentDeltaEvent = void 0;
    var core = __importStar5(require_core());
    var ChatContentDeltaEventDelta_1 = require_ChatContentDeltaEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatContentDeltaEvent = core.serialization.object({
      index: core.serialization.number().optional(),
      delta: ChatContentDeltaEventDelta_1.ChatContentDeltaEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatContentEndEvent.js
var require_ChatContentEndEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatContentEndEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatContentEndEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatContentEndEvent = core.serialization.object({
      index: core.serialization.number().optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolPlanDeltaEventDelta.js
var require_ChatToolPlanDeltaEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolPlanDeltaEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolPlanDeltaEventDelta = void 0;
    var core = __importStar5(require_core());
    exports.ChatToolPlanDeltaEventDelta = core.serialization.object({
      toolPlan: core.serialization.property("tool_plan", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolPlanDeltaEvent.js
var require_ChatToolPlanDeltaEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolPlanDeltaEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolPlanDeltaEvent = void 0;
    var core = __importStar5(require_core());
    var ChatToolPlanDeltaEventDelta_1 = require_ChatToolPlanDeltaEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatToolPlanDeltaEvent = core.serialization.object({
      delta: ChatToolPlanDeltaEventDelta_1.ChatToolPlanDeltaEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDeltaToolCallFunction.js
var require_ChatToolCallStartEventDeltaToolCallFunction2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDeltaToolCallFunction.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallStartEventDeltaToolCallFunction = void 0;
    var core = __importStar5(require_core());
    exports.ChatToolCallStartEventDeltaToolCallFunction = core.serialization.object({
      name: core.serialization.string().optional(),
      arguments: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDeltaToolCall.js
var require_ChatToolCallStartEventDeltaToolCall2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDeltaToolCall.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallStartEventDeltaToolCall = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallStartEventDeltaToolCallFunction_1 = require_ChatToolCallStartEventDeltaToolCallFunction2();
    exports.ChatToolCallStartEventDeltaToolCall = core.serialization.object({
      id: core.serialization.string().optional(),
      type: core.serialization.stringLiteral("function").optional(),
      function: ChatToolCallStartEventDeltaToolCallFunction_1.ChatToolCallStartEventDeltaToolCallFunction.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDelta.js
var require_ChatToolCallStartEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallStartEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallStartEventDeltaToolCall_1 = require_ChatToolCallStartEventDeltaToolCall2();
    exports.ChatToolCallStartEventDelta = core.serialization.object({
      toolCall: core.serialization.property("tool_call", ChatToolCallStartEventDeltaToolCall_1.ChatToolCallStartEventDeltaToolCall.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEvent.js
var require_ChatToolCallStartEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallStartEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallStartEvent = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallStartEventDelta_1 = require_ChatToolCallStartEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatToolCallStartEvent = core.serialization.object({
      index: core.serialization.number().optional(),
      delta: ChatToolCallStartEventDelta_1.ChatToolCallStartEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDeltaToolCallFunction.js
var require_ChatToolCallDeltaEventDeltaToolCallFunction2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDeltaToolCallFunction.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallDeltaEventDeltaToolCallFunction = void 0;
    var core = __importStar5(require_core());
    exports.ChatToolCallDeltaEventDeltaToolCallFunction = core.serialization.object({
      arguments: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDeltaToolCall.js
var require_ChatToolCallDeltaEventDeltaToolCall2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDeltaToolCall.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallDeltaEventDeltaToolCall = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallDeltaEventDeltaToolCallFunction_1 = require_ChatToolCallDeltaEventDeltaToolCallFunction2();
    exports.ChatToolCallDeltaEventDeltaToolCall = core.serialization.object({
      function: ChatToolCallDeltaEventDeltaToolCallFunction_1.ChatToolCallDeltaEventDeltaToolCallFunction.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDelta.js
var require_ChatToolCallDeltaEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallDeltaEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallDeltaEventDeltaToolCall_1 = require_ChatToolCallDeltaEventDeltaToolCall2();
    exports.ChatToolCallDeltaEventDelta = core.serialization.object({
      toolCall: core.serialization.property("tool_call", ChatToolCallDeltaEventDeltaToolCall_1.ChatToolCallDeltaEventDeltaToolCall.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEvent.js
var require_ChatToolCallDeltaEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallDeltaEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallDeltaEvent = void 0;
    var core = __importStar5(require_core());
    var ChatToolCallDeltaEventDelta_1 = require_ChatToolCallDeltaEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatToolCallDeltaEvent = core.serialization.object({
      index: core.serialization.number().optional(),
      delta: ChatToolCallDeltaEventDelta_1.ChatToolCallDeltaEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallEndEvent.js
var require_ChatToolCallEndEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatToolCallEndEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallEndEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatToolCallEndEvent = core.serialization.object({
      index: core.serialization.number().optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageEndEventDelta.js
var require_ChatMessageEndEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageEndEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessageEndEventDelta = void 0;
    var core = __importStar5(require_core());
    var ChatFinishReason_1 = require_ChatFinishReason2();
    var Usage_1 = require_Usage2();
    exports.ChatMessageEndEventDelta = core.serialization.object({
      finishReason: core.serialization.property("finish_reason", ChatFinishReason_1.ChatFinishReason.optional()),
      usage: Usage_1.Usage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageEndEvent.js
var require_ChatMessageEndEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/ChatMessageEndEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessageEndEvent = void 0;
    var core = __importStar5(require_core());
    var ChatMessageEndEventDelta_1 = require_ChatMessageEndEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.ChatMessageEndEvent = core.serialization.object({
      id: core.serialization.string().optional(),
      delta: ChatMessageEndEventDelta_1.ChatMessageEndEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/types/CitationStartEventDeltaMessage.js
var require_CitationStartEventDeltaMessage2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CitationStartEventDeltaMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CitationStartEventDeltaMessage = void 0;
    var core = __importStar5(require_core());
    var Citation_1 = require_Citation2();
    exports.CitationStartEventDeltaMessage = core.serialization.object({
      citations: Citation_1.Citation.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/CitationStartEventDelta.js
var require_CitationStartEventDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CitationStartEventDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CitationStartEventDelta = void 0;
    var core = __importStar5(require_core());
    var CitationStartEventDeltaMessage_1 = require_CitationStartEventDeltaMessage2();
    exports.CitationStartEventDelta = core.serialization.object({
      message: CitationStartEventDeltaMessage_1.CitationStartEventDeltaMessage.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/CitationStartEvent.js
var require_CitationStartEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CitationStartEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CitationStartEvent = void 0;
    var core = __importStar5(require_core());
    var CitationStartEventDelta_1 = require_CitationStartEventDelta2();
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.CitationStartEvent = core.serialization.object({
      index: core.serialization.number().optional(),
      delta: CitationStartEventDelta_1.CitationStartEventDelta.optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/types/CitationEndEvent.js
var require_CitationEndEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CitationEndEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CitationEndEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEventType_1 = require_ChatStreamEventType2();
    exports.CitationEndEvent = core.serialization.object({
      index: core.serialization.number().optional()
    }).extend(ChatStreamEventType_1.ChatStreamEventType);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/StreamedChatResponse2.js
var require_StreamedChatResponse22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/StreamedChatResponse2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StreamedChatResponse2 = void 0;
    var core = __importStar5(require_core());
    var ChatMessageStartEvent_1 = require_ChatMessageStartEvent2();
    var ChatContentStartEvent_1 = require_ChatContentStartEvent2();
    var ChatContentDeltaEvent_1 = require_ChatContentDeltaEvent2();
    var ChatContentEndEvent_1 = require_ChatContentEndEvent2();
    var ChatToolPlanDeltaEvent_1 = require_ChatToolPlanDeltaEvent2();
    var ChatToolCallStartEvent_1 = require_ChatToolCallStartEvent2();
    var ChatToolCallDeltaEvent_1 = require_ChatToolCallDeltaEvent2();
    var ChatToolCallEndEvent_1 = require_ChatToolCallEndEvent2();
    var CitationStartEvent_1 = require_CitationStartEvent2();
    var CitationEndEvent_1 = require_CitationEndEvent2();
    var ChatMessageEndEvent_1 = require_ChatMessageEndEvent2();
    exports.StreamedChatResponse2 = core.serialization.union("type", {
      "message-start": ChatMessageStartEvent_1.ChatMessageStartEvent,
      "content-start": ChatContentStartEvent_1.ChatContentStartEvent,
      "content-delta": ChatContentDeltaEvent_1.ChatContentDeltaEvent,
      "content-end": ChatContentEndEvent_1.ChatContentEndEvent,
      "tool-plan-delta": ChatToolPlanDeltaEvent_1.ChatToolPlanDeltaEvent,
      "tool-call-start": ChatToolCallStartEvent_1.ChatToolCallStartEvent,
      "tool-call-delta": ChatToolCallDeltaEvent_1.ChatToolCallDeltaEvent,
      "tool-call-end": ChatToolCallEndEvent_1.ChatToolCallEndEvent,
      "citation-start": CitationStartEvent_1.CitationStartEvent,
      "citation-end": CitationEndEvent_1.CitationEndEvent,
      "message-end": ChatMessageEndEvent_1.ChatMessageEndEvent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/types/index.js
var require_types7 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_V2ChatStreamRequestCitationMode2(), exports);
    __exportStar5(require_V2ChatRequestCitationMode2(), exports);
    __exportStar5(require_TextContent2(), exports);
    __exportStar5(require_Content2(), exports);
    __exportStar5(require_UserMessageContent2(), exports);
    __exportStar5(require_UserMessage2(), exports);
    __exportStar5(require_ToolCall2Function2(), exports);
    __exportStar5(require_ToolCall22(), exports);
    __exportStar5(require_ToolSource2(), exports);
    __exportStar5(require_DocumentSource2(), exports);
    __exportStar5(require_Source2(), exports);
    __exportStar5(require_Citation2(), exports);
    __exportStar5(require_AssistantMessageContentItem2(), exports);
    __exportStar5(require_AssistantMessageContent2(), exports);
    __exportStar5(require_AssistantMessage2(), exports);
    __exportStar5(require_SystemMessageContentItem2(), exports);
    __exportStar5(require_SystemMessageContent2(), exports);
    __exportStar5(require_SystemMessage2(), exports);
    __exportStar5(require_ToolContent2(), exports);
    __exportStar5(require_ToolMessage2ToolContentItem2(), exports);
    __exportStar5(require_ToolMessage22(), exports);
    __exportStar5(require_ChatMessage22(), exports);
    __exportStar5(require_ChatMessages2(), exports);
    __exportStar5(require_Tool2Function2(), exports);
    __exportStar5(require_Tool22(), exports);
    __exportStar5(require_ChatFinishReason2(), exports);
    __exportStar5(require_AssistantMessageResponseContentItem2(), exports);
    __exportStar5(require_AssistantMessageResponse2(), exports);
    __exportStar5(require_UsageBilledUnits2(), exports);
    __exportStar5(require_UsageTokens2(), exports);
    __exportStar5(require_Usage2(), exports);
    __exportStar5(require_NonStreamedChatResponse22(), exports);
    __exportStar5(require_ChatStreamEventType2(), exports);
    __exportStar5(require_ChatMessageStartEventDeltaMessage2(), exports);
    __exportStar5(require_ChatMessageStartEventDelta2(), exports);
    __exportStar5(require_ChatMessageStartEvent2(), exports);
    __exportStar5(require_ChatContentStartEventDeltaMessageContent2(), exports);
    __exportStar5(require_ChatContentStartEventDeltaMessage2(), exports);
    __exportStar5(require_ChatContentStartEventDelta2(), exports);
    __exportStar5(require_ChatContentStartEvent2(), exports);
    __exportStar5(require_ChatContentDeltaEventDeltaMessageContent2(), exports);
    __exportStar5(require_ChatContentDeltaEventDeltaMessage2(), exports);
    __exportStar5(require_ChatContentDeltaEventDelta2(), exports);
    __exportStar5(require_ChatContentDeltaEvent2(), exports);
    __exportStar5(require_ChatContentEndEvent2(), exports);
    __exportStar5(require_ChatToolPlanDeltaEventDelta2(), exports);
    __exportStar5(require_ChatToolPlanDeltaEvent2(), exports);
    __exportStar5(require_ChatToolCallStartEventDeltaToolCallFunction2(), exports);
    __exportStar5(require_ChatToolCallStartEventDeltaToolCall2(), exports);
    __exportStar5(require_ChatToolCallStartEventDelta2(), exports);
    __exportStar5(require_ChatToolCallStartEvent2(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDeltaToolCallFunction2(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDeltaToolCall2(), exports);
    __exportStar5(require_ChatToolCallDeltaEventDelta2(), exports);
    __exportStar5(require_ChatToolCallDeltaEvent2(), exports);
    __exportStar5(require_ChatToolCallEndEvent2(), exports);
    __exportStar5(require_ChatMessageEndEventDelta2(), exports);
    __exportStar5(require_ChatMessageEndEvent2(), exports);
    __exportStar5(require_StreamedChatResponse22(), exports);
  }
});

// node_modules/cohere-ai/serialization/types/TextResponseFormat.js
var require_TextResponseFormat2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/TextResponseFormat.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TextResponseFormat = void 0;
    var core = __importStar5(require_core());
    exports.TextResponseFormat = core.serialization.object({});
  }
});

// node_modules/cohere-ai/serialization/types/JsonResponseFormat2.js
var require_JsonResponseFormat22 = __commonJS({
  "node_modules/cohere-ai/serialization/types/JsonResponseFormat2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonResponseFormat2 = void 0;
    var core = __importStar5(require_core());
    exports.JsonResponseFormat2 = core.serialization.object({
      jsonSchema: core.serialization.property("json_schema", core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ResponseFormat2.js
var require_ResponseFormat22 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ResponseFormat2.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseFormat2 = void 0;
    var core = __importStar5(require_core());
    var TextResponseFormat_1 = require_TextResponseFormat2();
    var JsonResponseFormat2_1 = require_JsonResponseFormat22();
    exports.ResponseFormat2 = core.serialization.union("type", {
      text: TextResponseFormat_1.TextResponseFormat,
      json_object: JsonResponseFormat2_1.JsonResponseFormat2
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/client/requests/V2ChatStreamRequest.js
var require_V2ChatStreamRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/client/requests/V2ChatStreamRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatStreamRequest = void 0;
    var core = __importStar5(require_core());
    var ChatMessages_1 = require_ChatMessages2();
    var Tool2_1 = require_Tool22();
    var V2ChatStreamRequestCitationMode_1 = require_V2ChatStreamRequestCitationMode2();
    var ResponseFormat2_1 = require_ResponseFormat22();
    exports.V2ChatStreamRequest = core.serialization.object({
      model: core.serialization.string(),
      messages: ChatMessages_1.ChatMessages,
      tools: core.serialization.list(Tool2_1.Tool2).optional(),
      citationMode: core.serialization.property("citation_mode", V2ChatStreamRequestCitationMode_1.V2ChatStreamRequestCitationMode.optional()),
      responseFormat: core.serialization.property("response_format", ResponseFormat2_1.ResponseFormat2.optional()),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      temperature: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      returnPrompt: core.serialization.property("return_prompt", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/client/requests/V2ChatRequest.js
var require_V2ChatRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/client/requests/V2ChatRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatRequest = void 0;
    var core = __importStar5(require_core());
    var ChatMessages_1 = require_ChatMessages2();
    var Tool2_1 = require_Tool22();
    var V2ChatRequestCitationMode_1 = require_V2ChatRequestCitationMode2();
    var ResponseFormat2_1 = require_ResponseFormat22();
    exports.V2ChatRequest = core.serialization.object({
      model: core.serialization.string(),
      messages: ChatMessages_1.ChatMessages,
      tools: core.serialization.list(Tool2_1.Tool2).optional(),
      citationMode: core.serialization.property("citation_mode", V2ChatRequestCitationMode_1.V2ChatRequestCitationMode.optional()),
      responseFormat: core.serialization.property("response_format", ResponseFormat2_1.ResponseFormat2.optional()),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      temperature: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      returnPrompt: core.serialization.property("return_prompt", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/client/requests/index.js
var require_requests8 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2ChatRequest = exports.V2ChatStreamRequest = void 0;
    var V2ChatStreamRequest_1 = require_V2ChatStreamRequest();
    Object.defineProperty(exports, "V2ChatStreamRequest", { enumerable: true, get: function() {
      return V2ChatStreamRequest_1.V2ChatStreamRequest;
    } });
    var V2ChatRequest_1 = require_V2ChatRequest();
    Object.defineProperty(exports, "V2ChatRequest", { enumerable: true, get: function() {
      return V2ChatRequest_1.V2ChatRequest;
    } });
  }
});

// node_modules/cohere-ai/serialization/resources/v2/client/index.js
var require_client10 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests8(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/v2/index.js
var require_v22 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/v2/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types7(), exports);
    __exportStar5(require_client10(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/types/CreateEmbedJobRequestTruncate.js
var require_CreateEmbedJobRequestTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/types/CreateEmbedJobRequestTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateEmbedJobRequestTruncate = void 0;
    var core = __importStar5(require_core());
    exports.CreateEmbedJobRequestTruncate = core.serialization.enum_(["START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/types/index.js
var require_types8 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_CreateEmbedJobRequestTruncate2(), exports);
  }
});

// node_modules/cohere-ai/serialization/types/EmbedInputType.js
var require_EmbedInputType2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedInputType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedInputType = void 0;
    var core = __importStar5(require_core());
    exports.EmbedInputType = core.serialization.enum_(["search_document", "search_query", "classification", "clustering"]);
  }
});

// node_modules/cohere-ai/serialization/types/EmbeddingType.js
var require_EmbeddingType2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbeddingType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbeddingType = void 0;
    var core = __importStar5(require_core());
    exports.EmbeddingType = core.serialization.enum_(["float", "int8", "uint8", "binary", "ubinary"]);
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/client/requests/CreateEmbedJobRequest.js
var require_CreateEmbedJobRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/client/requests/CreateEmbedJobRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateEmbedJobRequest = void 0;
    var core = __importStar5(require_core());
    var EmbedInputType_1 = require_EmbedInputType2();
    var EmbeddingType_1 = require_EmbeddingType2();
    var CreateEmbedJobRequestTruncate_1 = require_CreateEmbedJobRequestTruncate2();
    exports.CreateEmbedJobRequest = core.serialization.object({
      model: core.serialization.string(),
      datasetId: core.serialization.property("dataset_id", core.serialization.string()),
      inputType: core.serialization.property("input_type", EmbedInputType_1.EmbedInputType),
      name: core.serialization.string().optional(),
      embeddingTypes: core.serialization.property("embedding_types", core.serialization.list(EmbeddingType_1.EmbeddingType).optional()),
      truncate: CreateEmbedJobRequestTruncate_1.CreateEmbedJobRequestTruncate.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/client/requests/index.js
var require_requests9 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateEmbedJobRequest = void 0;
    var CreateEmbedJobRequest_1 = require_CreateEmbedJobRequest();
    Object.defineProperty(exports, "CreateEmbedJobRequest", { enumerable: true, get: function() {
      return CreateEmbedJobRequest_1.CreateEmbedJobRequest;
    } });
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/client/index.js
var require_client11 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests9(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/embedJobs/index.js
var require_embedJobs2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/embedJobs/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types8(), exports);
    __exportStar5(require_client11(), exports);
  }
});

// node_modules/cohere-ai/serialization/types/DatasetType.js
var require_DatasetType2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/DatasetType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetType = void 0;
    var core = __importStar5(require_core());
    exports.DatasetType = core.serialization.enum_([
      "embed-input",
      "embed-result",
      "cluster-result",
      "cluster-outliers",
      "reranker-finetune-input",
      "single-label-classification-finetune-input",
      "chat-finetune-input",
      "multi-label-classification-finetune-input"
    ]);
  }
});

// node_modules/cohere-ai/serialization/types/DatasetValidationStatus.js
var require_DatasetValidationStatus2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/DatasetValidationStatus.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetValidationStatus = void 0;
    var core = __importStar5(require_core());
    exports.DatasetValidationStatus = core.serialization.enum_(["unknown", "queued", "processing", "failed", "validated", "skipped"]);
  }
});

// node_modules/cohere-ai/serialization/types/DatasetPart.js
var require_DatasetPart2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/DatasetPart.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetPart = void 0;
    var core = __importStar5(require_core());
    exports.DatasetPart = core.serialization.object({
      id: core.serialization.string(),
      name: core.serialization.string(),
      url: core.serialization.string().optional(),
      index: core.serialization.number().optional(),
      sizeBytes: core.serialization.property("size_bytes", core.serialization.number().optional()),
      numRows: core.serialization.property("num_rows", core.serialization.number().optional()),
      originalUrl: core.serialization.property("original_url", core.serialization.string().optional()),
      samples: core.serialization.list(core.serialization.string()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/Dataset.js
var require_Dataset2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Dataset.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Dataset = void 0;
    var core = __importStar5(require_core());
    var DatasetType_1 = require_DatasetType2();
    var DatasetValidationStatus_1 = require_DatasetValidationStatus2();
    var DatasetPart_1 = require_DatasetPart2();
    exports.Dataset = core.serialization.object({
      id: core.serialization.string(),
      name: core.serialization.string(),
      createdAt: core.serialization.property("created_at", core.serialization.date()),
      updatedAt: core.serialization.property("updated_at", core.serialization.date()),
      datasetType: core.serialization.property("dataset_type", DatasetType_1.DatasetType),
      validationStatus: core.serialization.property("validation_status", DatasetValidationStatus_1.DatasetValidationStatus),
      validationError: core.serialization.property("validation_error", core.serialization.string().optional()),
      schema: core.serialization.string().optional(),
      requiredFields: core.serialization.property("required_fields", core.serialization.list(core.serialization.string()).optional()),
      preserveFields: core.serialization.property("preserve_fields", core.serialization.list(core.serialization.string()).optional()),
      datasetParts: core.serialization.property("dataset_parts", core.serialization.list(DatasetPart_1.DatasetPart).optional()),
      validationWarnings: core.serialization.property("validation_warnings", core.serialization.list(core.serialization.string()).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsListResponse.js
var require_DatasetsListResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsListResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetsListResponse = void 0;
    var core = __importStar5(require_core());
    var Dataset_1 = require_Dataset2();
    exports.DatasetsListResponse = core.serialization.object({
      datasets: core.serialization.list(Dataset_1.Dataset).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.js
var require_DatasetsCreateResponseDatasetPartsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsCreateResponseDatasetPartsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetsCreateResponseDatasetPartsItem = void 0;
    var core = __importStar5(require_core());
    exports.DatasetsCreateResponseDatasetPartsItem = core.serialization.object({
      name: core.serialization.string().optional(),
      numRows: core.serialization.property("num_rows", core.serialization.number().optional()),
      samples: core.serialization.list(core.serialization.string()).optional(),
      partKind: core.serialization.property("part_kind", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsCreateResponse.js
var require_DatasetsCreateResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsCreateResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetsCreateResponse = void 0;
    var core = __importStar5(require_core());
    exports.DatasetsCreateResponse = core.serialization.object({
      id: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsGetUsageResponse.js
var require_DatasetsGetUsageResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsGetUsageResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetsGetUsageResponse = void 0;
    var core = __importStar5(require_core());
    exports.DatasetsGetUsageResponse = core.serialization.object({
      organizationUsage: core.serialization.property("organization_usage", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsGetResponse.js
var require_DatasetsGetResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/DatasetsGetResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DatasetsGetResponse = void 0;
    var core = __importStar5(require_core());
    var Dataset_1 = require_Dataset2();
    exports.DatasetsGetResponse = core.serialization.object({
      dataset: Dataset_1.Dataset
    });
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/types/index.js
var require_types9 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_DatasetsListResponse2(), exports);
    __exportStar5(require_DatasetsCreateResponseDatasetPartsItem2(), exports);
    __exportStar5(require_DatasetsCreateResponse2(), exports);
    __exportStar5(require_DatasetsGetUsageResponse2(), exports);
    __exportStar5(require_DatasetsGetResponse2(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/client/delete.js
var require_delete = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/client/delete.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Response = void 0;
    var core = __importStar5(require_core());
    exports.Response = core.serialization.record(core.serialization.string(), core.serialization.unknown());
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/client/index.js
var require_client12 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.delete = void 0;
    exports.delete = __importStar5(require_delete());
  }
});

// node_modules/cohere-ai/serialization/resources/datasets/index.js
var require_datasets2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/datasets/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types9(), exports);
    __exportStar5(require_client12(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/BaseType.js
var require_BaseType2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/BaseType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseType = void 0;
    var core = __importStar5(require_core());
    exports.BaseType = core.serialization.enum_([
      "BASE_TYPE_UNSPECIFIED",
      "BASE_TYPE_GENERATIVE",
      "BASE_TYPE_CLASSIFICATION",
      "BASE_TYPE_RERANK",
      "BASE_TYPE_CHAT"
    ]);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Strategy.js
var require_Strategy2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Strategy.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Strategy = void 0;
    var core = __importStar5(require_core());
    exports.Strategy = core.serialization.enum_(["STRATEGY_UNSPECIFIED", "STRATEGY_VANILLA", "STRATEGY_TFEW"]);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/BaseModel.js
var require_BaseModel2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/BaseModel.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BaseModel = void 0;
    var core = __importStar5(require_core());
    var BaseType_1 = require_BaseType2();
    var Strategy_1 = require_Strategy2();
    exports.BaseModel = core.serialization.object({
      name: core.serialization.string().optional(),
      version: core.serialization.string().optional(),
      baseType: core.serialization.property("base_type", BaseType_1.BaseType),
      strategy: Strategy_1.Strategy.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Hyperparameters.js
var require_Hyperparameters2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Hyperparameters.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Hyperparameters = void 0;
    var core = __importStar5(require_core());
    exports.Hyperparameters = core.serialization.object({
      earlyStoppingPatience: core.serialization.property("early_stopping_patience", core.serialization.number().optional()),
      earlyStoppingThreshold: core.serialization.property("early_stopping_threshold", core.serialization.number().optional()),
      trainBatchSize: core.serialization.property("train_batch_size", core.serialization.number().optional()),
      trainEpochs: core.serialization.property("train_epochs", core.serialization.number().optional()),
      learningRate: core.serialization.property("learning_rate", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/WandbConfig.js
var require_WandbConfig2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/WandbConfig.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.WandbConfig = void 0;
    var core = __importStar5(require_core());
    exports.WandbConfig = core.serialization.object({
      project: core.serialization.string(),
      apiKey: core.serialization.property("api_key", core.serialization.string()),
      entity: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Settings.js
var require_Settings2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Settings.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Settings = void 0;
    var core = __importStar5(require_core());
    var BaseModel_1 = require_BaseModel2();
    var Hyperparameters_1 = require_Hyperparameters2();
    var WandbConfig_1 = require_WandbConfig2();
    exports.Settings = core.serialization.object({
      baseModel: core.serialization.property("base_model", BaseModel_1.BaseModel),
      datasetId: core.serialization.property("dataset_id", core.serialization.string()),
      hyperparameters: Hyperparameters_1.Hyperparameters.optional(),
      multiLabel: core.serialization.property("multi_label", core.serialization.boolean().optional()),
      wandb: WandbConfig_1.WandbConfig.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Status.js
var require_Status2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Status.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Status = void 0;
    var core = __importStar5(require_core());
    exports.Status = core.serialization.enum_([
      "STATUS_UNSPECIFIED",
      "STATUS_FINETUNING",
      "STATUS_DEPLOYING_API",
      "STATUS_READY",
      "STATUS_FAILED",
      "STATUS_DELETED",
      "STATUS_TEMPORARILY_OFFLINE",
      "STATUS_PAUSED",
      "STATUS_QUEUED"
    ]);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/FinetunedModel.js
var require_FinetunedModel2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/FinetunedModel.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinetunedModel = void 0;
    var core = __importStar5(require_core());
    var Settings_1 = require_Settings2();
    var Status_1 = require_Status2();
    exports.FinetunedModel = core.serialization.object({
      id: core.serialization.string().optional(),
      name: core.serialization.string(),
      creatorId: core.serialization.property("creator_id", core.serialization.string().optional()),
      organizationId: core.serialization.property("organization_id", core.serialization.string().optional()),
      settings: Settings_1.Settings,
      status: Status_1.Status.optional(),
      createdAt: core.serialization.property("created_at", core.serialization.date().optional()),
      updatedAt: core.serialization.property("updated_at", core.serialization.date().optional()),
      completedAt: core.serialization.property("completed_at", core.serialization.date().optional()),
      lastUsed: core.serialization.property("last_used", core.serialization.date().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListFinetunedModelsResponse.js
var require_ListFinetunedModelsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListFinetunedModelsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListFinetunedModelsResponse = void 0;
    var core = __importStar5(require_core());
    var FinetunedModel_1 = require_FinetunedModel2();
    exports.ListFinetunedModelsResponse = core.serialization.object({
      finetunedModels: core.serialization.property("finetuned_models", core.serialization.list(FinetunedModel_1.FinetunedModel).optional()),
      nextPageToken: core.serialization.property("next_page_token", core.serialization.string().optional()),
      totalSize: core.serialization.property("total_size", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/CreateFinetunedModelResponse.js
var require_CreateFinetunedModelResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/CreateFinetunedModelResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateFinetunedModelResponse = void 0;
    var core = __importStar5(require_core());
    var FinetunedModel_1 = require_FinetunedModel2();
    exports.CreateFinetunedModelResponse = core.serialization.object({
      finetunedModel: core.serialization.property("finetuned_model", FinetunedModel_1.FinetunedModel.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/GetFinetunedModelResponse.js
var require_GetFinetunedModelResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/GetFinetunedModelResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GetFinetunedModelResponse = void 0;
    var core = __importStar5(require_core());
    var FinetunedModel_1 = require_FinetunedModel2();
    exports.GetFinetunedModelResponse = core.serialization.object({
      finetunedModel: core.serialization.property("finetuned_model", FinetunedModel_1.FinetunedModel.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/DeleteFinetunedModelResponse.js
var require_DeleteFinetunedModelResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/DeleteFinetunedModelResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteFinetunedModelResponse = void 0;
    var core = __importStar5(require_core());
    exports.DeleteFinetunedModelResponse = core.serialization.record(core.serialization.string(), core.serialization.unknown());
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/UpdateFinetunedModelResponse.js
var require_UpdateFinetunedModelResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/UpdateFinetunedModelResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UpdateFinetunedModelResponse = void 0;
    var core = __importStar5(require_core());
    var FinetunedModel_1 = require_FinetunedModel2();
    exports.UpdateFinetunedModelResponse = core.serialization.object({
      finetunedModel: core.serialization.property("finetuned_model", FinetunedModel_1.FinetunedModel.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Event.js
var require_Event2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/Event.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Event = void 0;
    var core = __importStar5(require_core());
    var Status_1 = require_Status2();
    exports.Event = core.serialization.object({
      userId: core.serialization.property("user_id", core.serialization.string().optional()),
      status: Status_1.Status.optional(),
      createdAt: core.serialization.property("created_at", core.serialization.date().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListEventsResponse.js
var require_ListEventsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListEventsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListEventsResponse = void 0;
    var core = __importStar5(require_core());
    var Event_1 = require_Event2();
    exports.ListEventsResponse = core.serialization.object({
      events: core.serialization.list(Event_1.Event).optional(),
      nextPageToken: core.serialization.property("next_page_token", core.serialization.string().optional()),
      totalSize: core.serialization.property("total_size", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/TrainingStepMetrics.js
var require_TrainingStepMetrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/TrainingStepMetrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TrainingStepMetrics = void 0;
    var core = __importStar5(require_core());
    exports.TrainingStepMetrics = core.serialization.object({
      createdAt: core.serialization.property("created_at", core.serialization.date().optional()),
      stepNumber: core.serialization.property("step_number", core.serialization.number().optional()),
      metrics: core.serialization.record(core.serialization.string(), core.serialization.number()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListTrainingStepMetricsResponse.js
var require_ListTrainingStepMetricsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/ListTrainingStepMetricsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListTrainingStepMetricsResponse = void 0;
    var core = __importStar5(require_core());
    var TrainingStepMetrics_1 = require_TrainingStepMetrics2();
    exports.ListTrainingStepMetricsResponse = core.serialization.object({
      stepMetrics: core.serialization.property("step_metrics", core.serialization.list(TrainingStepMetrics_1.TrainingStepMetrics).optional()),
      nextPageToken: core.serialization.property("next_page_token", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/index.js
var require_types10 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_BaseType2(), exports);
    __exportStar5(require_Strategy2(), exports);
    __exportStar5(require_BaseModel2(), exports);
    __exportStar5(require_Hyperparameters2(), exports);
    __exportStar5(require_WandbConfig2(), exports);
    __exportStar5(require_Settings2(), exports);
    __exportStar5(require_Status2(), exports);
    __exportStar5(require_FinetunedModel2(), exports);
    __exportStar5(require_ListFinetunedModelsResponse2(), exports);
    __exportStar5(require_CreateFinetunedModelResponse2(), exports);
    __exportStar5(require_GetFinetunedModelResponse2(), exports);
    __exportStar5(require_DeleteFinetunedModelResponse2(), exports);
    __exportStar5(require_UpdateFinetunedModelResponse2(), exports);
    __exportStar5(require_Event2(), exports);
    __exportStar5(require_ListEventsResponse2(), exports);
    __exportStar5(require_TrainingStepMetrics2(), exports);
    __exportStar5(require_ListTrainingStepMetricsResponse2(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/index.js
var require_finetuning3 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/finetuning/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_types10(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/resources/index.js
var require_resources3 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/resources/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.finetuning = void 0;
    exports.finetuning = __importStar5(require_finetuning3());
    __exportStar5(require_types10(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/client/requests/FinetuningUpdateFinetunedModelRequest.js
var require_FinetuningUpdateFinetunedModelRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/client/requests/FinetuningUpdateFinetunedModelRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinetuningUpdateFinetunedModelRequest = void 0;
    var core = __importStar5(require_core());
    var Settings_1 = require_Settings2();
    var Status_1 = require_Status2();
    exports.FinetuningUpdateFinetunedModelRequest = core.serialization.object({
      name: core.serialization.string(),
      creatorId: core.serialization.property("creator_id", core.serialization.string().optional()),
      organizationId: core.serialization.property("organization_id", core.serialization.string().optional()),
      settings: Settings_1.Settings,
      status: Status_1.Status.optional(),
      createdAt: core.serialization.property("created_at", core.serialization.date().optional()),
      updatedAt: core.serialization.property("updated_at", core.serialization.date().optional()),
      completedAt: core.serialization.property("completed_at", core.serialization.date().optional()),
      lastUsed: core.serialization.property("last_used", core.serialization.date().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/client/requests/index.js
var require_requests10 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinetuningUpdateFinetunedModelRequest = void 0;
    var FinetuningUpdateFinetunedModelRequest_1 = require_FinetuningUpdateFinetunedModelRequest();
    Object.defineProperty(exports, "FinetuningUpdateFinetunedModelRequest", { enumerable: true, get: function() {
      return FinetuningUpdateFinetunedModelRequest_1.FinetuningUpdateFinetunedModelRequest;
    } });
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/client/index.js
var require_client13 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests10(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/finetuning/index.js
var require_finetuning4 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/finetuning/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_resources3(), exports);
    __exportStar5(require_client13(), exports);
  }
});

// node_modules/cohere-ai/serialization/types/CreateConnectorOAuth.js
var require_CreateConnectorOAuth2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CreateConnectorOAuth.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateConnectorOAuth = void 0;
    var core = __importStar5(require_core());
    exports.CreateConnectorOAuth = core.serialization.object({
      clientId: core.serialization.property("client_id", core.serialization.string().optional()),
      clientSecret: core.serialization.property("client_secret", core.serialization.string().optional()),
      authorizeUrl: core.serialization.property("authorize_url", core.serialization.string().optional()),
      tokenUrl: core.serialization.property("token_url", core.serialization.string().optional()),
      scope: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/AuthTokenType.js
var require_AuthTokenType2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/AuthTokenType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AuthTokenType = void 0;
    var core = __importStar5(require_core());
    exports.AuthTokenType = core.serialization.enum_(["bearer", "basic", "noscheme"]);
  }
});

// node_modules/cohere-ai/serialization/types/CreateConnectorServiceAuth.js
var require_CreateConnectorServiceAuth2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CreateConnectorServiceAuth.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateConnectorServiceAuth = void 0;
    var core = __importStar5(require_core());
    var AuthTokenType_1 = require_AuthTokenType2();
    exports.CreateConnectorServiceAuth = core.serialization.object({
      type: AuthTokenType_1.AuthTokenType,
      token: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/resources/connectors/client/requests/CreateConnectorRequest.js
var require_CreateConnectorRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/connectors/client/requests/CreateConnectorRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateConnectorRequest = void 0;
    var core = __importStar5(require_core());
    var CreateConnectorOAuth_1 = require_CreateConnectorOAuth2();
    var CreateConnectorServiceAuth_1 = require_CreateConnectorServiceAuth2();
    exports.CreateConnectorRequest = core.serialization.object({
      name: core.serialization.string(),
      description: core.serialization.string().optional(),
      url: core.serialization.string(),
      excludes: core.serialization.list(core.serialization.string()).optional(),
      oauth: CreateConnectorOAuth_1.CreateConnectorOAuth.optional(),
      active: core.serialization.boolean().optional(),
      continueOnFailure: core.serialization.property("continue_on_failure", core.serialization.boolean().optional()),
      serviceAuth: core.serialization.property("service_auth", CreateConnectorServiceAuth_1.CreateConnectorServiceAuth.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/connectors/client/requests/UpdateConnectorRequest.js
var require_UpdateConnectorRequest = __commonJS({
  "node_modules/cohere-ai/serialization/resources/connectors/client/requests/UpdateConnectorRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UpdateConnectorRequest = void 0;
    var core = __importStar5(require_core());
    var CreateConnectorOAuth_1 = require_CreateConnectorOAuth2();
    var CreateConnectorServiceAuth_1 = require_CreateConnectorServiceAuth2();
    exports.UpdateConnectorRequest = core.serialization.object({
      name: core.serialization.string().optional(),
      url: core.serialization.string().optional(),
      excludes: core.serialization.list(core.serialization.string()).optional(),
      oauth: CreateConnectorOAuth_1.CreateConnectorOAuth.optional(),
      active: core.serialization.boolean().optional(),
      continueOnFailure: core.serialization.property("continue_on_failure", core.serialization.boolean().optional()),
      serviceAuth: core.serialization.property("service_auth", CreateConnectorServiceAuth_1.CreateConnectorServiceAuth.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/resources/connectors/client/requests/index.js
var require_requests11 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/connectors/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UpdateConnectorRequest = exports.CreateConnectorRequest = void 0;
    var CreateConnectorRequest_1 = require_CreateConnectorRequest();
    Object.defineProperty(exports, "CreateConnectorRequest", { enumerable: true, get: function() {
      return CreateConnectorRequest_1.CreateConnectorRequest;
    } });
    var UpdateConnectorRequest_1 = require_UpdateConnectorRequest();
    Object.defineProperty(exports, "UpdateConnectorRequest", { enumerable: true, get: function() {
      return UpdateConnectorRequest_1.UpdateConnectorRequest;
    } });
  }
});

// node_modules/cohere-ai/serialization/resources/connectors/client/index.js
var require_client14 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/connectors/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests11(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/connectors/index.js
var require_connectors2 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/connectors/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_client14(), exports);
  }
});

// node_modules/cohere-ai/serialization/resources/index.js
var require_resources4 = __commonJS({
  "node_modules/cohere-ai/serialization/resources/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.connectors = exports.finetuning = exports.datasets = exports.embedJobs = exports.v2 = void 0;
    exports.v2 = __importStar5(require_v22());
    __exportStar5(require_types7(), exports);
    exports.embedJobs = __importStar5(require_embedJobs2());
    __exportStar5(require_types8(), exports);
    exports.datasets = __importStar5(require_datasets2());
    __exportStar5(require_types9(), exports);
    exports.finetuning = __importStar5(require_finetuning4());
    __exportStar5(require_requests8(), exports);
    __exportStar5(require_requests9(), exports);
    exports.connectors = __importStar5(require_connectors2());
    __exportStar5(require_requests11(), exports);
    __exportStar5(require_requests10(), exports);
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamRequestPromptTruncation.js
var require_ChatStreamRequestPromptTruncation2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamRequestPromptTruncation.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestPromptTruncation = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamRequestPromptTruncation = core.serialization.enum_(["OFF", "AUTO", "AUTO_PRESERVE_ORDER"]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamRequestCitationQuality.js
var require_ChatStreamRequestCitationQuality2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamRequestCitationQuality.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestCitationQuality = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamRequestCitationQuality = core.serialization.enum_(["fast", "accurate", "off"]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamRequestConnectorsSearchOptions.js
var require_ChatStreamRequestConnectorsSearchOptions2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamRequestConnectorsSearchOptions.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestConnectorsSearchOptions = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamRequestConnectorsSearchOptions = core.serialization.object({
      seed: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamRequestSafetyMode.js
var require_ChatStreamRequestSafetyMode2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamRequestSafetyMode.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequestSafetyMode = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamRequestSafetyMode = core.serialization.enum_(["CONTEXTUAL", "STRICT", "NONE"]);
  }
});

// node_modules/cohere-ai/serialization/types/UnprocessableEntityErrorBody.js
var require_UnprocessableEntityErrorBody2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/UnprocessableEntityErrorBody.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UnprocessableEntityErrorBody = void 0;
    var core = __importStar5(require_core());
    exports.UnprocessableEntityErrorBody = core.serialization.object({
      data: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/TooManyRequestsErrorBody.js
var require_TooManyRequestsErrorBody2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/TooManyRequestsErrorBody.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TooManyRequestsErrorBody = void 0;
    var core = __importStar5(require_core());
    exports.TooManyRequestsErrorBody = core.serialization.object({
      data: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClientClosedRequestErrorBody.js
var require_ClientClosedRequestErrorBody2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClientClosedRequestErrorBody.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClientClosedRequestErrorBody = void 0;
    var core = __importStar5(require_core());
    exports.ClientClosedRequestErrorBody = core.serialization.object({
      data: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/NotImplementedErrorBody.js
var require_NotImplementedErrorBody2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/NotImplementedErrorBody.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NotImplementedErrorBody = void 0;
    var core = __importStar5(require_core());
    exports.NotImplementedErrorBody = core.serialization.object({
      data: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/GatewayTimeoutErrorBody.js
var require_GatewayTimeoutErrorBody2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GatewayTimeoutErrorBody.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GatewayTimeoutErrorBody = void 0;
    var core = __importStar5(require_core());
    exports.GatewayTimeoutErrorBody = core.serialization.object({
      data: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatRequestPromptTruncation.js
var require_ChatRequestPromptTruncation2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatRequestPromptTruncation.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestPromptTruncation = void 0;
    var core = __importStar5(require_core());
    exports.ChatRequestPromptTruncation = core.serialization.enum_(["OFF", "AUTO", "AUTO_PRESERVE_ORDER"]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatRequestCitationQuality.js
var require_ChatRequestCitationQuality2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatRequestCitationQuality.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestCitationQuality = void 0;
    var core = __importStar5(require_core());
    exports.ChatRequestCitationQuality = core.serialization.enum_(["fast", "accurate", "off"]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatRequestConnectorsSearchOptions.js
var require_ChatRequestConnectorsSearchOptions2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatRequestConnectorsSearchOptions.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestConnectorsSearchOptions = void 0;
    var core = __importStar5(require_core());
    exports.ChatRequestConnectorsSearchOptions = core.serialization.object({
      seed: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatRequestSafetyMode.js
var require_ChatRequestSafetyMode2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatRequestSafetyMode.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequestSafetyMode = void 0;
    var core = __importStar5(require_core());
    exports.ChatRequestSafetyMode = core.serialization.enum_(["CONTEXTUAL", "STRICT", "NONE"]);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamRequestTruncate.js
var require_GenerateStreamRequestTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamRequestTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamRequestTruncate = void 0;
    var core = __importStar5(require_core());
    exports.GenerateStreamRequestTruncate = core.serialization.enum_(["NONE", "START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamRequestReturnLikelihoods.js
var require_GenerateStreamRequestReturnLikelihoods2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamRequestReturnLikelihoods.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamRequestReturnLikelihoods = void 0;
    var core = __importStar5(require_core());
    exports.GenerateStreamRequestReturnLikelihoods = core.serialization.enum_(["GENERATION", "ALL", "NONE"]);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateRequestTruncate.js
var require_GenerateRequestTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateRequestTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateRequestTruncate = void 0;
    var core = __importStar5(require_core());
    exports.GenerateRequestTruncate = core.serialization.enum_(["NONE", "START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateRequestReturnLikelihoods.js
var require_GenerateRequestReturnLikelihoods2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateRequestReturnLikelihoods.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateRequestReturnLikelihoods = void 0;
    var core = __importStar5(require_core());
    exports.GenerateRequestReturnLikelihoods = core.serialization.enum_(["GENERATION", "ALL", "NONE"]);
  }
});

// node_modules/cohere-ai/serialization/types/EmbedRequestTruncate.js
var require_EmbedRequestTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedRequestTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedRequestTruncate = void 0;
    var core = __importStar5(require_core());
    exports.EmbedRequestTruncate = core.serialization.enum_(["NONE", "START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/types/ApiMetaApiVersion.js
var require_ApiMetaApiVersion2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ApiMetaApiVersion.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApiMetaApiVersion = void 0;
    var core = __importStar5(require_core());
    exports.ApiMetaApiVersion = core.serialization.object({
      version: core.serialization.string(),
      isDeprecated: core.serialization.property("is_deprecated", core.serialization.boolean().optional()),
      isExperimental: core.serialization.property("is_experimental", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ApiMetaBilledUnits.js
var require_ApiMetaBilledUnits2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ApiMetaBilledUnits.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApiMetaBilledUnits = void 0;
    var core = __importStar5(require_core());
    exports.ApiMetaBilledUnits = core.serialization.object({
      inputTokens: core.serialization.property("input_tokens", core.serialization.number().optional()),
      outputTokens: core.serialization.property("output_tokens", core.serialization.number().optional()),
      searchUnits: core.serialization.property("search_units", core.serialization.number().optional()),
      classifications: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ApiMetaTokens.js
var require_ApiMetaTokens2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ApiMetaTokens.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApiMetaTokens = void 0;
    var core = __importStar5(require_core());
    exports.ApiMetaTokens = core.serialization.object({
      inputTokens: core.serialization.property("input_tokens", core.serialization.number().optional()),
      outputTokens: core.serialization.property("output_tokens", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ApiMeta.js
var require_ApiMeta2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ApiMeta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ApiMeta = void 0;
    var core = __importStar5(require_core());
    var ApiMetaApiVersion_1 = require_ApiMetaApiVersion2();
    var ApiMetaBilledUnits_1 = require_ApiMetaBilledUnits2();
    var ApiMetaTokens_1 = require_ApiMetaTokens2();
    exports.ApiMeta = core.serialization.object({
      apiVersion: core.serialization.property("api_version", ApiMetaApiVersion_1.ApiMetaApiVersion.optional()),
      billedUnits: core.serialization.property("billed_units", ApiMetaBilledUnits_1.ApiMetaBilledUnits.optional()),
      tokens: ApiMetaTokens_1.ApiMetaTokens.optional(),
      warnings: core.serialization.list(core.serialization.string()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/EmbedFloatsResponse.js
var require_EmbedFloatsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedFloatsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedFloatsResponse = void 0;
    var core = __importStar5(require_core());
    var ApiMeta_1 = require_ApiMeta2();
    exports.EmbedFloatsResponse = core.serialization.object({
      id: core.serialization.string(),
      embeddings: core.serialization.list(core.serialization.list(core.serialization.number())),
      texts: core.serialization.list(core.serialization.string()),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/EmbedByTypeResponseEmbeddings.js
var require_EmbedByTypeResponseEmbeddings2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedByTypeResponseEmbeddings.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedByTypeResponseEmbeddings = void 0;
    var core = __importStar5(require_core());
    exports.EmbedByTypeResponseEmbeddings = core.serialization.object({
      float: core.serialization.list(core.serialization.list(core.serialization.number())).optional(),
      int8: core.serialization.list(core.serialization.list(core.serialization.number())).optional(),
      uint8: core.serialization.list(core.serialization.list(core.serialization.number())).optional(),
      binary: core.serialization.list(core.serialization.list(core.serialization.number())).optional(),
      ubinary: core.serialization.list(core.serialization.list(core.serialization.number())).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/EmbedByTypeResponse.js
var require_EmbedByTypeResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedByTypeResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedByTypeResponse = void 0;
    var core = __importStar5(require_core());
    var EmbedByTypeResponseEmbeddings_1 = require_EmbedByTypeResponseEmbeddings2();
    var ApiMeta_1 = require_ApiMeta2();
    exports.EmbedByTypeResponse = core.serialization.object({
      id: core.serialization.string(),
      embeddings: EmbedByTypeResponseEmbeddings_1.EmbedByTypeResponseEmbeddings,
      texts: core.serialization.list(core.serialization.string()),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/EmbedResponse.js
var require_EmbedResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedResponse = void 0;
    var core = __importStar5(require_core());
    var EmbedFloatsResponse_1 = require_EmbedFloatsResponse2();
    var EmbedByTypeResponse_1 = require_EmbedByTypeResponse2();
    exports.EmbedResponse = core.serialization.union(core.serialization.discriminant("responseType", "response_type"), {
      embeddings_floats: EmbedFloatsResponse_1.EmbedFloatsResponse,
      embeddings_by_type: EmbedByTypeResponse_1.EmbedByTypeResponse
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/types/RerankDocument.js
var require_RerankDocument2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankDocument.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankDocument = void 0;
    var core = __importStar5(require_core());
    exports.RerankDocument = core.serialization.record(core.serialization.string(), core.serialization.string());
  }
});

// node_modules/cohere-ai/serialization/types/RerankRequestDocumentsItem.js
var require_RerankRequestDocumentsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankRequestDocumentsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankRequestDocumentsItem = void 0;
    var core = __importStar5(require_core());
    var RerankDocument_1 = require_RerankDocument2();
    exports.RerankRequestDocumentsItem = core.serialization.undiscriminatedUnion([core.serialization.string(), RerankDocument_1.RerankDocument]);
  }
});

// node_modules/cohere-ai/serialization/types/RerankResponseResultsItemDocument.js
var require_RerankResponseResultsItemDocument2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankResponseResultsItemDocument.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankResponseResultsItemDocument = void 0;
    var core = __importStar5(require_core());
    exports.RerankResponseResultsItemDocument = core.serialization.object({
      text: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/types/RerankResponseResultsItem.js
var require_RerankResponseResultsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankResponseResultsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankResponseResultsItem = void 0;
    var core = __importStar5(require_core());
    var RerankResponseResultsItemDocument_1 = require_RerankResponseResultsItemDocument2();
    exports.RerankResponseResultsItem = core.serialization.object({
      document: RerankResponseResultsItemDocument_1.RerankResponseResultsItemDocument.optional(),
      index: core.serialization.number(),
      relevanceScore: core.serialization.property("relevance_score", core.serialization.number())
    });
  }
});

// node_modules/cohere-ai/serialization/types/RerankResponse.js
var require_RerankResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankResponse = void 0;
    var core = __importStar5(require_core());
    var RerankResponseResultsItem_1 = require_RerankResponseResultsItem2();
    var ApiMeta_1 = require_ApiMeta2();
    exports.RerankResponse = core.serialization.object({
      id: core.serialization.string().optional(),
      results: core.serialization.list(RerankResponseResultsItem_1.RerankResponseResultsItem),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyRequestTruncate.js
var require_ClassifyRequestTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyRequestTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyRequestTruncate = void 0;
    var core = __importStar5(require_core());
    exports.ClassifyRequestTruncate = core.serialization.enum_(["NONE", "START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItemLabelsValue.js
var require_ClassifyResponseClassificationsItemLabelsValue2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItemLabelsValue.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyResponseClassificationsItemLabelsValue = void 0;
    var core = __importStar5(require_core());
    exports.ClassifyResponseClassificationsItemLabelsValue = core.serialization.object({
      confidence: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItemClassificationType.js
var require_ClassifyResponseClassificationsItemClassificationType2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItemClassificationType.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyResponseClassificationsItemClassificationType = void 0;
    var core = __importStar5(require_core());
    exports.ClassifyResponseClassificationsItemClassificationType = core.serialization.enum_(["single-label", "multi-label"]);
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItem.js
var require_ClassifyResponseClassificationsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyResponseClassificationsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyResponseClassificationsItem = void 0;
    var core = __importStar5(require_core());
    var ClassifyResponseClassificationsItemLabelsValue_1 = require_ClassifyResponseClassificationsItemLabelsValue2();
    var ClassifyResponseClassificationsItemClassificationType_1 = require_ClassifyResponseClassificationsItemClassificationType2();
    exports.ClassifyResponseClassificationsItem = core.serialization.object({
      id: core.serialization.string(),
      input: core.serialization.string().optional(),
      prediction: core.serialization.string().optional(),
      predictions: core.serialization.list(core.serialization.string()),
      confidence: core.serialization.number().optional(),
      confidences: core.serialization.list(core.serialization.number()),
      labels: core.serialization.record(core.serialization.string(), ClassifyResponseClassificationsItemLabelsValue_1.ClassifyResponseClassificationsItemLabelsValue),
      classificationType: core.serialization.property("classification_type", ClassifyResponseClassificationsItemClassificationType_1.ClassifyResponseClassificationsItemClassificationType)
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyResponse.js
var require_ClassifyResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyResponse = void 0;
    var core = __importStar5(require_core());
    var ClassifyResponseClassificationsItem_1 = require_ClassifyResponseClassificationsItem2();
    var ApiMeta_1 = require_ApiMeta2();
    exports.ClassifyResponse = core.serialization.object({
      id: core.serialization.string(),
      classifications: core.serialization.list(ClassifyResponseClassificationsItem_1.ClassifyResponseClassificationsItem),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/SummarizeRequestLength.js
var require_SummarizeRequestLength2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SummarizeRequestLength.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestLength = void 0;
    var core = __importStar5(require_core());
    exports.SummarizeRequestLength = core.serialization.enum_(["short", "medium", "long"]);
  }
});

// node_modules/cohere-ai/serialization/types/SummarizeRequestFormat.js
var require_SummarizeRequestFormat2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SummarizeRequestFormat.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestFormat = void 0;
    var core = __importStar5(require_core());
    exports.SummarizeRequestFormat = core.serialization.enum_(["paragraph", "bullets"]);
  }
});

// node_modules/cohere-ai/serialization/types/SummarizeRequestExtractiveness.js
var require_SummarizeRequestExtractiveness2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SummarizeRequestExtractiveness.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequestExtractiveness = void 0;
    var core = __importStar5(require_core());
    exports.SummarizeRequestExtractiveness = core.serialization.enum_(["low", "medium", "high"]);
  }
});

// node_modules/cohere-ai/serialization/types/SummarizeResponse.js
var require_SummarizeResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SummarizeResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeResponse = void 0;
    var core = __importStar5(require_core());
    var ApiMeta_1 = require_ApiMeta2();
    exports.SummarizeResponse = core.serialization.object({
      id: core.serialization.string().optional(),
      summary: core.serialization.string().optional(),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/TokenizeResponse.js
var require_TokenizeResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/TokenizeResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenizeResponse = void 0;
    var core = __importStar5(require_core());
    var ApiMeta_1 = require_ApiMeta2();
    exports.TokenizeResponse = core.serialization.object({
      tokens: core.serialization.list(core.serialization.number()),
      tokenStrings: core.serialization.property("token_strings", core.serialization.list(core.serialization.string())),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/DetokenizeResponse.js
var require_DetokenizeResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/DetokenizeResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DetokenizeResponse = void 0;
    var core = __importStar5(require_core());
    var ApiMeta_1 = require_ApiMeta2();
    exports.DetokenizeResponse = core.serialization.object({
      text: core.serialization.string(),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/CheckApiKeyResponse.js
var require_CheckApiKeyResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CheckApiKeyResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CheckApiKeyResponse = void 0;
    var core = __importStar5(require_core());
    exports.CheckApiKeyResponse = core.serialization.object({
      valid: core.serialization.boolean(),
      organizationId: core.serialization.property("organization_id", core.serialization.string().optional()),
      ownerId: core.serialization.property("owner_id", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ToolCall.js
var require_ToolCall3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ToolCall.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCall = void 0;
    var core = __importStar5(require_core());
    exports.ToolCall = core.serialization.object({
      name: core.serialization.string(),
      parameters: core.serialization.record(core.serialization.string(), core.serialization.unknown())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatMessage.js
var require_ChatMessage3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatMessage = void 0;
    var core = __importStar5(require_core());
    var ToolCall_1 = require_ToolCall3();
    exports.ChatMessage = core.serialization.object({
      message: core.serialization.string(),
      toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall_1.ToolCall).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ToolResult.js
var require_ToolResult2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ToolResult.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolResult = void 0;
    var core = __importStar5(require_core());
    var ToolCall_1 = require_ToolCall3();
    exports.ToolResult = core.serialization.object({
      call: ToolCall_1.ToolCall,
      outputs: core.serialization.list(core.serialization.record(core.serialization.string(), core.serialization.unknown()))
    });
  }
});

// node_modules/cohere-ai/serialization/types/ToolMessage.js
var require_ToolMessage3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ToolMessage.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolMessage = void 0;
    var core = __importStar5(require_core());
    var ToolResult_1 = require_ToolResult2();
    exports.ToolMessage = core.serialization.object({
      toolResults: core.serialization.property("tool_results", core.serialization.list(ToolResult_1.ToolResult).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/Message.js
var require_Message3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Message.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Message = void 0;
    var core = __importStar5(require_core());
    var ChatMessage_1 = require_ChatMessage3();
    var ToolMessage_1 = require_ToolMessage3();
    exports.Message = core.serialization.union("role", {
      CHATBOT: ChatMessage_1.ChatMessage,
      SYSTEM: ChatMessage_1.ChatMessage,
      USER: ChatMessage_1.ChatMessage,
      TOOL: ToolMessage_1.ToolMessage
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatConnector.js
var require_ChatConnector2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatConnector.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatConnector = void 0;
    var core = __importStar5(require_core());
    exports.ChatConnector = core.serialization.object({
      id: core.serialization.string(),
      userAccessToken: core.serialization.property("user_access_token", core.serialization.string().optional()),
      continueOnFailure: core.serialization.property("continue_on_failure", core.serialization.boolean().optional()),
      options: core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ToolParameterDefinitionsValue.js
var require_ToolParameterDefinitionsValue2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ToolParameterDefinitionsValue.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolParameterDefinitionsValue = void 0;
    var core = __importStar5(require_core());
    exports.ToolParameterDefinitionsValue = core.serialization.object({
      description: core.serialization.string().optional(),
      type: core.serialization.string(),
      required: core.serialization.boolean().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/Tool.js
var require_Tool3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Tool.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tool = void 0;
    var core = __importStar5(require_core());
    var ToolParameterDefinitionsValue_1 = require_ToolParameterDefinitionsValue2();
    exports.Tool = core.serialization.object({
      name: core.serialization.string(),
      description: core.serialization.string(),
      parameterDefinitions: core.serialization.property("parameter_definitions", core.serialization.record(core.serialization.string(), ToolParameterDefinitionsValue_1.ToolParameterDefinitionsValue).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/JsonResponseFormat.js
var require_JsonResponseFormat3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/JsonResponseFormat.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.JsonResponseFormat = void 0;
    var core = __importStar5(require_core());
    exports.JsonResponseFormat = core.serialization.object({
      schema: core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ResponseFormat.js
var require_ResponseFormat3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ResponseFormat.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ResponseFormat = void 0;
    var core = __importStar5(require_core());
    var TextResponseFormat_1 = require_TextResponseFormat2();
    var JsonResponseFormat_1 = require_JsonResponseFormat3();
    exports.ResponseFormat = core.serialization.union("type", {
      text: TextResponseFormat_1.TextResponseFormat,
      json_object: JsonResponseFormat_1.JsonResponseFormat
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatCitation.js
var require_ChatCitation2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatCitation.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCitation = void 0;
    var core = __importStar5(require_core());
    exports.ChatCitation = core.serialization.object({
      start: core.serialization.number(),
      end: core.serialization.number(),
      text: core.serialization.string(),
      documentIds: core.serialization.property("document_ids", core.serialization.list(core.serialization.string()))
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatSearchQuery.js
var require_ChatSearchQuery2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatSearchQuery.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatSearchQuery = void 0;
    var core = __importStar5(require_core());
    exports.ChatSearchQuery = core.serialization.object({
      text: core.serialization.string(),
      generationId: core.serialization.property("generation_id", core.serialization.string())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatSearchResultConnector.js
var require_ChatSearchResultConnector2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatSearchResultConnector.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatSearchResultConnector = void 0;
    var core = __importStar5(require_core());
    exports.ChatSearchResultConnector = core.serialization.object({
      id: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatSearchResult.js
var require_ChatSearchResult2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatSearchResult.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatSearchResult = void 0;
    var core = __importStar5(require_core());
    var ChatSearchQuery_1 = require_ChatSearchQuery2();
    var ChatSearchResultConnector_1 = require_ChatSearchResultConnector2();
    exports.ChatSearchResult = core.serialization.object({
      searchQuery: core.serialization.property("search_query", ChatSearchQuery_1.ChatSearchQuery.optional()),
      connector: ChatSearchResultConnector_1.ChatSearchResultConnector,
      documentIds: core.serialization.property("document_ids", core.serialization.list(core.serialization.string())),
      errorMessage: core.serialization.property("error_message", core.serialization.string().optional()),
      continueOnFailure: core.serialization.property("continue_on_failure", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/FinishReason.js
var require_FinishReason2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/FinishReason.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinishReason = void 0;
    var core = __importStar5(require_core());
    exports.FinishReason = core.serialization.enum_([
      "COMPLETE",
      "STOP_SEQUENCE",
      "ERROR",
      "ERROR_TOXIC",
      "ERROR_LIMIT",
      "USER_CANCEL",
      "MAX_TOKENS"
    ]);
  }
});

// node_modules/cohere-ai/serialization/types/NonStreamedChatResponse.js
var require_NonStreamedChatResponse3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/NonStreamedChatResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NonStreamedChatResponse = void 0;
    var core = __importStar5(require_core());
    var ChatCitation_1 = require_ChatCitation2();
    var ChatDocument_1 = require_ChatDocument2();
    var ChatSearchQuery_1 = require_ChatSearchQuery2();
    var ChatSearchResult_1 = require_ChatSearchResult2();
    var FinishReason_1 = require_FinishReason2();
    var ToolCall_1 = require_ToolCall3();
    var Message_1 = require_Message3();
    var ApiMeta_1 = require_ApiMeta2();
    exports.NonStreamedChatResponse = core.serialization.object({
      text: core.serialization.string(),
      generationId: core.serialization.property("generation_id", core.serialization.string().optional()),
      citations: core.serialization.list(ChatCitation_1.ChatCitation).optional(),
      documents: core.serialization.list(ChatDocument_1.ChatDocument).optional(),
      isSearchRequired: core.serialization.property("is_search_required", core.serialization.boolean().optional()),
      searchQueries: core.serialization.property("search_queries", core.serialization.list(ChatSearchQuery_1.ChatSearchQuery).optional()),
      searchResults: core.serialization.property("search_results", core.serialization.list(ChatSearchResult_1.ChatSearchResult).optional()),
      finishReason: core.serialization.property("finish_reason", FinishReason_1.FinishReason.optional()),
      toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall_1.ToolCall).optional()),
      chatHistory: core.serialization.property("chat_history", core.serialization.list(Message_1.Message).optional()),
      prompt: core.serialization.string().optional(),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamEvent.js
var require_ChatStreamEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamEvent = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamEvent = core.serialization.object({});
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamStartEvent.js
var require_ChatStreamStartEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamStartEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamStartEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatStreamStartEvent = core.serialization.object({
      generationId: core.serialization.property("generation_id", core.serialization.string())
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatSearchQueriesGenerationEvent.js
var require_ChatSearchQueriesGenerationEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatSearchQueriesGenerationEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatSearchQueriesGenerationEvent = void 0;
    var core = __importStar5(require_core());
    var ChatSearchQuery_1 = require_ChatSearchQuery2();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatSearchQueriesGenerationEvent = core.serialization.object({
      searchQueries: core.serialization.property("search_queries", core.serialization.list(ChatSearchQuery_1.ChatSearchQuery))
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatSearchResultsEvent.js
var require_ChatSearchResultsEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatSearchResultsEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatSearchResultsEvent = void 0;
    var core = __importStar5(require_core());
    var ChatSearchResult_1 = require_ChatSearchResult2();
    var ChatDocument_1 = require_ChatDocument2();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatSearchResultsEvent = core.serialization.object({
      searchResults: core.serialization.property("search_results", core.serialization.list(ChatSearchResult_1.ChatSearchResult).optional()),
      documents: core.serialization.list(ChatDocument_1.ChatDocument).optional()
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatTextGenerationEvent.js
var require_ChatTextGenerationEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatTextGenerationEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatTextGenerationEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatTextGenerationEvent = core.serialization.object({
      text: core.serialization.string()
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatCitationGenerationEvent.js
var require_ChatCitationGenerationEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatCitationGenerationEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatCitationGenerationEvent = void 0;
    var core = __importStar5(require_core());
    var ChatCitation_1 = require_ChatCitation2();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatCitationGenerationEvent = core.serialization.object({
      citations: core.serialization.list(ChatCitation_1.ChatCitation)
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatToolCallsGenerationEvent.js
var require_ChatToolCallsGenerationEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatToolCallsGenerationEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallsGenerationEvent = void 0;
    var core = __importStar5(require_core());
    var ToolCall_1 = require_ToolCall3();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatToolCallsGenerationEvent = core.serialization.object({
      text: core.serialization.string().optional(),
      toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall_1.ToolCall))
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamEndEventFinishReason.js
var require_ChatStreamEndEventFinishReason2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamEndEventFinishReason.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamEndEventFinishReason = void 0;
    var core = __importStar5(require_core());
    exports.ChatStreamEndEventFinishReason = core.serialization.enum_(["COMPLETE", "ERROR_LIMIT", "MAX_TOKENS", "ERROR", "ERROR_TOXIC"]);
  }
});

// node_modules/cohere-ai/serialization/types/ChatStreamEndEvent.js
var require_ChatStreamEndEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatStreamEndEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamEndEvent = void 0;
    var core = __importStar5(require_core());
    var ChatStreamEndEventFinishReason_1 = require_ChatStreamEndEventFinishReason2();
    var NonStreamedChatResponse_1 = require_NonStreamedChatResponse3();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatStreamEndEvent = core.serialization.object({
      finishReason: core.serialization.property("finish_reason", ChatStreamEndEventFinishReason_1.ChatStreamEndEventFinishReason),
      response: NonStreamedChatResponse_1.NonStreamedChatResponse
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/ToolCallDelta.js
var require_ToolCallDelta2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ToolCallDelta.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ToolCallDelta = void 0;
    var core = __importStar5(require_core());
    exports.ToolCallDelta = core.serialization.object({
      name: core.serialization.string().optional(),
      index: core.serialization.number().optional(),
      parameters: core.serialization.string().optional(),
      text: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatToolCallsChunkEvent.js
var require_ChatToolCallsChunkEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatToolCallsChunkEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatToolCallsChunkEvent = void 0;
    var core = __importStar5(require_core());
    var ToolCallDelta_1 = require_ToolCallDelta2();
    var ChatStreamEvent_1 = require_ChatStreamEvent2();
    exports.ChatToolCallsChunkEvent = core.serialization.object({
      toolCallDelta: core.serialization.property("tool_call_delta", ToolCallDelta_1.ToolCallDelta)
    }).extend(ChatStreamEvent_1.ChatStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/StreamedChatResponse.js
var require_StreamedChatResponse3 = __commonJS({
  "node_modules/cohere-ai/serialization/types/StreamedChatResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StreamedChatResponse = void 0;
    var core = __importStar5(require_core());
    var ChatStreamStartEvent_1 = require_ChatStreamStartEvent2();
    var ChatSearchQueriesGenerationEvent_1 = require_ChatSearchQueriesGenerationEvent2();
    var ChatSearchResultsEvent_1 = require_ChatSearchResultsEvent2();
    var ChatTextGenerationEvent_1 = require_ChatTextGenerationEvent2();
    var ChatCitationGenerationEvent_1 = require_ChatCitationGenerationEvent2();
    var ChatToolCallsGenerationEvent_1 = require_ChatToolCallsGenerationEvent2();
    var ChatStreamEndEvent_1 = require_ChatStreamEndEvent2();
    var ChatToolCallsChunkEvent_1 = require_ChatToolCallsChunkEvent2();
    exports.StreamedChatResponse = core.serialization.union(core.serialization.discriminant("eventType", "event_type"), {
      "stream-start": ChatStreamStartEvent_1.ChatStreamStartEvent,
      "search-queries-generation": ChatSearchQueriesGenerationEvent_1.ChatSearchQueriesGenerationEvent,
      "search-results": ChatSearchResultsEvent_1.ChatSearchResultsEvent,
      "text-generation": ChatTextGenerationEvent_1.ChatTextGenerationEvent,
      "citation-generation": ChatCitationGenerationEvent_1.ChatCitationGenerationEvent,
      "tool-calls-generation": ChatToolCallsGenerationEvent_1.ChatToolCallsGenerationEvent,
      "stream-end": ChatStreamEndEvent_1.ChatStreamEndEvent,
      "tool-calls-chunk": ChatToolCallsChunkEvent_1.ChatToolCallsChunkEvent
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/types/SingleGenerationTokenLikelihoodsItem.js
var require_SingleGenerationTokenLikelihoodsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SingleGenerationTokenLikelihoodsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SingleGenerationTokenLikelihoodsItem = void 0;
    var core = __importStar5(require_core());
    exports.SingleGenerationTokenLikelihoodsItem = core.serialization.object({
      token: core.serialization.string(),
      likelihood: core.serialization.number()
    });
  }
});

// node_modules/cohere-ai/serialization/types/SingleGeneration.js
var require_SingleGeneration2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SingleGeneration.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SingleGeneration = void 0;
    var core = __importStar5(require_core());
    var SingleGenerationTokenLikelihoodsItem_1 = require_SingleGenerationTokenLikelihoodsItem2();
    exports.SingleGeneration = core.serialization.object({
      id: core.serialization.string(),
      text: core.serialization.string(),
      index: core.serialization.number().optional(),
      likelihood: core.serialization.number().optional(),
      tokenLikelihoods: core.serialization.property("token_likelihoods", core.serialization.list(SingleGenerationTokenLikelihoodsItem_1.SingleGenerationTokenLikelihoodsItem).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/Generation.js
var require_Generation2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Generation.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Generation = void 0;
    var core = __importStar5(require_core());
    var SingleGeneration_1 = require_SingleGeneration2();
    var ApiMeta_1 = require_ApiMeta2();
    exports.Generation = core.serialization.object({
      id: core.serialization.string(),
      prompt: core.serialization.string().optional(),
      generations: core.serialization.list(SingleGeneration_1.SingleGeneration),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamEvent.js
var require_GenerateStreamEvent2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamEvent.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamEvent = void 0;
    var core = __importStar5(require_core());
    exports.GenerateStreamEvent = core.serialization.object({});
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamText.js
var require_GenerateStreamText2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamText.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamText = void 0;
    var core = __importStar5(require_core());
    var GenerateStreamEvent_1 = require_GenerateStreamEvent2();
    exports.GenerateStreamText = core.serialization.object({
      text: core.serialization.string(),
      index: core.serialization.number().optional(),
      isFinished: core.serialization.property("is_finished", core.serialization.boolean())
    }).extend(GenerateStreamEvent_1.GenerateStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/SingleGenerationInStream.js
var require_SingleGenerationInStream2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/SingleGenerationInStream.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SingleGenerationInStream = void 0;
    var core = __importStar5(require_core());
    var FinishReason_1 = require_FinishReason2();
    exports.SingleGenerationInStream = core.serialization.object({
      id: core.serialization.string(),
      text: core.serialization.string(),
      index: core.serialization.number().optional(),
      finishReason: core.serialization.property("finish_reason", FinishReason_1.FinishReason)
    });
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamEndResponse.js
var require_GenerateStreamEndResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamEndResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamEndResponse = void 0;
    var core = __importStar5(require_core());
    var SingleGenerationInStream_1 = require_SingleGenerationInStream2();
    exports.GenerateStreamEndResponse = core.serialization.object({
      id: core.serialization.string(),
      prompt: core.serialization.string().optional(),
      generations: core.serialization.list(SingleGenerationInStream_1.SingleGenerationInStream).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamEnd.js
var require_GenerateStreamEnd2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamEnd.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamEnd = void 0;
    var core = __importStar5(require_core());
    var FinishReason_1 = require_FinishReason2();
    var GenerateStreamEndResponse_1 = require_GenerateStreamEndResponse2();
    var GenerateStreamEvent_1 = require_GenerateStreamEvent2();
    exports.GenerateStreamEnd = core.serialization.object({
      isFinished: core.serialization.property("is_finished", core.serialization.boolean()),
      finishReason: core.serialization.property("finish_reason", FinishReason_1.FinishReason.optional()),
      response: GenerateStreamEndResponse_1.GenerateStreamEndResponse
    }).extend(GenerateStreamEvent_1.GenerateStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamError.js
var require_GenerateStreamError2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamError.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamError = void 0;
    var core = __importStar5(require_core());
    var FinishReason_1 = require_FinishReason2();
    var GenerateStreamEvent_1 = require_GenerateStreamEvent2();
    exports.GenerateStreamError = core.serialization.object({
      index: core.serialization.number().optional(),
      isFinished: core.serialization.property("is_finished", core.serialization.boolean()),
      finishReason: core.serialization.property("finish_reason", FinishReason_1.FinishReason),
      err: core.serialization.string()
    }).extend(GenerateStreamEvent_1.GenerateStreamEvent);
  }
});

// node_modules/cohere-ai/serialization/types/GenerateStreamedResponse.js
var require_GenerateStreamedResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GenerateStreamedResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamedResponse = void 0;
    var core = __importStar5(require_core());
    var GenerateStreamText_1 = require_GenerateStreamText2();
    var GenerateStreamEnd_1 = require_GenerateStreamEnd2();
    var GenerateStreamError_1 = require_GenerateStreamError2();
    exports.GenerateStreamedResponse = core.serialization.union(core.serialization.discriminant("eventType", "event_type"), {
      "text-generation": GenerateStreamText_1.GenerateStreamText,
      "stream-end": GenerateStreamEnd_1.GenerateStreamEnd,
      "stream-error": GenerateStreamError_1.GenerateStreamError
    }).transform({
      transform: (value) => value,
      untransform: (value) => value
    });
  }
});

// node_modules/cohere-ai/serialization/types/EmbedJobStatus.js
var require_EmbedJobStatus2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedJobStatus.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJobStatus = void 0;
    var core = __importStar5(require_core());
    exports.EmbedJobStatus = core.serialization.enum_(["processing", "complete", "cancelling", "cancelled", "failed"]);
  }
});

// node_modules/cohere-ai/serialization/types/EmbedJobTruncate.js
var require_EmbedJobTruncate2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedJobTruncate.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJobTruncate = void 0;
    var core = __importStar5(require_core());
    exports.EmbedJobTruncate = core.serialization.enum_(["START", "END"]);
  }
});

// node_modules/cohere-ai/serialization/types/EmbedJob.js
var require_EmbedJob2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/EmbedJob.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJob = void 0;
    var core = __importStar5(require_core());
    var EmbedJobStatus_1 = require_EmbedJobStatus2();
    var EmbedJobTruncate_1 = require_EmbedJobTruncate2();
    var ApiMeta_1 = require_ApiMeta2();
    exports.EmbedJob = core.serialization.object({
      jobId: core.serialization.property("job_id", core.serialization.string()),
      name: core.serialization.string().optional(),
      status: EmbedJobStatus_1.EmbedJobStatus,
      createdAt: core.serialization.property("created_at", core.serialization.date()),
      inputDatasetId: core.serialization.property("input_dataset_id", core.serialization.string()),
      outputDatasetId: core.serialization.property("output_dataset_id", core.serialization.string().optional()),
      model: core.serialization.string(),
      truncate: EmbedJobTruncate_1.EmbedJobTruncate,
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ListEmbedJobResponse.js
var require_ListEmbedJobResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ListEmbedJobResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListEmbedJobResponse = void 0;
    var core = __importStar5(require_core());
    var EmbedJob_1 = require_EmbedJob2();
    exports.ListEmbedJobResponse = core.serialization.object({
      embedJobs: core.serialization.property("embed_jobs", core.serialization.list(EmbedJob_1.EmbedJob).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/CreateEmbedJobResponse.js
var require_CreateEmbedJobResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CreateEmbedJobResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateEmbedJobResponse = void 0;
    var core = __importStar5(require_core());
    var ApiMeta_1 = require_ApiMeta2();
    exports.CreateEmbedJobResponse = core.serialization.object({
      jobId: core.serialization.property("job_id", core.serialization.string()),
      meta: ApiMeta_1.ApiMeta.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyExample.js
var require_ClassifyExample2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyExample.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyExample = void 0;
    var core = __importStar5(require_core());
    exports.ClassifyExample = core.serialization.object({
      text: core.serialization.string().optional(),
      label: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ParseInfo.js
var require_ParseInfo2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ParseInfo.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ParseInfo = void 0;
    var core = __importStar5(require_core());
    exports.ParseInfo = core.serialization.object({
      separator: core.serialization.string().optional(),
      delimiter: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/RerankerDataMetrics.js
var require_RerankerDataMetrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/RerankerDataMetrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankerDataMetrics = void 0;
    var core = __importStar5(require_core());
    exports.RerankerDataMetrics = core.serialization.object({
      numTrainQueries: core.serialization.property("num_train_queries", core.serialization.number().optional()),
      numTrainRelevantPassages: core.serialization.property("num_train_relevant_passages", core.serialization.number().optional()),
      numTrainHardNegatives: core.serialization.property("num_train_hard_negatives", core.serialization.number().optional()),
      numEvalQueries: core.serialization.property("num_eval_queries", core.serialization.number().optional()),
      numEvalRelevantPassages: core.serialization.property("num_eval_relevant_passages", core.serialization.number().optional()),
      numEvalHardNegatives: core.serialization.property("num_eval_hard_negatives", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ChatDataMetrics.js
var require_ChatDataMetrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ChatDataMetrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatDataMetrics = void 0;
    var core = __importStar5(require_core());
    exports.ChatDataMetrics = core.serialization.object({
      numTrainTurns: core.serialization.property("num_train_turns", core.serialization.number().optional()),
      numEvalTurns: core.serialization.property("num_eval_turns", core.serialization.number().optional()),
      preamble: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/LabelMetric.js
var require_LabelMetric2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/LabelMetric.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LabelMetric = void 0;
    var core = __importStar5(require_core());
    exports.LabelMetric = core.serialization.object({
      totalExamples: core.serialization.property("total_examples", core.serialization.number().optional()),
      label: core.serialization.string().optional(),
      samples: core.serialization.list(core.serialization.string()).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ClassifyDataMetrics.js
var require_ClassifyDataMetrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ClassifyDataMetrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyDataMetrics = void 0;
    var core = __importStar5(require_core());
    var LabelMetric_1 = require_LabelMetric2();
    exports.ClassifyDataMetrics = core.serialization.object({
      labelMetrics: core.serialization.property("label_metrics", core.serialization.list(LabelMetric_1.LabelMetric).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/FinetuneDatasetMetrics.js
var require_FinetuneDatasetMetrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/FinetuneDatasetMetrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.FinetuneDatasetMetrics = void 0;
    var core = __importStar5(require_core());
    exports.FinetuneDatasetMetrics = core.serialization.object({
      trainableTokenCount: core.serialization.property("trainable_token_count", core.serialization.number().optional()),
      totalExamples: core.serialization.property("total_examples", core.serialization.number().optional()),
      trainExamples: core.serialization.property("train_examples", core.serialization.number().optional()),
      trainSizeBytes: core.serialization.property("train_size_bytes", core.serialization.number().optional()),
      evalExamples: core.serialization.property("eval_examples", core.serialization.number().optional()),
      evalSizeBytes: core.serialization.property("eval_size_bytes", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/MetricsEmbedDataFieldsItem.js
var require_MetricsEmbedDataFieldsItem2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/MetricsEmbedDataFieldsItem.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricsEmbedDataFieldsItem = void 0;
    var core = __importStar5(require_core());
    exports.MetricsEmbedDataFieldsItem = core.serialization.object({
      name: core.serialization.string().optional(),
      count: core.serialization.number().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/MetricsEmbedData.js
var require_MetricsEmbedData2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/MetricsEmbedData.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MetricsEmbedData = void 0;
    var core = __importStar5(require_core());
    var MetricsEmbedDataFieldsItem_1 = require_MetricsEmbedDataFieldsItem2();
    exports.MetricsEmbedData = core.serialization.object({
      fields: core.serialization.list(MetricsEmbedDataFieldsItem_1.MetricsEmbedDataFieldsItem).optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/Metrics.js
var require_Metrics2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Metrics.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Metrics = void 0;
    var core = __importStar5(require_core());
    var FinetuneDatasetMetrics_1 = require_FinetuneDatasetMetrics2();
    var MetricsEmbedData_1 = require_MetricsEmbedData2();
    exports.Metrics = core.serialization.object({
      finetuneDatasetMetrics: core.serialization.property("finetune_dataset_metrics", FinetuneDatasetMetrics_1.FinetuneDatasetMetrics.optional()),
      embedData: core.serialization.property("embed_data", MetricsEmbedData_1.MetricsEmbedData.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ConnectorOAuth.js
var require_ConnectorOAuth2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ConnectorOAuth.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConnectorOAuth = void 0;
    var core = __importStar5(require_core());
    exports.ConnectorOAuth = core.serialization.object({
      clientId: core.serialization.property("client_id", core.serialization.string().optional()),
      clientSecret: core.serialization.property("client_secret", core.serialization.string().optional()),
      authorizeUrl: core.serialization.property("authorize_url", core.serialization.string()),
      tokenUrl: core.serialization.property("token_url", core.serialization.string()),
      scope: core.serialization.string().optional()
    });
  }
});

// node_modules/cohere-ai/serialization/types/ConnectorAuthStatus.js
var require_ConnectorAuthStatus2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ConnectorAuthStatus.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ConnectorAuthStatus = void 0;
    var core = __importStar5(require_core());
    exports.ConnectorAuthStatus = core.serialization.enum_(["valid", "expired"]);
  }
});

// node_modules/cohere-ai/serialization/types/Connector.js
var require_Connector2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/Connector.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Connector = void 0;
    var core = __importStar5(require_core());
    var ConnectorOAuth_1 = require_ConnectorOAuth2();
    var ConnectorAuthStatus_1 = require_ConnectorAuthStatus2();
    exports.Connector = core.serialization.object({
      id: core.serialization.string(),
      organizationId: core.serialization.property("organization_id", core.serialization.string().optional()),
      name: core.serialization.string(),
      description: core.serialization.string().optional(),
      url: core.serialization.string().optional(),
      createdAt: core.serialization.property("created_at", core.serialization.date()),
      updatedAt: core.serialization.property("updated_at", core.serialization.date()),
      excludes: core.serialization.list(core.serialization.string()).optional(),
      authType: core.serialization.property("auth_type", core.serialization.string().optional()),
      oauth: ConnectorOAuth_1.ConnectorOAuth.optional(),
      authStatus: core.serialization.property("auth_status", ConnectorAuthStatus_1.ConnectorAuthStatus.optional()),
      active: core.serialization.boolean().optional(),
      continueOnFailure: core.serialization.property("continue_on_failure", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ListConnectorsResponse.js
var require_ListConnectorsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ListConnectorsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListConnectorsResponse = void 0;
    var core = __importStar5(require_core());
    var Connector_1 = require_Connector2();
    exports.ListConnectorsResponse = core.serialization.object({
      connectors: core.serialization.list(Connector_1.Connector),
      totalCount: core.serialization.property("total_count", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/CreateConnectorResponse.js
var require_CreateConnectorResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CreateConnectorResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CreateConnectorResponse = void 0;
    var core = __importStar5(require_core());
    var Connector_1 = require_Connector2();
    exports.CreateConnectorResponse = core.serialization.object({
      connector: Connector_1.Connector
    });
  }
});

// node_modules/cohere-ai/serialization/types/GetConnectorResponse.js
var require_GetConnectorResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GetConnectorResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GetConnectorResponse = void 0;
    var core = __importStar5(require_core());
    var Connector_1 = require_Connector2();
    exports.GetConnectorResponse = core.serialization.object({
      connector: Connector_1.Connector
    });
  }
});

// node_modules/cohere-ai/serialization/types/DeleteConnectorResponse.js
var require_DeleteConnectorResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/DeleteConnectorResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeleteConnectorResponse = void 0;
    var core = __importStar5(require_core());
    exports.DeleteConnectorResponse = core.serialization.record(core.serialization.string(), core.serialization.unknown());
  }
});

// node_modules/cohere-ai/serialization/types/UpdateConnectorResponse.js
var require_UpdateConnectorResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/UpdateConnectorResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.UpdateConnectorResponse = void 0;
    var core = __importStar5(require_core());
    var Connector_1 = require_Connector2();
    exports.UpdateConnectorResponse = core.serialization.object({
      connector: Connector_1.Connector
    });
  }
});

// node_modules/cohere-ai/serialization/types/OAuthAuthorizeResponse.js
var require_OAuthAuthorizeResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/OAuthAuthorizeResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OAuthAuthorizeResponse = void 0;
    var core = __importStar5(require_core());
    exports.OAuthAuthorizeResponse = core.serialization.object({
      redirectUrl: core.serialization.property("redirect_url", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/CompatibleEndpoint.js
var require_CompatibleEndpoint2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/CompatibleEndpoint.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CompatibleEndpoint = void 0;
    var core = __importStar5(require_core());
    exports.CompatibleEndpoint = core.serialization.enum_(["chat", "embed", "classify", "summarize", "rerank", "rate", "generate"]);
  }
});

// node_modules/cohere-ai/serialization/types/GetModelResponse.js
var require_GetModelResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/GetModelResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GetModelResponse = void 0;
    var core = __importStar5(require_core());
    var CompatibleEndpoint_1 = require_CompatibleEndpoint2();
    exports.GetModelResponse = core.serialization.object({
      name: core.serialization.string().optional(),
      endpoints: core.serialization.list(CompatibleEndpoint_1.CompatibleEndpoint).optional(),
      finetuned: core.serialization.boolean().optional(),
      contextLength: core.serialization.property("context_length", core.serialization.number().optional()),
      tokenizerUrl: core.serialization.property("tokenizer_url", core.serialization.string().optional()),
      defaultEndpoints: core.serialization.property("default_endpoints", core.serialization.list(CompatibleEndpoint_1.CompatibleEndpoint).optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/ListModelsResponse.js
var require_ListModelsResponse2 = __commonJS({
  "node_modules/cohere-ai/serialization/types/ListModelsResponse.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ListModelsResponse = void 0;
    var core = __importStar5(require_core());
    var GetModelResponse_1 = require_GetModelResponse2();
    exports.ListModelsResponse = core.serialization.object({
      models: core.serialization.list(GetModelResponse_1.GetModelResponse),
      nextPageToken: core.serialization.property("next_page_token", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/types/index.js
var require_types11 = __commonJS({
  "node_modules/cohere-ai/serialization/types/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_ChatStreamRequestPromptTruncation2(), exports);
    __exportStar5(require_ChatStreamRequestCitationQuality2(), exports);
    __exportStar5(require_ChatStreamRequestConnectorsSearchOptions2(), exports);
    __exportStar5(require_ChatStreamRequestSafetyMode2(), exports);
    __exportStar5(require_UnprocessableEntityErrorBody2(), exports);
    __exportStar5(require_TooManyRequestsErrorBody2(), exports);
    __exportStar5(require_ClientClosedRequestErrorBody2(), exports);
    __exportStar5(require_NotImplementedErrorBody2(), exports);
    __exportStar5(require_GatewayTimeoutErrorBody2(), exports);
    __exportStar5(require_ChatRequestPromptTruncation2(), exports);
    __exportStar5(require_ChatRequestCitationQuality2(), exports);
    __exportStar5(require_ChatRequestConnectorsSearchOptions2(), exports);
    __exportStar5(require_ChatRequestSafetyMode2(), exports);
    __exportStar5(require_GenerateStreamRequestTruncate2(), exports);
    __exportStar5(require_GenerateStreamRequestReturnLikelihoods2(), exports);
    __exportStar5(require_GenerateRequestTruncate2(), exports);
    __exportStar5(require_GenerateRequestReturnLikelihoods2(), exports);
    __exportStar5(require_EmbedRequestTruncate2(), exports);
    __exportStar5(require_EmbedResponse2(), exports);
    __exportStar5(require_RerankRequestDocumentsItem2(), exports);
    __exportStar5(require_RerankResponseResultsItemDocument2(), exports);
    __exportStar5(require_RerankResponseResultsItem2(), exports);
    __exportStar5(require_RerankResponse2(), exports);
    __exportStar5(require_ClassifyRequestTruncate2(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItemLabelsValue2(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItemClassificationType2(), exports);
    __exportStar5(require_ClassifyResponseClassificationsItem2(), exports);
    __exportStar5(require_ClassifyResponse2(), exports);
    __exportStar5(require_SummarizeRequestLength2(), exports);
    __exportStar5(require_SummarizeRequestFormat2(), exports);
    __exportStar5(require_SummarizeRequestExtractiveness2(), exports);
    __exportStar5(require_SummarizeResponse2(), exports);
    __exportStar5(require_TokenizeResponse2(), exports);
    __exportStar5(require_DetokenizeResponse2(), exports);
    __exportStar5(require_CheckApiKeyResponse2(), exports);
    __exportStar5(require_ToolCall3(), exports);
    __exportStar5(require_ChatMessage3(), exports);
    __exportStar5(require_ToolResult2(), exports);
    __exportStar5(require_ToolMessage3(), exports);
    __exportStar5(require_Message3(), exports);
    __exportStar5(require_ChatConnector2(), exports);
    __exportStar5(require_ChatDocument2(), exports);
    __exportStar5(require_ToolParameterDefinitionsValue2(), exports);
    __exportStar5(require_Tool3(), exports);
    __exportStar5(require_TextResponseFormat2(), exports);
    __exportStar5(require_JsonResponseFormat3(), exports);
    __exportStar5(require_ResponseFormat3(), exports);
    __exportStar5(require_ChatCitation2(), exports);
    __exportStar5(require_ChatSearchQuery2(), exports);
    __exportStar5(require_ChatSearchResultConnector2(), exports);
    __exportStar5(require_ChatSearchResult2(), exports);
    __exportStar5(require_FinishReason2(), exports);
    __exportStar5(require_ApiMetaApiVersion2(), exports);
    __exportStar5(require_ApiMetaBilledUnits2(), exports);
    __exportStar5(require_ApiMetaTokens2(), exports);
    __exportStar5(require_ApiMeta2(), exports);
    __exportStar5(require_NonStreamedChatResponse3(), exports);
    __exportStar5(require_ChatStreamEvent2(), exports);
    __exportStar5(require_ChatStreamStartEvent2(), exports);
    __exportStar5(require_ChatSearchQueriesGenerationEvent2(), exports);
    __exportStar5(require_ChatSearchResultsEvent2(), exports);
    __exportStar5(require_ChatTextGenerationEvent2(), exports);
    __exportStar5(require_ChatCitationGenerationEvent2(), exports);
    __exportStar5(require_ChatToolCallsGenerationEvent2(), exports);
    __exportStar5(require_ChatStreamEndEventFinishReason2(), exports);
    __exportStar5(require_ChatStreamEndEvent2(), exports);
    __exportStar5(require_ToolCallDelta2(), exports);
    __exportStar5(require_ChatToolCallsChunkEvent2(), exports);
    __exportStar5(require_StreamedChatResponse3(), exports);
    __exportStar5(require_JsonResponseFormat22(), exports);
    __exportStar5(require_ResponseFormat22(), exports);
    __exportStar5(require_CitationStartEventDeltaMessage2(), exports);
    __exportStar5(require_CitationStartEventDelta2(), exports);
    __exportStar5(require_CitationStartEvent2(), exports);
    __exportStar5(require_CitationEndEvent2(), exports);
    __exportStar5(require_SingleGenerationTokenLikelihoodsItem2(), exports);
    __exportStar5(require_SingleGeneration2(), exports);
    __exportStar5(require_Generation2(), exports);
    __exportStar5(require_GenerateStreamEvent2(), exports);
    __exportStar5(require_GenerateStreamText2(), exports);
    __exportStar5(require_SingleGenerationInStream2(), exports);
    __exportStar5(require_GenerateStreamEndResponse2(), exports);
    __exportStar5(require_GenerateStreamEnd2(), exports);
    __exportStar5(require_GenerateStreamError2(), exports);
    __exportStar5(require_GenerateStreamedResponse2(), exports);
    __exportStar5(require_EmbedInputType2(), exports);
    __exportStar5(require_EmbeddingType2(), exports);
    __exportStar5(require_EmbedFloatsResponse2(), exports);
    __exportStar5(require_EmbedByTypeResponseEmbeddings2(), exports);
    __exportStar5(require_EmbedByTypeResponse2(), exports);
    __exportStar5(require_EmbedJobStatus2(), exports);
    __exportStar5(require_EmbedJobTruncate2(), exports);
    __exportStar5(require_EmbedJob2(), exports);
    __exportStar5(require_ListEmbedJobResponse2(), exports);
    __exportStar5(require_CreateEmbedJobResponse2(), exports);
    __exportStar5(require_RerankDocument2(), exports);
    __exportStar5(require_ClassifyExample2(), exports);
    __exportStar5(require_DatasetValidationStatus2(), exports);
    __exportStar5(require_DatasetType2(), exports);
    __exportStar5(require_DatasetPart2(), exports);
    __exportStar5(require_ParseInfo2(), exports);
    __exportStar5(require_RerankerDataMetrics2(), exports);
    __exportStar5(require_ChatDataMetrics2(), exports);
    __exportStar5(require_LabelMetric2(), exports);
    __exportStar5(require_ClassifyDataMetrics2(), exports);
    __exportStar5(require_FinetuneDatasetMetrics2(), exports);
    __exportStar5(require_MetricsEmbedDataFieldsItem2(), exports);
    __exportStar5(require_MetricsEmbedData2(), exports);
    __exportStar5(require_Metrics2(), exports);
    __exportStar5(require_Dataset2(), exports);
    __exportStar5(require_ConnectorOAuth2(), exports);
    __exportStar5(require_ConnectorAuthStatus2(), exports);
    __exportStar5(require_Connector2(), exports);
    __exportStar5(require_ListConnectorsResponse2(), exports);
    __exportStar5(require_CreateConnectorOAuth2(), exports);
    __exportStar5(require_AuthTokenType2(), exports);
    __exportStar5(require_CreateConnectorServiceAuth2(), exports);
    __exportStar5(require_CreateConnectorResponse2(), exports);
    __exportStar5(require_GetConnectorResponse2(), exports);
    __exportStar5(require_DeleteConnectorResponse2(), exports);
    __exportStar5(require_UpdateConnectorResponse2(), exports);
    __exportStar5(require_OAuthAuthorizeResponse2(), exports);
    __exportStar5(require_CompatibleEndpoint2(), exports);
    __exportStar5(require_GetModelResponse2(), exports);
    __exportStar5(require_ListModelsResponse2(), exports);
  }
});

// node_modules/cohere-ai/serialization/client/requests/ChatStreamRequest.js
var require_ChatStreamRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/ChatStreamRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatStreamRequest = void 0;
    var core = __importStar5(require_core());
    var Message_1 = require_Message3();
    var ChatStreamRequestPromptTruncation_1 = require_ChatStreamRequestPromptTruncation2();
    var ChatConnector_1 = require_ChatConnector2();
    var ChatDocument_1 = require_ChatDocument2();
    var ChatStreamRequestCitationQuality_1 = require_ChatStreamRequestCitationQuality2();
    var Tool_1 = require_Tool3();
    var ToolResult_1 = require_ToolResult2();
    var ResponseFormat_1 = require_ResponseFormat3();
    var ChatStreamRequestSafetyMode_1 = require_ChatStreamRequestSafetyMode2();
    exports.ChatStreamRequest = core.serialization.object({
      message: core.serialization.string(),
      model: core.serialization.string().optional(),
      preamble: core.serialization.string().optional(),
      chatHistory: core.serialization.property("chat_history", core.serialization.list(Message_1.Message).optional()),
      conversationId: core.serialization.property("conversation_id", core.serialization.string().optional()),
      promptTruncation: core.serialization.property("prompt_truncation", ChatStreamRequestPromptTruncation_1.ChatStreamRequestPromptTruncation.optional()),
      connectors: core.serialization.list(ChatConnector_1.ChatConnector).optional(),
      searchQueriesOnly: core.serialization.property("search_queries_only", core.serialization.boolean().optional()),
      documents: core.serialization.list(ChatDocument_1.ChatDocument).optional(),
      citationQuality: core.serialization.property("citation_quality", ChatStreamRequestCitationQuality_1.ChatStreamRequestCitationQuality.optional()),
      temperature: core.serialization.number().optional(),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      maxInputTokens: core.serialization.property("max_input_tokens", core.serialization.number().optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      rawPrompting: core.serialization.property("raw_prompting", core.serialization.boolean().optional()),
      returnPrompt: core.serialization.property("return_prompt", core.serialization.boolean().optional()),
      tools: core.serialization.list(Tool_1.Tool).optional(),
      toolResults: core.serialization.property("tool_results", core.serialization.list(ToolResult_1.ToolResult).optional()),
      forceSingleStep: core.serialization.property("force_single_step", core.serialization.boolean().optional()),
      responseFormat: core.serialization.property("response_format", ResponseFormat_1.ResponseFormat.optional()),
      safetyMode: core.serialization.property("safety_mode", ChatStreamRequestSafetyMode_1.ChatStreamRequestSafetyMode.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/ChatRequest.js
var require_ChatRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/ChatRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ChatRequest = void 0;
    var core = __importStar5(require_core());
    var Message_1 = require_Message3();
    var ChatRequestPromptTruncation_1 = require_ChatRequestPromptTruncation2();
    var ChatConnector_1 = require_ChatConnector2();
    var ChatDocument_1 = require_ChatDocument2();
    var ChatRequestCitationQuality_1 = require_ChatRequestCitationQuality2();
    var Tool_1 = require_Tool3();
    var ToolResult_1 = require_ToolResult2();
    var ResponseFormat_1 = require_ResponseFormat3();
    var ChatRequestSafetyMode_1 = require_ChatRequestSafetyMode2();
    exports.ChatRequest = core.serialization.object({
      message: core.serialization.string(),
      model: core.serialization.string().optional(),
      preamble: core.serialization.string().optional(),
      chatHistory: core.serialization.property("chat_history", core.serialization.list(Message_1.Message).optional()),
      conversationId: core.serialization.property("conversation_id", core.serialization.string().optional()),
      promptTruncation: core.serialization.property("prompt_truncation", ChatRequestPromptTruncation_1.ChatRequestPromptTruncation.optional()),
      connectors: core.serialization.list(ChatConnector_1.ChatConnector).optional(),
      searchQueriesOnly: core.serialization.property("search_queries_only", core.serialization.boolean().optional()),
      documents: core.serialization.list(ChatDocument_1.ChatDocument).optional(),
      citationQuality: core.serialization.property("citation_quality", ChatRequestCitationQuality_1.ChatRequestCitationQuality.optional()),
      temperature: core.serialization.number().optional(),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      maxInputTokens: core.serialization.property("max_input_tokens", core.serialization.number().optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      rawPrompting: core.serialization.property("raw_prompting", core.serialization.boolean().optional()),
      returnPrompt: core.serialization.property("return_prompt", core.serialization.boolean().optional()),
      tools: core.serialization.list(Tool_1.Tool).optional(),
      toolResults: core.serialization.property("tool_results", core.serialization.list(ToolResult_1.ToolResult).optional()),
      forceSingleStep: core.serialization.property("force_single_step", core.serialization.boolean().optional()),
      responseFormat: core.serialization.property("response_format", ResponseFormat_1.ResponseFormat.optional()),
      safetyMode: core.serialization.property("safety_mode", ChatRequestSafetyMode_1.ChatRequestSafetyMode.optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/GenerateStreamRequest.js
var require_GenerateStreamRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/GenerateStreamRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateStreamRequest = void 0;
    var core = __importStar5(require_core());
    var GenerateStreamRequestTruncate_1 = require_GenerateStreamRequestTruncate2();
    var GenerateStreamRequestReturnLikelihoods_1 = require_GenerateStreamRequestReturnLikelihoods2();
    exports.GenerateStreamRequest = core.serialization.object({
      prompt: core.serialization.string(),
      model: core.serialization.string().optional(),
      numGenerations: core.serialization.property("num_generations", core.serialization.number().optional()),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      truncate: GenerateStreamRequestTruncate_1.GenerateStreamRequestTruncate.optional(),
      temperature: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      preset: core.serialization.string().optional(),
      endSequences: core.serialization.property("end_sequences", core.serialization.list(core.serialization.string()).optional()),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      returnLikelihoods: core.serialization.property("return_likelihoods", GenerateStreamRequestReturnLikelihoods_1.GenerateStreamRequestReturnLikelihoods.optional()),
      rawPrompting: core.serialization.property("raw_prompting", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/GenerateRequest.js
var require_GenerateRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/GenerateRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.GenerateRequest = void 0;
    var core = __importStar5(require_core());
    var GenerateRequestTruncate_1 = require_GenerateRequestTruncate2();
    var GenerateRequestReturnLikelihoods_1 = require_GenerateRequestReturnLikelihoods2();
    exports.GenerateRequest = core.serialization.object({
      prompt: core.serialization.string(),
      model: core.serialization.string().optional(),
      numGenerations: core.serialization.property("num_generations", core.serialization.number().optional()),
      maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
      truncate: GenerateRequestTruncate_1.GenerateRequestTruncate.optional(),
      temperature: core.serialization.number().optional(),
      seed: core.serialization.number().optional(),
      preset: core.serialization.string().optional(),
      endSequences: core.serialization.property("end_sequences", core.serialization.list(core.serialization.string()).optional()),
      stopSequences: core.serialization.property("stop_sequences", core.serialization.list(core.serialization.string()).optional()),
      k: core.serialization.number().optional(),
      p: core.serialization.number().optional(),
      frequencyPenalty: core.serialization.property("frequency_penalty", core.serialization.number().optional()),
      presencePenalty: core.serialization.property("presence_penalty", core.serialization.number().optional()),
      returnLikelihoods: core.serialization.property("return_likelihoods", GenerateRequestReturnLikelihoods_1.GenerateRequestReturnLikelihoods.optional()),
      rawPrompting: core.serialization.property("raw_prompting", core.serialization.boolean().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/EmbedRequest.js
var require_EmbedRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/EmbedRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedRequest = void 0;
    var core = __importStar5(require_core());
    var EmbedInputType_1 = require_EmbedInputType2();
    var EmbeddingType_1 = require_EmbeddingType2();
    var EmbedRequestTruncate_1 = require_EmbedRequestTruncate2();
    exports.EmbedRequest = core.serialization.object({
      texts: core.serialization.list(core.serialization.string()),
      model: core.serialization.string().optional(),
      inputType: core.serialization.property("input_type", EmbedInputType_1.EmbedInputType.optional()),
      embeddingTypes: core.serialization.property("embedding_types", core.serialization.list(EmbeddingType_1.EmbeddingType).optional()),
      truncate: EmbedRequestTruncate_1.EmbedRequestTruncate.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/RerankRequest.js
var require_RerankRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/RerankRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RerankRequest = void 0;
    var core = __importStar5(require_core());
    var RerankRequestDocumentsItem_1 = require_RerankRequestDocumentsItem2();
    exports.RerankRequest = core.serialization.object({
      model: core.serialization.string().optional(),
      query: core.serialization.string(),
      documents: core.serialization.list(RerankRequestDocumentsItem_1.RerankRequestDocumentsItem),
      topN: core.serialization.property("top_n", core.serialization.number().optional()),
      rankFields: core.serialization.property("rank_fields", core.serialization.list(core.serialization.string()).optional()),
      returnDocuments: core.serialization.property("return_documents", core.serialization.boolean().optional()),
      maxChunksPerDoc: core.serialization.property("max_chunks_per_doc", core.serialization.number().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/ClassifyRequest.js
var require_ClassifyRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/ClassifyRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ClassifyRequest = void 0;
    var core = __importStar5(require_core());
    var ClassifyExample_1 = require_ClassifyExample2();
    var ClassifyRequestTruncate_1 = require_ClassifyRequestTruncate2();
    exports.ClassifyRequest = core.serialization.object({
      inputs: core.serialization.list(core.serialization.string()),
      examples: core.serialization.list(ClassifyExample_1.ClassifyExample).optional(),
      model: core.serialization.string().optional(),
      preset: core.serialization.string().optional(),
      truncate: ClassifyRequestTruncate_1.ClassifyRequestTruncate.optional()
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/SummarizeRequest.js
var require_SummarizeRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/SummarizeRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SummarizeRequest = void 0;
    var core = __importStar5(require_core());
    var SummarizeRequestLength_1 = require_SummarizeRequestLength2();
    var SummarizeRequestFormat_1 = require_SummarizeRequestFormat2();
    var SummarizeRequestExtractiveness_1 = require_SummarizeRequestExtractiveness2();
    exports.SummarizeRequest = core.serialization.object({
      text: core.serialization.string(),
      length: SummarizeRequestLength_1.SummarizeRequestLength.optional(),
      format: SummarizeRequestFormat_1.SummarizeRequestFormat.optional(),
      model: core.serialization.string().optional(),
      extractiveness: SummarizeRequestExtractiveness_1.SummarizeRequestExtractiveness.optional(),
      temperature: core.serialization.number().optional(),
      additionalCommand: core.serialization.property("additional_command", core.serialization.string().optional())
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/TokenizeRequest.js
var require_TokenizeRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/TokenizeRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TokenizeRequest = void 0;
    var core = __importStar5(require_core());
    exports.TokenizeRequest = core.serialization.object({
      text: core.serialization.string(),
      model: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/DetokenizeRequest.js
var require_DetokenizeRequest = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/DetokenizeRequest.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DetokenizeRequest = void 0;
    var core = __importStar5(require_core());
    exports.DetokenizeRequest = core.serialization.object({
      tokens: core.serialization.list(core.serialization.number()),
      model: core.serialization.string()
    });
  }
});

// node_modules/cohere-ai/serialization/client/requests/index.js
var require_requests12 = __commonJS({
  "node_modules/cohere-ai/serialization/client/requests/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DetokenizeRequest = exports.TokenizeRequest = exports.SummarizeRequest = exports.ClassifyRequest = exports.RerankRequest = exports.EmbedRequest = exports.GenerateRequest = exports.GenerateStreamRequest = exports.ChatRequest = exports.ChatStreamRequest = void 0;
    var ChatStreamRequest_1 = require_ChatStreamRequest();
    Object.defineProperty(exports, "ChatStreamRequest", { enumerable: true, get: function() {
      return ChatStreamRequest_1.ChatStreamRequest;
    } });
    var ChatRequest_1 = require_ChatRequest();
    Object.defineProperty(exports, "ChatRequest", { enumerable: true, get: function() {
      return ChatRequest_1.ChatRequest;
    } });
    var GenerateStreamRequest_1 = require_GenerateStreamRequest();
    Object.defineProperty(exports, "GenerateStreamRequest", { enumerable: true, get: function() {
      return GenerateStreamRequest_1.GenerateStreamRequest;
    } });
    var GenerateRequest_1 = require_GenerateRequest();
    Object.defineProperty(exports, "GenerateRequest", { enumerable: true, get: function() {
      return GenerateRequest_1.GenerateRequest;
    } });
    var EmbedRequest_1 = require_EmbedRequest();
    Object.defineProperty(exports, "EmbedRequest", { enumerable: true, get: function() {
      return EmbedRequest_1.EmbedRequest;
    } });
    var RerankRequest_1 = require_RerankRequest();
    Object.defineProperty(exports, "RerankRequest", { enumerable: true, get: function() {
      return RerankRequest_1.RerankRequest;
    } });
    var ClassifyRequest_1 = require_ClassifyRequest();
    Object.defineProperty(exports, "ClassifyRequest", { enumerable: true, get: function() {
      return ClassifyRequest_1.ClassifyRequest;
    } });
    var SummarizeRequest_1 = require_SummarizeRequest();
    Object.defineProperty(exports, "SummarizeRequest", { enumerable: true, get: function() {
      return SummarizeRequest_1.SummarizeRequest;
    } });
    var TokenizeRequest_1 = require_TokenizeRequest();
    Object.defineProperty(exports, "TokenizeRequest", { enumerable: true, get: function() {
      return TokenizeRequest_1.TokenizeRequest;
    } });
    var DetokenizeRequest_1 = require_DetokenizeRequest();
    Object.defineProperty(exports, "DetokenizeRequest", { enumerable: true, get: function() {
      return DetokenizeRequest_1.DetokenizeRequest;
    } });
  }
});

// node_modules/cohere-ai/serialization/client/index.js
var require_client15 = __commonJS({
  "node_modules/cohere-ai/serialization/client/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_requests12(), exports);
  }
});

// node_modules/cohere-ai/serialization/index.js
var require_serialization = __commonJS({
  "node_modules/cohere-ai/serialization/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
      for (var p3 in m3)
        if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p3))
          __createBinding5(exports2, m3, p3);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar5(require_resources4(), exports);
    __exportStar5(require_types11(), exports);
    __exportStar5(require_client15(), exports);
  }
});

// node_modules/cohere-ai/aws-utils.js
var require_aws_utils = __commonJS({
  "node_modules/cohere-ai/aws-utils.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __asyncValues5 = exports && exports.__asyncValues || function(o3) {
      if (!Symbol.asyncIterator)
        throw new TypeError("Symbol.asyncIterator is not defined.");
      var m3 = o3[Symbol.asyncIterator], i3;
      return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
        return this;
      }, i3);
      function verb(n4) {
        i3[n4] = o3[n4] && function(v5) {
          return new Promise(function(resolve, reject) {
            v5 = o3[n4](v5), settle(resolve, reject, v5.done, v5.value);
          });
        };
      }
      function settle(resolve, reject, d3, v5) {
        Promise.resolve(v5).then(function(v6) {
          resolve({ value: v6, done: d3 });
        }, reject);
      }
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.fetchOverride = exports.parseAWSEvent = exports.getEndpointFromUrl = exports.getAuthHeaders = exports.getUrl = exports.mapResponseFromBedrock = void 0;
    var sha256_js_1 = require_main2();
    var credential_providers_1 = (init_index_browser2(), __toCommonJS(index_browser_exports));
    var protocol_http_1 = require_dist_cjs6();
    var signature_v4_1 = require_dist_cjs16();
    var readable_stream_1 = require_browser3();
    var core_1 = require_core();
    var Stream_1 = require_Stream();
    var streaming_utils_1 = require_streaming_utils();
    var serializers = __importStar5(require_serialization());
    var withTempEnv = (updateEnv, fn) => __awaiter6(void 0, void 0, void 0, function* () {
      const previousEnv = Object.assign({}, process.env);
      try {
        updateEnv();
        return yield fn();
      } finally {
        process.env = previousEnv;
      }
    });
    var streamingResponseParser = {
      "chat": serializers.StreamedChatResponse,
      "generate": serializers.GenerateStreamedResponse
    };
    var nonStreamedResponseParser = {
      "chat": serializers.NonStreamedChatResponse,
      "embed": serializers.EmbedResponse,
      "generate": serializers.Generation
    };
    var mapResponseFromBedrock = (streaming, endpoint, obj) => __awaiter6(void 0, void 0, void 0, function* () {
      const parser = streaming ? streamingResponseParser[endpoint] : nonStreamedResponseParser[endpoint];
      const config = {
        unrecognizedObjectKeys: "passthrough",
        allowUnrecognizedUnionMembers: true,
        allowUnrecognizedEnumValues: true,
        skipValidation: true,
        breadcrumbsPrefix: ["response"]
      };
      const parsed = yield parser.parseOrThrow(obj, config);
      return parser.jsonOrThrow(parsed, config);
    });
    exports.mapResponseFromBedrock = mapResponseFromBedrock;
    var getUrl = (platform2, awsRegion, model, stream) => {
      const endpoint = {
        "bedrock": stream ? "invoke-with-response-stream" : "invoke",
        "sagemaker": stream ? "invocations-response-stream" : "invocations"
      }[platform2];
      return {
        "bedrock": `https://${platform2}-runtime.${awsRegion}.amazonaws.com/model/${model}/${endpoint}`,
        "sagemaker": `https://runtime.sagemaker.${awsRegion}.amazonaws.com/endpoints/${model}/${endpoint}`
      }[platform2];
    };
    exports.getUrl = getUrl;
    var getAuthHeaders = (url, method, headers, body, service, props) => __awaiter6(void 0, void 0, void 0, function* () {
      const providerChain = (0, credential_providers_1.fromNodeProviderChain)();
      const credentials = yield withTempEnv(() => {
        if (props.awsAccessKey) {
          process.env["AWS_ACCESS_KEY_ID"] = props.awsAccessKey;
        }
        if (props.awsSecretKey) {
          process.env["AWS_SECRET_ACCESS_KEY"] = props.awsSecretKey;
        }
        if (props.awsSessionToken) {
          process.env["AWS_SESSION_TOKEN"] = props.awsSessionToken;
        }
      }, () => providerChain());
      const signer = new signature_v4_1.SignatureV4({
        service,
        region: props.awsRegion,
        credentials,
        sha256: sha256_js_1.Sha256
      });
      delete headers["connection"];
      headers["host"] = url.hostname;
      const request = new protocol_http_1.HttpRequest({
        method: method.toUpperCase(),
        protocol: url.protocol,
        path: url.pathname,
        headers,
        body
      });
      const signed = yield signer.sign(request);
      return signed.headers;
    });
    exports.getAuthHeaders = getAuthHeaders;
    var getEndpointFromUrl = (url, chatModel, embedModel, generateModel) => {
      if (chatModel && url.includes(chatModel)) {
        return "chat";
      }
      if (embedModel && url.includes(embedModel)) {
        return "embed";
      }
      if (generateModel && url.includes(generateModel)) {
        return "generate";
      }
      throw new Error(`Unknown endpoint in url: ${url}`);
    };
    exports.getEndpointFromUrl = getEndpointFromUrl;
    var parseAWSEvent = (line) => {
      const regex2 = /{[^\}]*}/;
      const match2 = line.match(regex2);
      if (match2 === null || match2 === void 0 ? void 0 : match2[0]) {
        const obj = JSON.parse(match2[0]);
        if (obj.bytes) {
          const base64Payload = Buffer.from(obj.bytes, "base64").toString("utf-8");
          const streamedObj = JSON.parse(base64Payload);
          if (streamedObj.event_type) {
            return streamedObj;
          }
        }
      }
    };
    exports.parseAWSEvent = parseAWSEvent;
    var fetchOverride = (platform2, { awsRegion, awsAccessKey, awsSecretKey, awsSessionToken }) => (fetcherArgs) => __awaiter6(void 0, void 0, void 0, function* () {
      var e_1, _a5;
      const endpoint = fetcherArgs.url.split("/").pop();
      const bodyJson = fetcherArgs.body;
      console.assert(bodyJson.model, "model is required");
      const isStreaming = Boolean(bodyJson.stream);
      const url = (0, exports.getUrl)(platform2, awsRegion, bodyJson.model, isStreaming);
      delete bodyJson["stream"];
      delete bodyJson["model"];
      delete fetcherArgs.headers["Authorization"];
      fetcherArgs.headers["Host"] = new URL(url).hostname;
      const authHeaders = yield (0, exports.getAuthHeaders)(new URL(url), fetcherArgs.method, fetcherArgs.headers, JSON.stringify(bodyJson), platform2, {
        awsRegion,
        awsAccessKey,
        awsSecretKey,
        awsSessionToken
      });
      fetcherArgs.url = url;
      fetcherArgs.headers = authHeaders;
      const response = yield (0, core_1.fetcher)(fetcherArgs);
      if (!response.ok) {
        return response;
      }
      try {
        if (isStreaming) {
          const responseStream = (0, Stream_1.readableStreamAsyncIterable)(response.body);
          const lineDecoder = new streaming_utils_1.LineDecoder();
          const newBody = new readable_stream_1.PassThrough();
          try {
            for (var responseStream_1 = __asyncValues5(responseStream), responseStream_1_1; responseStream_1_1 = yield responseStream_1.next(), !responseStream_1_1.done; ) {
              const chunk = responseStream_1_1.value;
              for (const line of lineDecoder.decode(chunk)) {
                const event = (0, exports.parseAWSEvent)(line);
                if (event) {
                  const obj = yield (0, exports.mapResponseFromBedrock)(isStreaming, endpoint, event);
                  newBody.push(JSON.stringify(obj) + "\n");
                }
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (responseStream_1_1 && !responseStream_1_1.done && (_a5 = responseStream_1.return))
                yield _a5.call(responseStream_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
          for (const line of lineDecoder.flush()) {
            const event = (0, exports.parseAWSEvent)(line);
            if (event) {
              const obj = yield (0, exports.mapResponseFromBedrock)(isStreaming, endpoint, event);
              newBody.push(JSON.stringify(obj) + "\n");
            }
          }
          newBody.end();
          return {
            ok: true,
            body: newBody
          };
        } else {
          const oldBody = yield response.body;
          const mappedResponse = yield (0, exports.mapResponseFromBedrock)(isStreaming, endpoint, oldBody);
          return {
            ok: true,
            body: mappedResponse
          };
        }
      } catch (e3) {
        throw e3;
      }
    });
    exports.fetchOverride = fetchOverride;
  }
});

// node_modules/cohere-ai/environments.js
var require_environments = __commonJS({
  "node_modules/cohere-ai/environments.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereEnvironment = void 0;
    exports.CohereEnvironment = {
      Production: "https://api.cohere.com"
    };
  }
});

// node_modules/url-join/lib/url-join.js
var require_url_join = __commonJS({
  "node_modules/url-join/lib/url-join.js"(exports, module2) {
    (function(name, context, definition) {
      if (typeof module2 !== "undefined" && module2.exports)
        module2.exports = definition();
      else if (typeof define === "function" && define.amd)
        define(definition);
      else
        context[name] = definition();
    })("urljoin", exports, function() {
      function normalize(strArray) {
        var resultArray = [];
        if (strArray.length === 0) {
          return "";
        }
        if (typeof strArray[0] !== "string") {
          throw new TypeError("Url must be a string. Received " + strArray[0]);
        }
        if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
          var first = strArray.shift();
          strArray[0] = first + strArray[0];
        }
        if (strArray[0].match(/^file:\/\/\//)) {
          strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1:///");
        } else {
          strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1://");
        }
        for (var i3 = 0; i3 < strArray.length; i3++) {
          var component = strArray[i3];
          if (typeof component !== "string") {
            throw new TypeError("Url must be a string. Received " + component);
          }
          if (component === "") {
            continue;
          }
          if (i3 > 0) {
            component = component.replace(/^[\/]+/, "");
          }
          if (i3 < strArray.length - 1) {
            component = component.replace(/[\/]+$/, "");
          } else {
            component = component.replace(/[\/]+$/, "/");
          }
          resultArray.push(component);
        }
        var str2 = resultArray.join("/");
        str2 = str2.replace(/\/(\?|&|#[^!])/g, "$1");
        var parts = str2.split("?");
        str2 = parts.shift() + (parts.length > 0 ? "?" : "") + parts.join("&");
        return str2;
      }
      return function() {
        var input;
        if (typeof arguments[0] === "object") {
          input = arguments[0];
        } else {
          input = [].slice.call(arguments);
        }
        return normalize(input);
      };
    });
  }
});

// node_modules/cohere-ai/api/resources/v2/client/Client.js
var require_Client = __commonJS({
  "node_modules/cohere-ai/api/resources/v2/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.V2 = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var serializers = __importStar5(require_serialization());
    var url_join_1 = __importDefault5(require_url_join());
    var errors2 = __importStar5(require_errors());
    var V2 = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * Generates a message from the model in response to a provided conversation. To learn how to use the Chat API with Streaming and RAG follow our Text Generation guides.
       */
      chatStream(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v2/chat"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.V2ChatStreamRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: true }),
            responseType: "sse",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return new core.Stream({
              stream: _response.body,
              parse: (data) => __awaiter6(this, void 0, void 0, function* () {
                return serializers.StreamedChatResponse2.parseOrThrow(data, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                });
              }),
              signal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
              eventShape: {
                type: "sse",
                streamTerminator: "[DONE]"
              }
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Generates a message from the model in response to a provided conversation. To learn how to use the Chat API with Streaming and RAG follow our Text Generation guides.
       *
       * @param {Cohere.V2ChatRequest} request
       * @param {V2.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.v2.chat({
       *         model: "model",
       *         messages: []
       *     })
       */
      chat(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v2/chat"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.V2ChatRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: false }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.NonStreamedChatResponse2.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.V2 = V2;
  }
});

// node_modules/cohere-ai/api/resources/embedJobs/client/Client.js
var require_Client2 = __commonJS({
  "node_modules/cohere-ai/api/resources/embedJobs/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EmbedJobs = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var url_join_1 = __importDefault5(require_url_join());
    var serializers = __importStar5(require_serialization());
    var errors2 = __importStar5(require_errors());
    var EmbedJobs = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * The list embed job endpoint allows users to view all embed jobs history for that specific user.
       *
       * @param {EmbedJobs.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.embedJobs.list()
       */
      list(requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/embed-jobs"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.ListEmbedJobResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This API launches an async Embed job for a [Dataset](https://docs.cohere.com/docs/datasets) of type `embed-input`. The result of a completed embed job is new Dataset of type `embed-output`, which contains the original text entries and the corresponding embeddings.
       *
       * @param {Cohere.CreateEmbedJobRequest} request
       * @param {EmbedJobs.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.embedJobs.create({
       *         model: "model",
       *         datasetId: "dataset_id",
       *         inputType: Cohere.EmbedInputType.SearchDocument
       *     })
       */
      create(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/embed-jobs"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.CreateEmbedJobRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.CreateEmbedJobResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This API retrieves the details about an embed job started by the same user.
       *
       * @param {string} id - The ID of the embed job to retrieve.
       * @param {EmbedJobs.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.embedJobs.get("id")
       */
      get(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/embed-jobs/${encodeURIComponent(id)}`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.EmbedJob.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This API allows users to cancel an active embed job. Once invoked, the embedding process will be terminated, and users will be charged for the embeddings processed up to the cancellation point. It's important to note that partial results will not be available to users after cancellation.
       *
       * @param {string} id - The ID of the embed job to cancel.
       * @param {EmbedJobs.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.embedJobs.cancel("id")
       */
      cancel(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/embed-jobs/${encodeURIComponent(id)}/cancel`),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return;
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.EmbedJobs = EmbedJobs;
  }
});

// node_modules/cohere-ai/api/resources/datasets/client/Client.js
var require_Client3 = __commonJS({
  "node_modules/cohere-ai/api/resources/datasets/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Datasets = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var url_join_1 = __importDefault5(require_url_join());
    var serializers = __importStar5(require_serialization());
    var errors2 = __importStar5(require_errors());
    var Datasets = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * List datasets that have been created.
       *
       * @param {Cohere.DatasetsListRequest} request
       * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.datasets.list()
       */
      list(request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { datasetType, before, after, limit: limit2, offset: offset5, validationStatus } = request;
          const _queryParams = {};
          if (datasetType != null) {
            _queryParams["datasetType"] = datasetType;
          }
          if (before != null) {
            _queryParams["before"] = before.toISOString();
          }
          if (after != null) {
            _queryParams["after"] = after.toISOString();
          }
          if (limit2 != null) {
            _queryParams["limit"] = limit2.toString();
          }
          if (offset5 != null) {
            _queryParams["offset"] = offset5.toString();
          }
          if (validationStatus != null) {
            _queryParams["validationStatus"] = validationStatus;
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/datasets"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.12.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DatasetsListResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Create a dataset by uploading a file. See ['Dataset Creation'](https://docs.cohere.com/docs/datasets#dataset-creation) for more information.
       *
       * @param {File | fs.ReadStream | Blob} data
       * @param {File | fs.ReadStream | Blob | undefined} evalData
       * @param {Cohere.DatasetsCreateRequest} request
       * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.datasets.create(fs.createReadStream("/path/to/your/file"), fs.createReadStream("/path/to/your/file"), {
       *         name: "name",
       *         type: Cohere.DatasetType.EmbedInput
       *     })
       */
      create(data, evalData, request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _queryParams = {};
          _queryParams["name"] = request.name;
          _queryParams["type"] = request.type;
          if (request.keepOriginalFile != null) {
            _queryParams["keep_original_file"] = request.keepOriginalFile.toString();
          }
          if (request.skipMalformedInput != null) {
            _queryParams["skip_malformed_input"] = request.skipMalformedInput.toString();
          }
          if (request.keepFields != null) {
            if (Array.isArray(request.keepFields)) {
              _queryParams["keep_fields"] = request.keepFields.map((item) => item);
            } else {
              _queryParams["keep_fields"] = request.keepFields;
            }
          }
          if (request.optionalFields != null) {
            if (Array.isArray(request.optionalFields)) {
              _queryParams["optional_fields"] = request.optionalFields.map((item) => item);
            } else {
              _queryParams["optional_fields"] = request.optionalFields;
            }
          }
          if (request.textSeparator != null) {
            _queryParams["text_separator"] = request.textSeparator;
          }
          if (request.csvDelimiter != null) {
            _queryParams["csv_delimiter"] = request.csvDelimiter;
          }
          if (request.dryRun != null) {
            _queryParams["dry_run"] = request.dryRun.toString();
          }
          const _request = yield core.newFormData();
          yield _request.appendFile("data", data, data === null || data === void 0 ? void 0 : data.name);
          if (evalData != null) {
            yield _request.appendFile("eval_data", evalData, evalData === null || evalData === void 0 ? void 0 : evalData.name);
          }
          const _maybeEncodedRequest = yield _request.getRequest();
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/datasets"),
            method: "POST",
            headers: Object.assign({ Authorization: yield this._getAuthorizationHeader(), "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0, "X-Fern-Language": "JavaScript", "X-Fern-SDK-Name": "cohere-ai", "X-Fern-SDK-Version": "7.12.0", "X-Fern-Runtime": core.RUNTIME.type, "X-Fern-Runtime-Version": core.RUNTIME.version }, _maybeEncodedRequest.headers),
            queryParameters: _queryParams,
            requestType: "file",
            duplex: _maybeEncodedRequest.duplex,
            body: _maybeEncodedRequest.body,
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DatasetsCreateResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * View the dataset storage usage for your Organization. Each Organization can have up to 10GB of storage across all their users.
       *
       * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.datasets.getUsage()
       */
      getUsage(requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/datasets/usage"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.12.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DatasetsGetUsageResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Retrieve a dataset by ID. See ['Datasets'](https://docs.cohere.com/docs/datasets) for more information.
       *
       * @param {string} id
       * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.datasets.get("id")
       */
      get(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/datasets/${encodeURIComponent(id)}`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.12.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DatasetsGetResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Delete a dataset by ID. Datasets are automatically deleted after 30 days, but they can also be deleted manually.
       *
       * @param {string} id
       * @param {Datasets.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.datasets.delete("id")
       */
      delete(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/datasets/${encodeURIComponent(id)}`),
            method: "DELETE",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.12.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.datasets.delete.Response.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.Datasets = Datasets;
  }
});

// node_modules/cohere-ai/api/resources/connectors/client/Client.js
var require_Client4 = __commonJS({
  "node_modules/cohere-ai/api/resources/connectors/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Connectors = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var url_join_1 = __importDefault5(require_url_join());
    var serializers = __importStar5(require_serialization());
    var errors2 = __importStar5(require_errors());
    var Connectors = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * Returns a list of connectors ordered by descending creation date (newer first). See ['Managing your Connector'](https://docs.cohere.com/docs/managing-your-connector) for more information.
       *
       * @param {Cohere.ConnectorsListRequest} request
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.list()
       */
      list(request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { limit: limit2, offset: offset5 } = request;
          const _queryParams = {};
          if (limit2 != null) {
            _queryParams["limit"] = limit2.toString();
          }
          if (offset5 != null) {
            _queryParams["offset"] = offset5.toString();
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/connectors"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.ListConnectorsResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Creates a new connector. The connector is tested during registration and will cancel registration when the test is unsuccessful. See ['Creating and Deploying a Connector'](https://docs.cohere.com/docs/creating-and-deploying-a-connector) for more information.
       *
       * @param {Cohere.CreateConnectorRequest} request
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.create({
       *         name: "name",
       *         url: "url"
       *     })
       */
      create(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/connectors"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.CreateConnectorRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.CreateConnectorResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Retrieve a connector by ID. See ['Connectors'](https://docs.cohere.com/docs/connectors) for more information.
       *
       * @param {string} id - The ID of the connector to retrieve.
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.get("id")
       */
      get(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/connectors/${encodeURIComponent(id)}`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.GetConnectorResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Delete a connector by ID. See ['Connectors'](https://docs.cohere.com/docs/connectors) for more information.
       *
       * @param {string} id - The ID of the connector to delete.
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.delete("id")
       */
      delete(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/connectors/${encodeURIComponent(id)}`),
            method: "DELETE",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DeleteConnectorResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Update a connector by ID. Omitted fields will not be updated. See ['Managing your Connector'](https://docs.cohere.com/docs/managing-your-connector) for more information.
       *
       * @param {string} id - The ID of the connector to update.
       * @param {Cohere.UpdateConnectorRequest} request
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.update("id")
       */
      update(id, request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/connectors/${encodeURIComponent(id)}`),
            method: "PATCH",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.UpdateConnectorRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.UpdateConnectorResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Authorize the connector with the given ID for the connector oauth app. See ['Connector Authentication'](https://docs.cohere.com/docs/connector-authentication) for more information.
       *
       * @param {string} id - The ID of the connector to authorize.
       * @param {Cohere.ConnectorsOAuthAuthorizeRequest} request
       * @param {Connectors.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.connectors.oAuthAuthorize("id")
       */
      oAuthAuthorize(id, request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { afterTokenRedirect } = request;
          const _queryParams = {};
          if (afterTokenRedirect != null) {
            _queryParams["after_token_redirect"] = afterTokenRedirect;
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/connectors/${encodeURIComponent(id)}/oauth/authorize`),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.OAuthAuthorizeResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.Connectors = Connectors;
  }
});

// node_modules/cohere-ai/api/resources/models/client/Client.js
var require_Client5 = __commonJS({
  "node_modules/cohere-ai/api/resources/models/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Models = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var url_join_1 = __importDefault5(require_url_join());
    var serializers = __importStar5(require_serialization());
    var errors2 = __importStar5(require_errors());
    var Models3 = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * Returns the details of a model, provided its name.
       *
       * @param {string} model
       * @param {Models.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.models.get("command-r")
       */
      get(model, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/models/${encodeURIComponent(model)}`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.GetModelResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models.
       *
       * @param {Cohere.ModelsListRequest} request
       * @param {Models.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.models.list()
       */
      list(request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { pageSize, pageToken, endpoint, defaultOnly } = request;
          const _queryParams = {};
          if (pageSize != null) {
            _queryParams["page_size"] = pageSize.toString();
          }
          if (pageToken != null) {
            _queryParams["page_token"] = pageToken;
          }
          if (endpoint != null) {
            _queryParams["endpoint"] = endpoint;
          }
          if (defaultOnly != null) {
            _queryParams["default_only"] = defaultOnly.toString();
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/models"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.ListModelsResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.Models = Models3;
  }
});

// node_modules/cohere-ai/api/resources/finetuning/client/Client.js
var require_Client6 = __commonJS({
  "node_modules/cohere-ai/api/resources/finetuning/client/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Finetuning = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var url_join_1 = __importDefault5(require_url_join());
    var serializers = __importStar5(require_serialization());
    var errors2 = __importStar5(require_errors());
    var Finetuning = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * @param {Cohere.FinetuningListFinetunedModelsRequest} request
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.listFinetunedModels()
       */
      listFinetunedModels(request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { pageSize, pageToken, orderBy } = request;
          const _queryParams = {};
          if (pageSize != null) {
            _queryParams["page_size"] = pageSize.toString();
          }
          if (pageToken != null) {
            _queryParams["page_token"] = pageToken;
          }
          if (orderBy != null) {
            _queryParams["order_by"] = orderBy;
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/finetuning/finetuned-models"),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.ListFinetunedModelsResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {Cohere.finetuning.FinetunedModel} request
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.createFinetunedModel({
       *         name: "api-test",
       *         settings: {
       *             baseModel: {
       *                 baseType: Cohere.finetuning.BaseType.BaseTypeGenerative
       *             },
       *             datasetId: "my-dataset-id"
       *         }
       *     })
       */
      createFinetunedModel(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/finetuning/finetuned-models"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.finetuning.FinetunedModel.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.CreateFinetunedModelResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {string} id - The fine-tuned model ID.
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.getFinetunedModel("id")
       */
      getFinetunedModel(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/finetuning/finetuned-models/${encodeURIComponent(id)}`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.GetFinetunedModelResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {string} id - The fine-tuned model ID.
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.deleteFinetunedModel("id")
       */
      deleteFinetunedModel(id, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/finetuning/finetuned-models/${encodeURIComponent(id)}`),
            method: "DELETE",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.DeleteFinetunedModelResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {string} id - FinetunedModel ID.
       * @param {Cohere.FinetuningUpdateFinetunedModelRequest} request
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.updateFinetunedModel("id", {
       *         name: "name",
       *         settings: {
       *             baseModel: {
       *                 baseType: Cohere.finetuning.BaseType.BaseTypeUnspecified
       *             },
       *             datasetId: "dataset_id"
       *         }
       *     })
       */
      updateFinetunedModel(id, request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/finetuning/finetuned-models/${encodeURIComponent(id)}`),
            method: "PATCH",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.FinetuningUpdateFinetunedModelRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.UpdateFinetunedModelResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {string} finetunedModelId - The parent fine-tuned model ID.
       * @param {Cohere.FinetuningListEventsRequest} request
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.listEvents("finetuned_model_id")
       */
      listEvents(finetunedModelId, request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { pageSize, pageToken, orderBy } = request;
          const _queryParams = {};
          if (pageSize != null) {
            _queryParams["page_size"] = pageSize.toString();
          }
          if (pageToken != null) {
            _queryParams["page_token"] = pageToken;
          }
          if (orderBy != null) {
            _queryParams["order_by"] = orderBy;
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/finetuning/finetuned-models/${encodeURIComponent(finetunedModelId)}/events`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.ListEventsResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * @param {string} finetunedModelId - The parent fine-tuned model ID.
       * @param {Cohere.FinetuningListTrainingStepMetricsRequest} request
       * @param {Finetuning.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.ServiceUnavailableError}
       *
       * @example
       *     await client.finetuning.listTrainingStepMetrics("finetuned_model_id")
       */
      listTrainingStepMetrics(finetunedModelId, request = {}, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const { pageSize, pageToken } = request;
          const _queryParams = {};
          if (pageSize != null) {
            _queryParams["page_size"] = pageSize.toString();
          }
          if (pageToken != null) {
            _queryParams["page_token"] = pageToken;
          }
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, `v1/finetuning/finetuned-models/${encodeURIComponent(finetunedModelId)}/training-step-metrics`),
            method: "GET",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            queryParameters: _queryParams,
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.finetuning.ListTrainingStepMetricsResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.Finetuning = Finetuning;
  }
});

// node_modules/cohere-ai/Client.js
var require_Client7 = __commonJS({
  "node_modules/cohere-ai/Client.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    var __awaiter6 = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e3) {
            reject(e3);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e3) {
            reject(e3);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault5 = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereClient = void 0;
    var environments = __importStar5(require_environments());
    var core = __importStar5(require_core());
    var Cohere = __importStar5(require_api());
    var serializers = __importStar5(require_serialization());
    var url_join_1 = __importDefault5(require_url_join());
    var errors2 = __importStar5(require_errors());
    var Client_1 = require_Client();
    var Client_2 = require_Client2();
    var Client_3 = require_Client3();
    var Client_4 = require_Client4();
    var Client_5 = require_Client5();
    var Client_6 = require_Client6();
    var CohereClient5 = class {
      constructor(_options = {}) {
        this._options = _options;
      }
      /**
       * Generates a text response to a user message.
       * To learn how to use the Chat API with Streaming and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api).
       */
      chatStream(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/chat"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.ChatStreamRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: true }),
            responseType: "sse",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return new core.Stream({
              stream: _response.body,
              parse: (data) => __awaiter6(this, void 0, void 0, function* () {
                return serializers.StreamedChatResponse.parseOrThrow(data, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                });
              }),
              signal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
              eventShape: {
                type: "json",
                messageTerminator: "\n"
              }
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Generates a text response to a user message.
       * To learn how to use the Chat API with Streaming and RAG follow our [Text Generation guides](https://docs.cohere.com/docs/chat-api).
       *
       * @param {Cohere.ChatRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.chat({
       *         message: "Can you give me a global market overview of solar panels?",
       *         promptTruncation: Cohere.ChatRequestPromptTruncation.Off,
       *         temperature: 0.3
       *     })
       */
      chat(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/chat"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.ChatRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: false }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.NonStreamedChatResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * <Warning>
       * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
       * </Warning>
       * Generates realistic text conditioned on a given input.
       */
      generateStream(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/generate"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.GenerateStreamRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: true }),
            responseType: "sse",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return new core.Stream({
              stream: _response.body,
              parse: (data) => __awaiter6(this, void 0, void 0, function* () {
                return serializers.GenerateStreamedResponse.parseOrThrow(data, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                });
              }),
              signal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal,
              eventShape: {
                type: "json",
                messageTerminator: "\n"
              }
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * <Warning>
       * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
       * </Warning>
       * Generates realistic text conditioned on a given input.
       *
       * @param {Cohere.GenerateRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.generate({
       *         prompt: "Please explain to me how LLMs work"
       *     })
       */
      generate(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/generate"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: Object.assign(Object.assign({}, serializers.GenerateRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            })), { stream: false }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.Generation.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This endpoint returns text embeddings. An embedding is a list of floating point numbers that captures semantic information about the text that it represents.
       *
       * Embeddings can be used to create text classifiers as well as empower semantic search. To learn more about embeddings, see the embedding page.
       *
       * If you want to learn more how to use the embedding model, have a look at the [Semantic Search Guide](/docs/semantic-search).
       *
       * @param {Cohere.EmbedRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.embed({
       *         texts: ["string"],
       *         images: ["string"],
       *         model: "string",
       *         inputType: Cohere.EmbedInputType.SearchDocument,
       *         embeddingTypes: [Cohere.EmbeddingType.Float],
       *         truncate: Cohere.EmbedRequestTruncate.None
       *     })
       */
      embed(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/embed"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.EmbedRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.EmbedResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This endpoint takes in a query and a list of texts and produces an ordered array with each text assigned a relevance score.
       *
       * @param {Cohere.RerankRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.rerank({
       *         query: "query",
       *         documents: ["documents"]
       *     })
       */
      rerank(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/rerank"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.RerankRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.RerankResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This endpoint makes a prediction about which label fits the specified text inputs best. To make a prediction, Classify uses the provided `examples` of text + label pairs as a reference.
       * Note: [Fine-tuned models](https://docs.cohere.com/docs/classify-fine-tuning) trained on classification examples don't require the `examples` parameter to be passed in explicitly.
       *
       * @param {Cohere.ClassifyRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.classify({
       *         inputs: ["inputs"]
       *     })
       */
      classify(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/classify"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.ClassifyRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.ClassifyResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * <Warning>
       * This API is marked as "Legacy" and is no longer maintained. Follow the [migration guide](/docs/migrating-from-cogenerate-to-cochat) to start using the Chat API.
       * </Warning>
       * Generates a summary in English for a given text.
       *
       * @param {Cohere.SummarizeRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.summarize({
       *         text: "text"
       *     })
       */
      summarize(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/summarize"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.SummarizeRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.SummarizeResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This endpoint splits input text into smaller units called tokens using byte-pair encoding (BPE). To learn more about tokenization and byte pair encoding, see the tokens page.
       *
       * @param {Cohere.TokenizeRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.tokenize({
       *         text: "tokenize me! :D",
       *         model: "command"
       *     })
       */
      tokenize(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/tokenize"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.TokenizeRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.TokenizeResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * This endpoint takes tokens using byte-pair encoding and returns their text representation. To learn more about tokenization and byte pair encoding, see the tokens page.
       *
       * @param {Cohere.DetokenizeRequest} request
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.detokenize({
       *         tokens: [1],
       *         model: "model"
       *     })
       */
      detokenize(request, requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/detokenize"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            body: serializers.DetokenizeRequest.jsonOrThrow(request, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true
            }),
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.DetokenizeResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      /**
       * Checks that the api key in the Authorization header is valid and active
       *
       * @param {CohereClient.RequestOptions} requestOptions - Request-specific configuration.
       *
       * @throws {@link Cohere.BadRequestError}
       * @throws {@link Cohere.UnauthorizedError}
       * @throws {@link Cohere.ForbiddenError}
       * @throws {@link Cohere.NotFoundError}
       * @throws {@link Cohere.UnprocessableEntityError}
       * @throws {@link Cohere.TooManyRequestsError}
       * @throws {@link Cohere.ClientClosedRequestError}
       * @throws {@link Cohere.InternalServerError}
       * @throws {@link Cohere.NotImplementedError}
       * @throws {@link Cohere.ServiceUnavailableError}
       * @throws {@link Cohere.GatewayTimeoutError}
       *
       * @example
       *     await client.checkApiKey()
       */
      checkApiKey(requestOptions) {
        var _a5, _b;
        return __awaiter6(this, void 0, void 0, function* () {
          const _response = yield ((_a5 = this._options.fetcher) !== null && _a5 !== void 0 ? _a5 : core.fetcher)({
            url: (0, url_join_1.default)((_b = yield core.Supplier.get(this._options.environment)) !== null && _b !== void 0 ? _b : environments.CohereEnvironment.Production, "v1/check-api-key"),
            method: "POST",
            headers: {
              Authorization: yield this._getAuthorizationHeader(),
              "X-Client-Name": (yield core.Supplier.get(this._options.clientName)) != null ? yield core.Supplier.get(this._options.clientName) : void 0,
              "X-Fern-Language": "JavaScript",
              "X-Fern-SDK-Name": "cohere-ai",
              "X-Fern-SDK-Version": "7.13.0",
              "User-Agent": "cohere-ai/7.13.0",
              "X-Fern-Runtime": core.RUNTIME.type,
              "X-Fern-Runtime-Version": core.RUNTIME.version
            },
            contentType: "application/json",
            requestType: "json",
            timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 3e5,
            maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
            abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
          });
          if (_response.ok) {
            return serializers.CheckApiKeyResponse.parseOrThrow(_response.body, {
              unrecognizedObjectKeys: "passthrough",
              allowUnrecognizedUnionMembers: true,
              allowUnrecognizedEnumValues: true,
              skipValidation: true,
              breadcrumbsPrefix: ["response"]
            });
          }
          if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
              case 400:
                throw new Cohere.BadRequestError(_response.error.body);
              case 401:
                throw new Cohere.UnauthorizedError(_response.error.body);
              case 403:
                throw new Cohere.ForbiddenError(_response.error.body);
              case 404:
                throw new Cohere.NotFoundError(_response.error.body);
              case 422:
                throw new Cohere.UnprocessableEntityError(serializers.UnprocessableEntityErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 429:
                throw new Cohere.TooManyRequestsError(serializers.TooManyRequestsErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 499:
                throw new Cohere.ClientClosedRequestError(serializers.ClientClosedRequestErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 500:
                throw new Cohere.InternalServerError(_response.error.body);
              case 501:
                throw new Cohere.NotImplementedError(serializers.NotImplementedErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              case 503:
                throw new Cohere.ServiceUnavailableError(_response.error.body);
              case 504:
                throw new Cohere.GatewayTimeoutError(serializers.GatewayTimeoutErrorBody.parseOrThrow(_response.error.body, {
                  unrecognizedObjectKeys: "passthrough",
                  allowUnrecognizedUnionMembers: true,
                  allowUnrecognizedEnumValues: true,
                  skipValidation: true,
                  breadcrumbsPrefix: ["response"]
                }));
              default:
                throw new errors2.CohereError({
                  statusCode: _response.error.statusCode,
                  body: _response.error.body
                });
            }
          }
          switch (_response.error.reason) {
            case "non-json":
              throw new errors2.CohereError({
                statusCode: _response.error.statusCode,
                body: _response.error.rawBody
              });
            case "timeout":
              throw new errors2.CohereTimeoutError();
            case "unknown":
              throw new errors2.CohereError({
                message: _response.error.errorMessage
              });
          }
        });
      }
      get v2() {
        var _a5;
        return (_a5 = this._v2) !== null && _a5 !== void 0 ? _a5 : this._v2 = new Client_1.V2(this._options);
      }
      get embedJobs() {
        var _a5;
        return (_a5 = this._embedJobs) !== null && _a5 !== void 0 ? _a5 : this._embedJobs = new Client_2.EmbedJobs(this._options);
      }
      get datasets() {
        var _a5;
        return (_a5 = this._datasets) !== null && _a5 !== void 0 ? _a5 : this._datasets = new Client_3.Datasets(this._options);
      }
      get connectors() {
        var _a5;
        return (_a5 = this._connectors) !== null && _a5 !== void 0 ? _a5 : this._connectors = new Client_4.Connectors(this._options);
      }
      get models() {
        var _a5;
        return (_a5 = this._models) !== null && _a5 !== void 0 ? _a5 : this._models = new Client_5.Models(this._options);
      }
      get finetuning() {
        var _a5;
        return (_a5 = this._finetuning) !== null && _a5 !== void 0 ? _a5 : this._finetuning = new Client_6.Finetuning(this._options);
      }
      _getAuthorizationHeader() {
        var _a5;
        return __awaiter6(this, void 0, void 0, function* () {
          const bearer = (_a5 = yield core.Supplier.get(this._options.token)) !== null && _a5 !== void 0 ? _a5 : process === null || process === void 0 ? void 0 : process.env["CO_API_KEY"];
          if (bearer == null) {
            throw new errors2.CohereError({
              message: "Please specify CO_API_KEY when instantiating the client."
            });
          }
          return `Bearer ${bearer}`;
        });
      }
    };
    exports.CohereClient = CohereClient5;
  }
});

// node_modules/cohere-ai/AwsClient.js
var require_AwsClient = __commonJS({
  "node_modules/cohere-ai/AwsClient.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AwsClient = void 0;
    var Client_1 = require_Client7();
    var AwsClient = class extends Client_1.CohereClient {
      constructor(_options) {
        _options.token = "n/a";
        super(_options);
      }
    };
    exports.AwsClient = AwsClient;
  }
});

// node_modules/cohere-ai/BedrockClient.js
var require_BedrockClient = __commonJS({
  "node_modules/cohere-ai/BedrockClient.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.BedrockClient = void 0;
    var aws_utils_1 = require_aws_utils();
    var AwsClient_1 = require_AwsClient();
    var BedrockClient = class extends AwsClient_1.AwsClient {
      constructor(_options) {
        super(Object.assign(Object.assign({}, _options), { fetcher: (0, aws_utils_1.fetchOverride)("bedrock", _options) }));
      }
    };
    exports.BedrockClient = BedrockClient;
  }
});

// node_modules/cohere-ai/ClientV2.js
var require_ClientV2 = __commonJS({
  "node_modules/cohere-ai/ClientV2.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CohereClientV2 = void 0;
    var Client_1 = require_Client();
    var Client_2 = require_Client7();
    var CohereClientV2 = class {
      constructor(_options) {
        this._options = _options;
        this.client = new Client_2.CohereClient(this._options);
        this.clientV2 = new Client_1.V2(this._options);
        this.chat = this.clientV2.chat.bind(this.clientV2);
        this.chatStream = this.clientV2.chatStream.bind(this.clientV2);
        this.generateStream = this.client.generateStream.bind(this.clientV2);
        this.generate = this.client.generate.bind(this.clientV2);
        this.embed = this.client.embed.bind(this.clientV2);
        this.rerank = this.client.rerank.bind(this.clientV2);
        this.classify = this.client.classify.bind(this.clientV2);
        this.summarize = this.client.summarize.bind(this.clientV2);
        this.tokenize = this.client.tokenize.bind(this.clientV2);
        this.detokenize = this.client.detokenize.bind(this.clientV2);
        this.checkApiKey = this.client.checkApiKey.bind(this.clientV2);
        this.embedJobs = this.client.embedJobs;
        this.datasets = this.client.datasets;
        this.connectors = this.client.connectors;
        this.models = this.client.models;
        this.finetuning = this.client.finetuning;
      }
    };
    exports.CohereClientV2 = CohereClientV2;
  }
});

// node_modules/cohere-ai/CustomClient.js
var require_CustomClient = __commonJS({
  "node_modules/cohere-ai/CustomClient.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CustomClient = void 0;
    var Client_1 = require_Client7();
    var CustomClient = class extends Client_1.CohereClient {
      constructor(_options = {}) {
        var _a5, _b;
        try {
          const match2 = /\/v1\/?$/;
          const fixed = (_a5 = _options.environment) === null || _a5 === void 0 ? void 0 : _a5.toString().replace(match2, "");
          if (fixed !== ((_b = _options.environment) === null || _b === void 0 ? void 0 : _b.toString())) {
            _options.environment = fixed;
          }
        } catch (_c) {
        }
        super(_options);
        this._options = _options;
      }
    };
    exports.CustomClient = CustomClient;
  }
});

// node_modules/cohere-ai/SagemakerClient.js
var require_SagemakerClient = __commonJS({
  "node_modules/cohere-ai/SagemakerClient.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SagemakerClient = void 0;
    var AwsClient_1 = require_AwsClient();
    var aws_utils_1 = require_aws_utils();
    var SagemakerClient = class extends AwsClient_1.AwsClient {
      constructor(_options) {
        super(Object.assign(Object.assign({}, _options), { fetcher: (0, aws_utils_1.fetchOverride)("sagemaker", _options) }));
      }
    };
    exports.SagemakerClient = SagemakerClient;
  }
});

// node_modules/cohere-ai/index.js
var require_cohere_ai = __commonJS({
  "node_modules/cohere-ai/index.js"(exports) {
    "use strict";
    var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      var desc = Object.getOwnPropertyDescriptor(m3, k3);
      if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m3[k3];
        } };
      }
      Object.defineProperty(o3, k22, desc);
    } : function(o3, m3, k3, k22) {
      if (k22 === void 0)
        k22 = k3;
      o3[k22] = m3[k3];
    });
    var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o3, v5) {
      Object.defineProperty(o3, "default", { enumerable: true, value: v5 });
    } : function(o3, v5) {
      o3["default"] = v5;
    });
    var __importStar5 = exports && exports.__importStar || function(mod) {
      if (mod && mod.__esModule)
        return mod;
      var result = {};
      if (mod != null) {
        for (var k3 in mod)
          if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3))
            __createBinding5(result, mod, k3);
      }
      __setModuleDefault4(result, mod);
      return result;
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SagemakerClient = exports.CohereTimeoutError = exports.CohereError = exports.CohereEnvironment = exports.CohereClient = exports.CohereClientV2 = exports.BedrockClient = exports.Cohere = void 0;
    exports.Cohere = __importStar5(require_api());
    var BedrockClient_1 = require_BedrockClient();
    Object.defineProperty(exports, "BedrockClient", { enumerable: true, get: function() {
      return BedrockClient_1.BedrockClient;
    } });
    var ClientV2_1 = require_ClientV2();
    Object.defineProperty(exports, "CohereClientV2", { enumerable: true, get: function() {
      return ClientV2_1.CohereClientV2;
    } });
    var CustomClient_1 = require_CustomClient();
    Object.defineProperty(exports, "CohereClient", { enumerable: true, get: function() {
      return CustomClient_1.CustomClient;
    } });
    var environments_1 = require_environments();
    Object.defineProperty(exports, "CohereEnvironment", { enumerable: true, get: function() {
      return environments_1.CohereEnvironment;
    } });
    var errors_1 = require_errors();
    Object.defineProperty(exports, "CohereError", { enumerable: true, get: function() {
      return errors_1.CohereError;
    } });
    Object.defineProperty(exports, "CohereTimeoutError", { enumerable: true, get: function() {
      return errors_1.CohereTimeoutError;
    } });
    var SagemakerClient_1 = require_SagemakerClient();
    Object.defineProperty(exports, "SagemakerClient", { enumerable: true, get: function() {
      return SagemakerClient_1.SagemakerClient;
    } });
  }
});

// node_modules/@langchain/core/dist/utils/js-sha1/hash.js
function Sha1(sharedMemory) {
  if (sharedMemory) {
    blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
    this.blocks = blocks;
  } else {
    this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  }
  this.h0 = 1732584193;
  this.h1 = 4023233417;
  this.h2 = 2562383102;
  this.h3 = 271733878;
  this.h4 = 3285377520;
  this.block = this.start = this.bytes = this.hBytes = 0;
  this.finalized = this.hashed = false;
  this.first = true;
}
var root, HEX_CHARS, EXTRA, SHIFT, blocks, insecureHash;
var init_hash = __esm({
  "node_modules/@langchain/core/dist/utils/js-sha1/hash.js"() {
    "use strict";
    root = typeof window === "object" ? window : {};
    HEX_CHARS = "0123456789abcdef".split("");
    EXTRA = [-2147483648, 8388608, 32768, 128];
    SHIFT = [24, 16, 8, 0];
    blocks = [];
    Sha1.prototype.update = function(message) {
      if (this.finalized) {
        return;
      }
      var notString = typeof message !== "string";
      if (notString && message.constructor === root.ArrayBuffer) {
        message = new Uint8Array(message);
      }
      var code, index2 = 0, i3, length = message.length || 0, blocks2 = this.blocks;
      while (index2 < length) {
        if (this.hashed) {
          this.hashed = false;
          blocks2[0] = this.block;
          blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0;
        }
        if (notString) {
          for (i3 = this.start; index2 < length && i3 < 64; ++index2) {
            blocks2[i3 >> 2] |= message[index2] << SHIFT[i3++ & 3];
          }
        } else {
          for (i3 = this.start; index2 < length && i3 < 64; ++index2) {
            code = message.charCodeAt(index2);
            if (code < 128) {
              blocks2[i3 >> 2] |= code << SHIFT[i3++ & 3];
            } else if (code < 2048) {
              blocks2[i3 >> 2] |= (192 | code >> 6) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code & 63) << SHIFT[i3++ & 3];
            } else if (code < 55296 || code >= 57344) {
              blocks2[i3 >> 2] |= (224 | code >> 12) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code & 63) << SHIFT[i3++ & 3];
            } else {
              code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index2) & 1023);
              blocks2[i3 >> 2] |= (240 | code >> 18) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i3++ & 3];
              blocks2[i3 >> 2] |= (128 | code & 63) << SHIFT[i3++ & 3];
            }
          }
        }
        this.lastByteIndex = i3;
        this.bytes += i3 - this.start;
        if (i3 >= 64) {
          this.block = blocks2[16];
          this.start = i3 - 64;
          this.hash();
          this.hashed = true;
        } else {
          this.start = i3;
        }
      }
      if (this.bytes > 4294967295) {
        this.hBytes += this.bytes / 4294967296 << 0;
        this.bytes = this.bytes % 4294967296;
      }
      return this;
    };
    Sha1.prototype.finalize = function() {
      if (this.finalized) {
        return;
      }
      this.finalized = true;
      var blocks2 = this.blocks, i3 = this.lastByteIndex;
      blocks2[16] = this.block;
      blocks2[i3 >> 2] |= EXTRA[i3 & 3];
      this.block = blocks2[16];
      if (i3 >= 56) {
        if (!this.hashed) {
          this.hash();
        }
        blocks2[0] = this.block;
        blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0;
      }
      blocks2[14] = this.hBytes << 3 | this.bytes >>> 29;
      blocks2[15] = this.bytes << 3;
      this.hash();
    };
    Sha1.prototype.hash = function() {
      var a3 = this.h0, b3 = this.h1, c4 = this.h2, d3 = this.h3, e3 = this.h4;
      var f3, j3, t3, blocks2 = this.blocks;
      for (j3 = 16; j3 < 80; ++j3) {
        t3 = blocks2[j3 - 3] ^ blocks2[j3 - 8] ^ blocks2[j3 - 14] ^ blocks2[j3 - 16];
        blocks2[j3] = t3 << 1 | t3 >>> 31;
      }
      for (j3 = 0; j3 < 20; j3 += 5) {
        f3 = b3 & c4 | ~b3 & d3;
        t3 = a3 << 5 | a3 >>> 27;
        e3 = t3 + f3 + e3 + 1518500249 + blocks2[j3] << 0;
        b3 = b3 << 30 | b3 >>> 2;
        f3 = a3 & b3 | ~a3 & c4;
        t3 = e3 << 5 | e3 >>> 27;
        d3 = t3 + f3 + d3 + 1518500249 + blocks2[j3 + 1] << 0;
        a3 = a3 << 30 | a3 >>> 2;
        f3 = e3 & a3 | ~e3 & b3;
        t3 = d3 << 5 | d3 >>> 27;
        c4 = t3 + f3 + c4 + 1518500249 + blocks2[j3 + 2] << 0;
        e3 = e3 << 30 | e3 >>> 2;
        f3 = d3 & e3 | ~d3 & a3;
        t3 = c4 << 5 | c4 >>> 27;
        b3 = t3 + f3 + b3 + 1518500249 + blocks2[j3 + 3] << 0;
        d3 = d3 << 30 | d3 >>> 2;
        f3 = c4 & d3 | ~c4 & e3;
        t3 = b3 << 5 | b3 >>> 27;
        a3 = t3 + f3 + a3 + 1518500249 + blocks2[j3 + 4] << 0;
        c4 = c4 << 30 | c4 >>> 2;
      }
      for (; j3 < 40; j3 += 5) {
        f3 = b3 ^ c4 ^ d3;
        t3 = a3 << 5 | a3 >>> 27;
        e3 = t3 + f3 + e3 + 1859775393 + blocks2[j3] << 0;
        b3 = b3 << 30 | b3 >>> 2;
        f3 = a3 ^ b3 ^ c4;
        t3 = e3 << 5 | e3 >>> 27;
        d3 = t3 + f3 + d3 + 1859775393 + blocks2[j3 + 1] << 0;
        a3 = a3 << 30 | a3 >>> 2;
        f3 = e3 ^ a3 ^ b3;
        t3 = d3 << 5 | d3 >>> 27;
        c4 = t3 + f3 + c4 + 1859775393 + blocks2[j3 + 2] << 0;
        e3 = e3 << 30 | e3 >>> 2;
        f3 = d3 ^ e3 ^ a3;
        t3 = c4 << 5 | c4 >>> 27;
        b3 = t3 + f3 + b3 + 1859775393 + blocks2[j3 + 3] << 0;
        d3 = d3 << 30 | d3 >>> 2;
        f3 = c4 ^ d3 ^ e3;
        t3 = b3 << 5 | b3 >>> 27;
        a3 = t3 + f3 + a3 + 1859775393 + blocks2[j3 + 4] << 0;
        c4 = c4 << 30 | c4 >>> 2;
      }
      for (; j3 < 60; j3 += 5) {
        f3 = b3 & c4 | b3 & d3 | c4 & d3;
        t3 = a3 << 5 | a3 >>> 27;
        e3 = t3 + f3 + e3 - 1894007588 + blocks2[j3] << 0;
        b3 = b3 << 30 | b3 >>> 2;
        f3 = a3 & b3 | a3 & c4 | b3 & c4;
        t3 = e3 << 5 | e3 >>> 27;
        d3 = t3 + f3 + d3 - 1894007588 + blocks2[j3 + 1] << 0;
        a3 = a3 << 30 | a3 >>> 2;
        f3 = e3 & a3 | e3 & b3 | a3 & b3;
        t3 = d3 << 5 | d3 >>> 27;
        c4 = t3 + f3 + c4 - 1894007588 + blocks2[j3 + 2] << 0;
        e3 = e3 << 30 | e3 >>> 2;
        f3 = d3 & e3 | d3 & a3 | e3 & a3;
        t3 = c4 << 5 | c4 >>> 27;
        b3 = t3 + f3 + b3 - 1894007588 + blocks2[j3 + 3] << 0;
        d3 = d3 << 30 | d3 >>> 2;
        f3 = c4 & d3 | c4 & e3 | d3 & e3;
        t3 = b3 << 5 | b3 >>> 27;
        a3 = t3 + f3 + a3 - 1894007588 + blocks2[j3 + 4] << 0;
        c4 = c4 << 30 | c4 >>> 2;
      }
      for (; j3 < 80; j3 += 5) {
        f3 = b3 ^ c4 ^ d3;
        t3 = a3 << 5 | a3 >>> 27;
        e3 = t3 + f3 + e3 - 899497514 + blocks2[j3] << 0;
        b3 = b3 << 30 | b3 >>> 2;
        f3 = a3 ^ b3 ^ c4;
        t3 = e3 << 5 | e3 >>> 27;
        d3 = t3 + f3 + d3 - 899497514 + blocks2[j3 + 1] << 0;
        a3 = a3 << 30 | a3 >>> 2;
        f3 = e3 ^ a3 ^ b3;
        t3 = d3 << 5 | d3 >>> 27;
        c4 = t3 + f3 + c4 - 899497514 + blocks2[j3 + 2] << 0;
        e3 = e3 << 30 | e3 >>> 2;
        f3 = d3 ^ e3 ^ a3;
        t3 = c4 << 5 | c4 >>> 27;
        b3 = t3 + f3 + b3 - 899497514 + blocks2[j3 + 3] << 0;
        d3 = d3 << 30 | d3 >>> 2;
        f3 = c4 ^ d3 ^ e3;
        t3 = b3 << 5 | b3 >>> 27;
        a3 = t3 + f3 + a3 - 899497514 + blocks2[j3 + 4] << 0;
        c4 = c4 << 30 | c4 >>> 2;
      }
      this.h0 = this.h0 + a3 << 0;
      this.h1 = this.h1 + b3 << 0;
      this.h2 = this.h2 + c4 << 0;
      this.h3 = this.h3 + d3 << 0;
      this.h4 = this.h4 + e3 << 0;
    };
    Sha1.prototype.hex = function() {
      this.finalize();
      var h0 = this.h0, h1 = this.h1, h22 = this.h2, h3 = this.h3, h4 = this.h4;
      return HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h22 >> 28 & 15] + HEX_CHARS[h22 >> 24 & 15] + HEX_CHARS[h22 >> 20 & 15] + HEX_CHARS[h22 >> 16 & 15] + HEX_CHARS[h22 >> 12 & 15] + HEX_CHARS[h22 >> 8 & 15] + HEX_CHARS[h22 >> 4 & 15] + HEX_CHARS[h22 & 15] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[h4 & 15];
    };
    Sha1.prototype.toString = Sha1.prototype.hex;
    Sha1.prototype.digest = function() {
      this.finalize();
      var h0 = this.h0, h1 = this.h1, h22 = this.h2, h3 = this.h3, h4 = this.h4;
      return [
        h0 >> 24 & 255,
        h0 >> 16 & 255,
        h0 >> 8 & 255,
        h0 & 255,
        h1 >> 24 & 255,
        h1 >> 16 & 255,
        h1 >> 8 & 255,
        h1 & 255,
        h22 >> 24 & 255,
        h22 >> 16 & 255,
        h22 >> 8 & 255,
        h22 & 255,
        h3 >> 24 & 255,
        h3 >> 16 & 255,
        h3 >> 8 & 255,
        h3 & 255,
        h4 >> 24 & 255,
        h4 >> 16 & 255,
        h4 >> 8 & 255,
        h4 & 255
      ];
    };
    Sha1.prototype.array = Sha1.prototype.digest;
    Sha1.prototype.arrayBuffer = function() {
      this.finalize();
      var buffer = new ArrayBuffer(20);
      var dataView = new DataView(buffer);
      dataView.setUint32(0, this.h0);
      dataView.setUint32(4, this.h1);
      dataView.setUint32(8, this.h2);
      dataView.setUint32(12, this.h3);
      dataView.setUint32(16, this.h4);
      return buffer;
    };
    insecureHash = (message) => {
      return new Sha1(true).update(message)["hex"]();
    };
  }
});

// node_modules/@langchain/core/dist/utils/hash.js
var init_hash2 = __esm({
  "node_modules/@langchain/core/dist/utils/hash.js"() {
    init_hash();
  }
});

// node_modules/@langchain/core/dist/caches/base.js
var getCacheKey, BaseCache, GLOBAL_MAP, InMemoryCache;
var init_base7 = __esm({
  "node_modules/@langchain/core/dist/caches/base.js"() {
    init_hash2();
    init_utils2();
    getCacheKey = (...strings) => insecureHash(strings.join("_"));
    BaseCache = class {
    };
    GLOBAL_MAP = /* @__PURE__ */ new Map();
    InMemoryCache = class extends BaseCache {
      constructor(map) {
        super();
        Object.defineProperty(this, "cache", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.cache = map ?? /* @__PURE__ */ new Map();
      }
      /**
       * Retrieves data from the cache using a prompt and an LLM key. If the
       * data is not found, it returns null.
       * @param prompt The prompt used to find the data.
       * @param llmKey The LLM key used to find the data.
       * @returns The data corresponding to the prompt and LLM key, or null if not found.
       */
      lookup(prompt, llmKey) {
        return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null);
      }
      /**
       * Updates the cache with new data using a prompt and an LLM key.
       * @param prompt The prompt used to store the data.
       * @param llmKey The LLM key used to store the data.
       * @param value The data to be stored.
       */
      async update(prompt, llmKey, value) {
        this.cache.set(getCacheKey(prompt, llmKey), value);
      }
      /**
       * Returns a global instance of InMemoryCache using a predefined global
       * map as the initial cache.
       * @returns A global instance of InMemoryCache.
       */
      static global() {
        return new InMemoryCache(GLOBAL_MAP);
      }
    };
  }
});

// node_modules/js-tiktoken/dist/chunk-XX6PTLQF.js
function bytePairMerge(piece, ranks) {
  let parts = Array.from(
    { length: piece.length },
    (_2, i3) => ({ start: i3, end: i3 + 1 })
  );
  while (parts.length > 1) {
    let minRank = null;
    for (let i3 = 0; i3 < parts.length - 1; i3++) {
      const slice = piece.slice(parts[i3].start, parts[i3 + 1].end);
      const rank = ranks.get(slice.join(","));
      if (rank == null)
        continue;
      if (minRank == null || rank < minRank[0]) {
        minRank = [rank, i3];
      }
    }
    if (minRank != null) {
      const i3 = minRank[1];
      parts[i3] = { start: parts[i3].start, end: parts[i3 + 1].end };
      parts.splice(i3 + 1, 1);
    } else {
      break;
    }
  }
  return parts;
}
function bytePairEncode(piece, ranks) {
  if (piece.length === 1)
    return [ranks.get(piece.join(","))];
  return bytePairMerge(piece, ranks).map((p3) => ranks.get(piece.slice(p3.start, p3.end).join(","))).filter((x2) => x2 != null);
}
function escapeRegex(str2) {
  return str2.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&");
}
function getEncodingNameForModel(model) {
  switch (model) {
    case "gpt2": {
      return "gpt2";
    }
    case "code-cushman-001":
    case "code-cushman-002":
    case "code-davinci-001":
    case "code-davinci-002":
    case "cushman-codex":
    case "davinci-codex":
    case "davinci-002":
    case "text-davinci-002":
    case "text-davinci-003": {
      return "p50k_base";
    }
    case "code-davinci-edit-001":
    case "text-davinci-edit-001": {
      return "p50k_edit";
    }
    case "ada":
    case "babbage":
    case "babbage-002":
    case "code-search-ada-code-001":
    case "code-search-babbage-code-001":
    case "curie":
    case "davinci":
    case "text-ada-001":
    case "text-babbage-001":
    case "text-curie-001":
    case "text-davinci-001":
    case "text-search-ada-doc-001":
    case "text-search-babbage-doc-001":
    case "text-search-curie-doc-001":
    case "text-search-davinci-doc-001":
    case "text-similarity-ada-001":
    case "text-similarity-babbage-001":
    case "text-similarity-curie-001":
    case "text-similarity-davinci-001": {
      return "r50k_base";
    }
    case "gpt-3.5-turbo-instruct-0914":
    case "gpt-3.5-turbo-instruct":
    case "gpt-3.5-turbo-16k-0613":
    case "gpt-3.5-turbo-16k":
    case "gpt-3.5-turbo-0613":
    case "gpt-3.5-turbo-0301":
    case "gpt-3.5-turbo":
    case "gpt-4-32k-0613":
    case "gpt-4-32k-0314":
    case "gpt-4-32k":
    case "gpt-4-0613":
    case "gpt-4-0314":
    case "gpt-4":
    case "gpt-3.5-turbo-1106":
    case "gpt-35-turbo":
    case "gpt-4-1106-preview":
    case "gpt-4-vision-preview":
    case "gpt-3.5-turbo-0125":
    case "gpt-4-turbo":
    case "gpt-4-turbo-2024-04-09":
    case "gpt-4-turbo-preview":
    case "gpt-4-0125-preview":
    case "text-embedding-ada-002":
    case "text-embedding-3-small":
    case "text-embedding-3-large": {
      return "cl100k_base";
    }
    case "gpt-4o":
    case "gpt-4o-2024-05-13":
    case "gpt-4o-2024-08-06":
    case "gpt-4o-mini-2024-07-18":
    case "gpt-4o-mini": {
      return "o200k_base";
    }
    default:
      throw new Error("Unknown model");
  }
}
var import_base64_js, __defProp2, __defNormalProp2, __publicField2, _Tiktoken, Tiktoken;
var init_chunk_XX6PTLQF = __esm({
  "node_modules/js-tiktoken/dist/chunk-XX6PTLQF.js"() {
    import_base64_js = __toESM(require_base64_js(), 1);
    __defProp2 = Object.defineProperty;
    __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
    __publicField2 = (obj, key, value) => {
      __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
      return value;
    };
    _Tiktoken = class {
      constructor(ranks, extendedSpecialTokens) {
        /** @internal */
        __publicField(this, "specialTokens");
        /** @internal */
        __publicField(this, "inverseSpecialTokens");
        /** @internal */
        __publicField(this, "patStr");
        /** @internal */
        __publicField(this, "textEncoder", new TextEncoder());
        /** @internal */
        __publicField(this, "textDecoder", new TextDecoder("utf-8"));
        /** @internal */
        __publicField(this, "rankMap", /* @__PURE__ */ new Map());
        /** @internal */
        __publicField(this, "textMap", /* @__PURE__ */ new Map());
        this.patStr = ranks.pat_str;
        const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo3, x2) => {
          const [_2, offsetStr, ...tokens] = x2.split(" ");
          const offset5 = Number.parseInt(offsetStr, 10);
          tokens.forEach((token, i3) => memo3[token] = offset5 + i3);
          return memo3;
        }, {});
        for (const [token, rank] of Object.entries(uncompressed)) {
          const bytes = import_base64_js.default.toByteArray(token);
          this.rankMap.set(bytes.join(","), rank);
          this.textMap.set(rank, bytes);
        }
        this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens };
        this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo3, [text, rank]) => {
          memo3[rank] = this.textEncoder.encode(text);
          return memo3;
        }, {});
      }
      encode(text, allowedSpecial = [], disallowedSpecial = "all") {
        const regexes = new RegExp(this.patStr, "ug");
        const specialRegex = _Tiktoken.specialTokenRegex(
          Object.keys(this.specialTokens)
        );
        const ret = [];
        const allowedSpecialSet = new Set(
          allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial
        );
        const disallowedSpecialSet = new Set(
          disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter(
            (x2) => !allowedSpecialSet.has(x2)
          ) : disallowedSpecial
        );
        if (disallowedSpecialSet.size > 0) {
          const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([
            ...disallowedSpecialSet
          ]);
          const specialMatch = text.match(disallowedSpecialRegex);
          if (specialMatch != null) {
            throw new Error(
              `The text contains a special token that is not allowed: ${specialMatch[0]}`
            );
          }
        }
        let start = 0;
        while (true) {
          let nextSpecial = null;
          let startFind = start;
          while (true) {
            specialRegex.lastIndex = startFind;
            nextSpecial = specialRegex.exec(text);
            if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0]))
              break;
            startFind = nextSpecial.index + 1;
          }
          const end = nextSpecial?.index ?? text.length;
          for (const match2 of text.substring(start, end).matchAll(regexes)) {
            const piece = this.textEncoder.encode(match2[0]);
            const token2 = this.rankMap.get(piece.join(","));
            if (token2 != null) {
              ret.push(token2);
              continue;
            }
            ret.push(...bytePairEncode(piece, this.rankMap));
          }
          if (nextSpecial == null)
            break;
          let token = this.specialTokens[nextSpecial[0]];
          ret.push(token);
          start = nextSpecial.index + nextSpecial[0].length;
        }
        return ret;
      }
      decode(tokens) {
        const res = [];
        let length = 0;
        for (let i22 = 0; i22 < tokens.length; ++i22) {
          const token = tokens[i22];
          const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token];
          if (bytes != null) {
            res.push(bytes);
            length += bytes.length;
          }
        }
        const mergedArray = new Uint8Array(length);
        let i3 = 0;
        for (const bytes of res) {
          mergedArray.set(bytes, i3);
          i3 += bytes.length;
        }
        return this.textDecoder.decode(mergedArray);
      }
    };
    Tiktoken = _Tiktoken;
    __publicField2(Tiktoken, "specialTokenRegex", (tokens) => {
      return new RegExp(tokens.map((i3) => escapeRegex(i3)).join("|"), "g");
    });
  }
});

// node_modules/js-tiktoken/dist/lite.js
var init_lite = __esm({
  "node_modules/js-tiktoken/dist/lite.js"() {
    init_chunk_XX6PTLQF();
  }
});

// node_modules/@langchain/core/dist/utils/tiktoken.js
async function getEncoding(encoding) {
  if (!(encoding in cache)) {
    cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e3) => {
      delete cache[encoding];
      throw e3;
    });
  }
  return await cache[encoding];
}
async function encodingForModel(model) {
  return getEncoding(getEncodingNameForModel(model));
}
var cache, caller;
var init_tiktoken = __esm({
  "node_modules/@langchain/core/dist/utils/tiktoken.js"() {
    init_lite();
    init_async_caller2();
    cache = {};
    caller = /* @__PURE__ */ new AsyncCaller2({});
  }
});

// node_modules/@langchain/core/dist/language_models/base.js
function isOpenAITool(tool2) {
  if (typeof tool2 !== "object" || !tool2)
    return false;
  if ("type" in tool2 && tool2.type === "function" && "function" in tool2 && typeof tool2.function === "object" && tool2.function && "name" in tool2.function && "parameters" in tool2.function) {
    return true;
  }
  return false;
}
var getModelNameForTiktoken, getVerbosity, BaseLangChain, BaseLanguageModel;
var init_base8 = __esm({
  "node_modules/@langchain/core/dist/language_models/base.js"() {
    init_base7();
    init_prompt_values();
    init_utils2();
    init_async_caller2();
    init_tiktoken();
    init_base4();
    getModelNameForTiktoken = (modelName) => {
      if (modelName.startsWith("gpt-3.5-turbo-16k")) {
        return "gpt-3.5-turbo-16k";
      }
      if (modelName.startsWith("gpt-3.5-turbo-")) {
        return "gpt-3.5-turbo";
      }
      if (modelName.startsWith("gpt-4-32k")) {
        return "gpt-4-32k";
      }
      if (modelName.startsWith("gpt-4-")) {
        return "gpt-4";
      }
      if (modelName.startsWith("gpt-4o")) {
        return "gpt-4o";
      }
      return modelName;
    };
    getVerbosity = () => false;
    BaseLangChain = class extends Runnable {
      get lc_attributes() {
        return {
          callbacks: void 0,
          verbose: void 0
        };
      }
      constructor(params) {
        super(params);
        Object.defineProperty(this, "verbose", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "callbacks", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "tags", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.verbose = params.verbose ?? getVerbosity();
        this.callbacks = params.callbacks;
        this.tags = params.tags ?? [];
        this.metadata = params.metadata ?? {};
      }
    };
    BaseLanguageModel = class extends BaseLangChain {
      /**
       * Keys that the language model accepts as call options.
       */
      get callKeys() {
        return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"];
      }
      constructor({ callbacks, callbackManager, ...params }) {
        const { cache: cache2, ...rest } = params;
        super({
          callbacks: callbacks ?? callbackManager,
          ...rest
        });
        Object.defineProperty(this, "caller", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "cache", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "_encoding", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        if (typeof cache2 === "object") {
          this.cache = cache2;
        } else if (cache2) {
          this.cache = InMemoryCache.global();
        } else {
          this.cache = void 0;
        }
        this.caller = new AsyncCaller2(params ?? {});
      }
      async getNumTokens(content) {
        if (typeof content !== "string") {
          return 0;
        }
        let numTokens = Math.ceil(content.length / 4);
        if (!this._encoding) {
          try {
            this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2");
          } catch (error) {
            console.warn("Failed to calculate number of tokens, falling back to approximate count", error);
          }
        }
        if (this._encoding) {
          try {
            numTokens = this._encoding.encode(content).length;
          } catch (error) {
            console.warn("Failed to calculate number of tokens, falling back to approximate count", error);
          }
        }
        return numTokens;
      }
      static _convertInputToPromptValue(input) {
        if (typeof input === "string") {
          return new StringPromptValue(input);
        } else if (Array.isArray(input)) {
          return new ChatPromptValue(input.map(coerceMessageLikeToMessage));
        } else {
          return input;
        }
      }
      /**
       * Get the identifying parameters of the LLM.
       */
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      _identifyingParams() {
        return {};
      }
      /**
       * Create a unique cache key for a specific call to a specific language model.
       * @param callOptions Call options for the model
       * @returns A unique cache key.
       */
      _getSerializedCacheKeyParametersForCall({ config, ...callOptions }) {
        const params = {
          ...this._identifyingParams(),
          ...callOptions,
          _type: this._llmType(),
          _model: this._modelType()
        };
        const filteredEntries = Object.entries(params).filter(([_2, value]) => value !== void 0);
        const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(",");
        return serializedEntries;
      }
      /**
       * @deprecated
       * Return a json-like object representing this LLM.
       */
      serialize() {
        return {
          ...this._identifyingParams(),
          _type: this._llmType(),
          _model: this._modelType()
        };
      }
      /**
       * @deprecated
       * Load an LLM from a json-like object describing it.
       */
      static async deserialize(_data3) {
        throw new Error("Use .toJSON() instead");
      }
    };
  }
});

// node_modules/@langchain/core/language_models/base.js
var init_base9 = __esm({
  "node_modules/@langchain/core/language_models/base.js"() {
    init_base8();
  }
});

// node_modules/@langchain/core/outputs.js
var init_outputs2 = __esm({
  "node_modules/@langchain/core/outputs.js"() {
    init_outputs();
  }
});

// (disabled):crypto
var require_crypto2 = __commonJS({
  "(disabled):crypto"() {
  }
});

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

// node_modules/crypto-js/x64-core.js
var require_x64_core = __commonJS({
  "node_modules/crypto-js/x64-core.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(undefined2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Base = C_lib.Base;
        var X32WordArray = C_lib.WordArray;
        var C_x64 = C3.x64 = {};
        var X64Word = C_x64.Word = Base.extend({
          /**
           * Initializes a newly created 64-bit word.
           *
           * @param {number} high The high 32 bits.
           * @param {number} low The low 32 bits.
           *
           * @example
           *
           *     var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
           */
          init: function(high, low) {
            this.high = high;
            this.low = low;
          }
          /**
           * Bitwise NOTs this word.
           *
           * @return {X64Word} A new x64-Word object after negating.
           *
           * @example
           *
           *     var negated = x64Word.not();
           */
          // not: function () {
          // var high = ~this.high;
          // var low = ~this.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ANDs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to AND with this word.
           *
           * @return {X64Word} A new x64-Word object after ANDing.
           *
           * @example
           *
           *     var anded = x64Word.and(anotherX64Word);
           */
          // and: function (word) {
          // var high = this.high & word.high;
          // var low = this.low & word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to OR with this word.
           *
           * @return {X64Word} A new x64-Word object after ORing.
           *
           * @example
           *
           *     var ored = x64Word.or(anotherX64Word);
           */
          // or: function (word) {
          // var high = this.high | word.high;
          // var low = this.low | word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise XORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to XOR with this word.
           *
           * @return {X64Word} A new x64-Word object after XORing.
           *
           * @example
           *
           *     var xored = x64Word.xor(anotherX64Word);
           */
          // xor: function (word) {
          // var high = this.high ^ word.high;
          // var low = this.low ^ word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the left.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftL(25);
           */
          // shiftL: function (n) {
          // if (n < 32) {
          // var high = (this.high << n) | (this.low >>> (32 - n));
          // var low = this.low << n;
          // } else {
          // var high = this.low << (n - 32);
          // var low = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the right.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftR(7);
           */
          // shiftR: function (n) {
          // if (n < 32) {
          // var low = (this.low >>> n) | (this.high << (32 - n));
          // var high = this.high >>> n;
          // } else {
          // var low = this.high >>> (n - 32);
          // var high = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Rotates this word n bits to the left.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotL(25);
           */
          // rotL: function (n) {
          // return this.shiftL(n).or(this.shiftR(64 - n));
          // },
          /**
           * Rotates this word n bits to the right.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotR(7);
           */
          // rotR: function (n) {
          // return this.shiftR(n).or(this.shiftL(64 - n));
          // },
          /**
           * Adds this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to add with this word.
           *
           * @return {X64Word} A new x64-Word object after adding.
           *
           * @example
           *
           *     var added = x64Word.add(anotherX64Word);
           */
          // add: function (word) {
          // var low = (this.low + word.low) | 0;
          // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
          // var high = (this.high + word.high + carry) | 0;
          // return X64Word.create(high, low);
          // }
        });
        var X64WordArray = C_x64.WordArray = Base.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.x64.WordArray.create();
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ]);
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ], 10);
           */
          init: function(words, sigBytes) {
            words = this.words = words || [];
            if (sigBytes != undefined2) {
              this.sigBytes = sigBytes;
            } else {
              this.sigBytes = words.length * 8;
            }
          },
          /**
           * Converts this 64-bit word array to a 32-bit word array.
           *
           * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
           *
           * @example
           *
           *     var x32WordArray = x64WordArray.toX32();
           */
          toX32: function() {
            var x64Words = this.words;
            var x64WordsLength = x64Words.length;
            var x32Words = [];
            for (var i3 = 0; i3 < x64WordsLength; i3++) {
              var x64Word = x64Words[i3];
              x32Words.push(x64Word.high);
              x32Words.push(x64Word.low);
            }
            return X32WordArray.create(x32Words, this.sigBytes);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {X64WordArray} The clone.
           *
           * @example
           *
           *     var clone = x64WordArray.clone();
           */
          clone: function() {
            var clone3 = Base.clone.call(this);
            var words = clone3.words = this.words.slice(0);
            var wordsLength = words.length;
            for (var i3 = 0; i3 < wordsLength; i3++) {
              words[i3] = words[i3].clone();
            }
            return clone3;
          }
        });
      })();
      return CryptoJS;
    });
  }
});

// node_modules/crypto-js/lib-typedarrays.js
var require_lib_typedarrays = __commonJS({
  "node_modules/crypto-js/lib-typedarrays.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        if (typeof ArrayBuffer != "function") {
          return;
        }
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var superInit = WordArray.init;
        var subInit = WordArray.init = function(typedArray) {
          if (typedArray instanceof ArrayBuffer) {
            typedArray = new Uint8Array(typedArray);
          }
          if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
            typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
          }
          if (typedArray instanceof Uint8Array) {
            var typedArrayByteLength = typedArray.byteLength;
            var words = [];
            for (var i3 = 0; i3 < typedArrayByteLength; i3++) {
              words[i3 >>> 2] |= typedArray[i3] << 24 - i3 % 4 * 8;
            }
            superInit.call(this, words, typedArrayByteLength);
          } else {
            superInit.apply(this, arguments);
          }
        };
        subInit.prototype = WordArray;
      })();
      return CryptoJS.lib.WordArray;
    });
  }
});

// node_modules/crypto-js/enc-utf16.js
var require_enc_utf16 = __commonJS({
  "node_modules/crypto-js/enc-utf16.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C3.enc;
        var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
          /**
           * Converts a word array to a UTF-16 BE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 BE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var utf16Chars = [];
            for (var i3 = 0; i3 < sigBytes; i3 += 2) {
              var codePoint = words[i3 >>> 2] >>> 16 - i3 % 4 * 8 & 65535;
              utf16Chars.push(String.fromCharCode(codePoint));
            }
            return utf16Chars.join("");
          },
          /**
           * Converts a UTF-16 BE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 BE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
           */
          parse: function(utf16Str) {
            var utf16StrLength = utf16Str.length;
            var words = [];
            for (var i3 = 0; i3 < utf16StrLength; i3++) {
              words[i3 >>> 1] |= utf16Str.charCodeAt(i3) << 16 - i3 % 2 * 16;
            }
            return WordArray.create(words, utf16StrLength * 2);
          }
        };
        C_enc.Utf16LE = {
          /**
           * Converts a word array to a UTF-16 LE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 LE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var utf16Chars = [];
            for (var i3 = 0; i3 < sigBytes; i3 += 2) {
              var codePoint = swapEndian(words[i3 >>> 2] >>> 16 - i3 % 4 * 8 & 65535);
              utf16Chars.push(String.fromCharCode(codePoint));
            }
            return utf16Chars.join("");
          },
          /**
           * Converts a UTF-16 LE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 LE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
           */
          parse: function(utf16Str) {
            var utf16StrLength = utf16Str.length;
            var words = [];
            for (var i3 = 0; i3 < utf16StrLength; i3++) {
              words[i3 >>> 1] |= swapEndian(utf16Str.charCodeAt(i3) << 16 - i3 % 2 * 16);
            }
            return WordArray.create(words, utf16StrLength * 2);
          }
        };
        function swapEndian(word) {
          return word << 8 & 4278255360 | word >>> 8 & 16711935;
        }
      })();
      return CryptoJS.enc.Utf16;
    });
  }
});

// node_modules/crypto-js/enc-base64.js
var require_enc_base64 = __commonJS({
  "node_modules/crypto-js/enc-base64.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C3.enc;
        var Base642 = C_enc.Base64 = {
          /**
           * Converts a word array to a Base64 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Base64 string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var map = this._map;
            wordArray.clamp();
            var base64Chars = [];
            for (var i3 = 0; i3 < sigBytes; i3 += 3) {
              var byte1 = words[i3 >>> 2] >>> 24 - i3 % 4 * 8 & 255;
              var byte2 = words[i3 + 1 >>> 2] >>> 24 - (i3 + 1) % 4 * 8 & 255;
              var byte3 = words[i3 + 2 >>> 2] >>> 24 - (i3 + 2) % 4 * 8 & 255;
              var triplet = byte1 << 16 | byte2 << 8 | byte3;
              for (var j3 = 0; j3 < 4 && i3 + j3 * 0.75 < sigBytes; j3++) {
                base64Chars.push(map.charAt(triplet >>> 6 * (3 - j3) & 63));
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              while (base64Chars.length % 4) {
                base64Chars.push(paddingChar);
              }
            }
            return base64Chars.join("");
          },
          /**
           * Converts a Base64 string to a word array.
           *
           * @param {string} base64Str The Base64 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64.parse(base64String);
           */
          parse: function(base64Str) {
            var base64StrLength = base64Str.length;
            var map = this._map;
            var reverseMap = this._reverseMap;
            if (!reverseMap) {
              reverseMap = this._reverseMap = [];
              for (var j3 = 0; j3 < map.length; j3++) {
                reverseMap[map.charCodeAt(j3)] = j3;
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              var paddingIndex = base64Str.indexOf(paddingChar);
              if (paddingIndex !== -1) {
                base64StrLength = paddingIndex;
              }
            }
            return parseLoop(base64Str, base64StrLength, reverseMap);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        };
        function parseLoop(base64Str, base64StrLength, reverseMap) {
          var words = [];
          var nBytes = 0;
          for (var i3 = 0; i3 < base64StrLength; i3++) {
            if (i3 % 4) {
              var bits1 = reverseMap[base64Str.charCodeAt(i3 - 1)] << i3 % 4 * 2;
              var bits2 = reverseMap[base64Str.charCodeAt(i3)] >>> 6 - i3 % 4 * 2;
              var bitsCombined = bits1 | bits2;
              words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
              nBytes++;
            }
          }
          return WordArray.create(words, nBytes);
        }
      })();
      return CryptoJS.enc.Base64;
    });
  }
});

// node_modules/crypto-js/enc-base64url.js
var require_enc_base64url = __commonJS({
  "node_modules/crypto-js/enc-base64url.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C3.enc;
        var Base64url = C_enc.Base64url = {
          /**
           * Converts a word array to a Base64url string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {string} The Base64url string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
           */
          stringify: function(wordArray, urlSafe) {
            if (urlSafe === void 0) {
              urlSafe = true;
            }
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var map = urlSafe ? this._safe_map : this._map;
            wordArray.clamp();
            var base64Chars = [];
            for (var i3 = 0; i3 < sigBytes; i3 += 3) {
              var byte1 = words[i3 >>> 2] >>> 24 - i3 % 4 * 8 & 255;
              var byte2 = words[i3 + 1 >>> 2] >>> 24 - (i3 + 1) % 4 * 8 & 255;
              var byte3 = words[i3 + 2 >>> 2] >>> 24 - (i3 + 2) % 4 * 8 & 255;
              var triplet = byte1 << 16 | byte2 << 8 | byte3;
              for (var j3 = 0; j3 < 4 && i3 + j3 * 0.75 < sigBytes; j3++) {
                base64Chars.push(map.charAt(triplet >>> 6 * (3 - j3) & 63));
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              while (base64Chars.length % 4) {
                base64Chars.push(paddingChar);
              }
            }
            return base64Chars.join("");
          },
          /**
           * Converts a Base64url string to a word array.
           *
           * @param {string} base64Str The Base64url string.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64url.parse(base64String);
           */
          parse: function(base64Str, urlSafe) {
            if (urlSafe === void 0) {
              urlSafe = true;
            }
            var base64StrLength = base64Str.length;
            var map = urlSafe ? this._safe_map : this._map;
            var reverseMap = this._reverseMap;
            if (!reverseMap) {
              reverseMap = this._reverseMap = [];
              for (var j3 = 0; j3 < map.length; j3++) {
                reverseMap[map.charCodeAt(j3)] = j3;
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              var paddingIndex = base64Str.indexOf(paddingChar);
              if (paddingIndex !== -1) {
                base64StrLength = paddingIndex;
              }
            }
            return parseLoop(base64Str, base64StrLength, reverseMap);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
          _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
        };
        function parseLoop(base64Str, base64StrLength, reverseMap) {
          var words = [];
          var nBytes = 0;
          for (var i3 = 0; i3 < base64StrLength; i3++) {
            if (i3 % 4) {
              var bits1 = reverseMap[base64Str.charCodeAt(i3 - 1)] << i3 % 4 * 2;
              var bits2 = reverseMap[base64Str.charCodeAt(i3)] >>> 6 - i3 % 4 * 2;
              var bitsCombined = bits1 | bits2;
              words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
              nBytes++;
            }
          }
          return WordArray.create(words, nBytes);
        }
      })();
      return CryptoJS.enc.Base64url;
    });
  }
});

// node_modules/crypto-js/md5.js
var require_md5 = __commonJS({
  "node_modules/crypto-js/md5.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(Math2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C3.algo;
        var T = [];
        (function() {
          for (var i3 = 0; i3 < 64; i3++) {
            T[i3] = Math2.abs(Math2.sin(i3 + 1)) * 4294967296 | 0;
          }
        })();
        var MD54 = C_algo.MD5 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              1732584193,
              4023233417,
              2562383102,
              271733878
            ]);
          },
          _doProcessBlock: function(M, offset5) {
            for (var i3 = 0; i3 < 16; i3++) {
              var offset_i = offset5 + i3;
              var M_offset_i = M[offset_i];
              M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
            }
            var H2 = this._hash.words;
            var M_offset_0 = M[offset5 + 0];
            var M_offset_1 = M[offset5 + 1];
            var M_offset_2 = M[offset5 + 2];
            var M_offset_3 = M[offset5 + 3];
            var M_offset_4 = M[offset5 + 4];
            var M_offset_5 = M[offset5 + 5];
            var M_offset_6 = M[offset5 + 6];
            var M_offset_7 = M[offset5 + 7];
            var M_offset_8 = M[offset5 + 8];
            var M_offset_9 = M[offset5 + 9];
            var M_offset_10 = M[offset5 + 10];
            var M_offset_11 = M[offset5 + 11];
            var M_offset_12 = M[offset5 + 12];
            var M_offset_13 = M[offset5 + 13];
            var M_offset_14 = M[offset5 + 14];
            var M_offset_15 = M[offset5 + 15];
            var a3 = H2[0];
            var b3 = H2[1];
            var c4 = H2[2];
            var d3 = H2[3];
            a3 = FF(a3, b3, c4, d3, M_offset_0, 7, T[0]);
            d3 = FF(d3, a3, b3, c4, M_offset_1, 12, T[1]);
            c4 = FF(c4, d3, a3, b3, M_offset_2, 17, T[2]);
            b3 = FF(b3, c4, d3, a3, M_offset_3, 22, T[3]);
            a3 = FF(a3, b3, c4, d3, M_offset_4, 7, T[4]);
            d3 = FF(d3, a3, b3, c4, M_offset_5, 12, T[5]);
            c4 = FF(c4, d3, a3, b3, M_offset_6, 17, T[6]);
            b3 = FF(b3, c4, d3, a3, M_offset_7, 22, T[7]);
            a3 = FF(a3, b3, c4, d3, M_offset_8, 7, T[8]);
            d3 = FF(d3, a3, b3, c4, M_offset_9, 12, T[9]);
            c4 = FF(c4, d3, a3, b3, M_offset_10, 17, T[10]);
            b3 = FF(b3, c4, d3, a3, M_offset_11, 22, T[11]);
            a3 = FF(a3, b3, c4, d3, M_offset_12, 7, T[12]);
            d3 = FF(d3, a3, b3, c4, M_offset_13, 12, T[13]);
            c4 = FF(c4, d3, a3, b3, M_offset_14, 17, T[14]);
            b3 = FF(b3, c4, d3, a3, M_offset_15, 22, T[15]);
            a3 = GG(a3, b3, c4, d3, M_offset_1, 5, T[16]);
            d3 = GG(d3, a3, b3, c4, M_offset_6, 9, T[17]);
            c4 = GG(c4, d3, a3, b3, M_offset_11, 14, T[18]);
            b3 = GG(b3, c4, d3, a3, M_offset_0, 20, T[19]);
            a3 = GG(a3, b3, c4, d3, M_offset_5, 5, T[20]);
            d3 = GG(d3, a3, b3, c4, M_offset_10, 9, T[21]);
            c4 = GG(c4, d3, a3, b3, M_offset_15, 14, T[22]);
            b3 = GG(b3, c4, d3, a3, M_offset_4, 20, T[23]);
            a3 = GG(a3, b3, c4, d3, M_offset_9, 5, T[24]);
            d3 = GG(d3, a3, b3, c4, M_offset_14, 9, T[25]);
            c4 = GG(c4, d3, a3, b3, M_offset_3, 14, T[26]);
            b3 = GG(b3, c4, d3, a3, M_offset_8, 20, T[27]);
            a3 = GG(a3, b3, c4, d3, M_offset_13, 5, T[28]);
            d3 = GG(d3, a3, b3, c4, M_offset_2, 9, T[29]);
            c4 = GG(c4, d3, a3, b3, M_offset_7, 14, T[30]);
            b3 = GG(b3, c4, d3, a3, M_offset_12, 20, T[31]);
            a3 = HH(a3, b3, c4, d3, M_offset_5, 4, T[32]);
            d3 = HH(d3, a3, b3, c4, M_offset_8, 11, T[33]);
            c4 = HH(c4, d3, a3, b3, M_offset_11, 16, T[34]);
            b3 = HH(b3, c4, d3, a3, M_offset_14, 23, T[35]);
            a3 = HH(a3, b3, c4, d3, M_offset_1, 4, T[36]);
            d3 = HH(d3, a3, b3, c4, M_offset_4, 11, T[37]);
            c4 = HH(c4, d3, a3, b3, M_offset_7, 16, T[38]);
            b3 = HH(b3, c4, d3, a3, M_offset_10, 23, T[39]);
            a3 = HH(a3, b3, c4, d3, M_offset_13, 4, T[40]);
            d3 = HH(d3, a3, b3, c4, M_offset_0, 11, T[41]);
            c4 = HH(c4, d3, a3, b3, M_offset_3, 16, T[42]);
            b3 = HH(b3, c4, d3, a3, M_offset_6, 23, T[43]);
            a3 = HH(a3, b3, c4, d3, M_offset_9, 4, T[44]);
            d3 = HH(d3, a3, b3, c4, M_offset_12, 11, T[45]);
            c4 = HH(c4, d3, a3, b3, M_offset_15, 16, T[46]);
            b3 = HH(b3, c4, d3, a3, M_offset_2, 23, T[47]);
            a3 = II(a3, b3, c4, d3, M_offset_0, 6, T[48]);
            d3 = II(d3, a3, b3, c4, M_offset_7, 10, T[49]);
            c4 = II(c4, d3, a3, b3, M_offset_14, 15, T[50]);
            b3 = II(b3, c4, d3, a3, M_offset_5, 21, T[51]);
            a3 = II(a3, b3, c4, d3, M_offset_12, 6, T[52]);
            d3 = II(d3, a3, b3, c4, M_offset_3, 10, T[53]);
            c4 = II(c4, d3, a3, b3, M_offset_10, 15, T[54]);
            b3 = II(b3, c4, d3, a3, M_offset_1, 21, T[55]);
            a3 = II(a3, b3, c4, d3, M_offset_8, 6, T[56]);
            d3 = II(d3, a3, b3, c4, M_offset_15, 10, T[57]);
            c4 = II(c4, d3, a3, b3, M_offset_6, 15, T[58]);
            b3 = II(b3, c4, d3, a3, M_offset_13, 21, T[59]);
            a3 = II(a3, b3, c4, d3, M_offset_4, 6, T[60]);
            d3 = II(d3, a3, b3, c4, M_offset_11, 10, T[61]);
            c4 = II(c4, d3, a3, b3, M_offset_2, 15, T[62]);
            b3 = II(b3, c4, d3, a3, M_offset_9, 21, T[63]);
            H2[0] = H2[0] + a3 | 0;
            H2[1] = H2[1] + b3 | 0;
            H2[2] = H2[2] + c4 | 0;
            H2[3] = H2[3] + d3 | 0;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            var nBitsTotalH = Math2.floor(nBitsTotal / 4294967296);
            var nBitsTotalL = nBitsTotal;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 16711935 | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 4278255360;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 16711935 | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 4278255360;
            data.sigBytes = (dataWords.length + 1) * 4;
            this._process();
            var hash = this._hash;
            var H2 = hash.words;
            for (var i3 = 0; i3 < 4; i3++) {
              var H_i = H2[i3];
              H2[i3] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
            }
            return hash;
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            clone3._hash = this._hash.clone();
            return clone3;
          }
        });
        function FF(a3, b3, c4, d3, x2, s4, t3) {
          var n4 = a3 + (b3 & c4 | ~b3 & d3) + x2 + t3;
          return (n4 << s4 | n4 >>> 32 - s4) + b3;
        }
        function GG(a3, b3, c4, d3, x2, s4, t3) {
          var n4 = a3 + (b3 & d3 | c4 & ~d3) + x2 + t3;
          return (n4 << s4 | n4 >>> 32 - s4) + b3;
        }
        function HH(a3, b3, c4, d3, x2, s4, t3) {
          var n4 = a3 + (b3 ^ c4 ^ d3) + x2 + t3;
          return (n4 << s4 | n4 >>> 32 - s4) + b3;
        }
        function II(a3, b3, c4, d3, x2, s4, t3) {
          var n4 = a3 + (c4 ^ (b3 | ~d3)) + x2 + t3;
          return (n4 << s4 | n4 >>> 32 - s4) + b3;
        }
        C3.MD5 = Hasher._createHelper(MD54);
        C3.HmacMD5 = Hasher._createHmacHelper(MD54);
      })(Math);
      return CryptoJS.MD5;
    });
  }
});

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

// node_modules/crypto-js/sha256.js
var require_sha256 = __commonJS({
  "node_modules/crypto-js/sha256.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(Math2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C3.algo;
        var H2 = [];
        var K2 = [];
        (function() {
          function isPrime(n5) {
            var sqrtN = Math2.sqrt(n5);
            for (var factor = 2; factor <= sqrtN; factor++) {
              if (!(n5 % factor)) {
                return false;
              }
            }
            return true;
          }
          function getFractionalBits(n5) {
            return (n5 - (n5 | 0)) * 4294967296 | 0;
          }
          var n4 = 2;
          var nPrime = 0;
          while (nPrime < 64) {
            if (isPrime(n4)) {
              if (nPrime < 8) {
                H2[nPrime] = getFractionalBits(Math2.pow(n4, 1 / 2));
              }
              K2[nPrime] = getFractionalBits(Math2.pow(n4, 1 / 3));
              nPrime++;
            }
            n4++;
          }
        })();
        var W = [];
        var SHA256 = C_algo.SHA256 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init(H2.slice(0));
          },
          _doProcessBlock: function(M, offset5) {
            var H3 = this._hash.words;
            var a3 = H3[0];
            var b3 = H3[1];
            var c4 = H3[2];
            var d3 = H3[3];
            var e3 = H3[4];
            var f3 = H3[5];
            var g4 = H3[6];
            var h3 = H3[7];
            for (var i3 = 0; i3 < 64; i3++) {
              if (i3 < 16) {
                W[i3] = M[offset5 + i3] | 0;
              } else {
                var gamma0x = W[i3 - 15];
                var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
                var gamma1x = W[i3 - 2];
                var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
                W[i3] = gamma0 + W[i3 - 7] + gamma1 + W[i3 - 16];
              }
              var ch = e3 & f3 ^ ~e3 & g4;
              var maj = a3 & b3 ^ a3 & c4 ^ b3 & c4;
              var sigma0 = (a3 << 30 | a3 >>> 2) ^ (a3 << 19 | a3 >>> 13) ^ (a3 << 10 | a3 >>> 22);
              var sigma1 = (e3 << 26 | e3 >>> 6) ^ (e3 << 21 | e3 >>> 11) ^ (e3 << 7 | e3 >>> 25);
              var t1 = h3 + sigma1 + ch + K2[i3] + W[i3];
              var t22 = sigma0 + maj;
              h3 = g4;
              g4 = f3;
              f3 = e3;
              e3 = d3 + t1 | 0;
              d3 = c4;
              c4 = b3;
              b3 = a3;
              a3 = t1 + t22 | 0;
            }
            H3[0] = H3[0] + a3 | 0;
            H3[1] = H3[1] + b3 | 0;
            H3[2] = H3[2] + c4 | 0;
            H3[3] = H3[3] + d3 | 0;
            H3[4] = H3[4] + e3 | 0;
            H3[5] = H3[5] + f3 | 0;
            H3[6] = H3[6] + g4 | 0;
            H3[7] = H3[7] + h3 | 0;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            clone3._hash = this._hash.clone();
            return clone3;
          }
        });
        C3.SHA256 = Hasher._createHelper(SHA256);
        C3.HmacSHA256 = Hasher._createHmacHelper(SHA256);
      })(Math);
      return CryptoJS.SHA256;
    });
  }
});

// node_modules/crypto-js/sha224.js
var require_sha224 = __commonJS({
  "node_modules/crypto-js/sha224.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_sha256());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./sha256"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var C_algo = C3.algo;
        var SHA256 = C_algo.SHA256;
        var SHA224 = C_algo.SHA224 = SHA256.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              3238371032,
              914150663,
              812702999,
              4144912697,
              4290775857,
              1750603025,
              1694076839,
              3204075428
            ]);
          },
          _doFinalize: function() {
            var hash = SHA256._doFinalize.call(this);
            hash.sigBytes -= 4;
            return hash;
          }
        });
        C3.SHA224 = SHA256._createHelper(SHA224);
        C3.HmacSHA224 = SHA256._createHmacHelper(SHA224);
      })();
      return CryptoJS.SHA224;
    });
  }
});

// node_modules/crypto-js/sha512.js
var require_sha512 = __commonJS({
  "node_modules/crypto-js/sha512.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_x64_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./x64-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Hasher = C_lib.Hasher;
        var C_x64 = C3.x64;
        var X64Word = C_x64.Word;
        var X64WordArray = C_x64.WordArray;
        var C_algo = C3.algo;
        function X64Word_create() {
          return X64Word.create.apply(X64Word, arguments);
        }
        var K2 = [
          X64Word_create(1116352408, 3609767458),
          X64Word_create(1899447441, 602891725),
          X64Word_create(3049323471, 3964484399),
          X64Word_create(3921009573, 2173295548),
          X64Word_create(961987163, 4081628472),
          X64Word_create(1508970993, 3053834265),
          X64Word_create(2453635748, 2937671579),
          X64Word_create(2870763221, 3664609560),
          X64Word_create(3624381080, 2734883394),
          X64Word_create(310598401, 1164996542),
          X64Word_create(607225278, 1323610764),
          X64Word_create(1426881987, 3590304994),
          X64Word_create(1925078388, 4068182383),
          X64Word_create(2162078206, 991336113),
          X64Word_create(2614888103, 633803317),
          X64Word_create(3248222580, 3479774868),
          X64Word_create(3835390401, 2666613458),
          X64Word_create(4022224774, 944711139),
          X64Word_create(264347078, 2341262773),
          X64Word_create(604807628, 2007800933),
          X64Word_create(770255983, 1495990901),
          X64Word_create(1249150122, 1856431235),
          X64Word_create(1555081692, 3175218132),
          X64Word_create(1996064986, 2198950837),
          X64Word_create(2554220882, 3999719339),
          X64Word_create(2821834349, 766784016),
          X64Word_create(2952996808, 2566594879),
          X64Word_create(3210313671, 3203337956),
          X64Word_create(3336571891, 1034457026),
          X64Word_create(3584528711, 2466948901),
          X64Word_create(113926993, 3758326383),
          X64Word_create(338241895, 168717936),
          X64Word_create(666307205, 1188179964),
          X64Word_create(773529912, 1546045734),
          X64Word_create(1294757372, 1522805485),
          X64Word_create(1396182291, 2643833823),
          X64Word_create(1695183700, 2343527390),
          X64Word_create(1986661051, 1014477480),
          X64Word_create(2177026350, 1206759142),
          X64Word_create(2456956037, 344077627),
          X64Word_create(2730485921, 1290863460),
          X64Word_create(2820302411, 3158454273),
          X64Word_create(3259730800, 3505952657),
          X64Word_create(3345764771, 106217008),
          X64Word_create(3516065817, 3606008344),
          X64Word_create(3600352804, 1432725776),
          X64Word_create(4094571909, 1467031594),
          X64Word_create(275423344, 851169720),
          X64Word_create(430227734, 3100823752),
          X64Word_create(506948616, 1363258195),
          X64Word_create(659060556, 3750685593),
          X64Word_create(883997877, 3785050280),
          X64Word_create(958139571, 3318307427),
          X64Word_create(1322822218, 3812723403),
          X64Word_create(1537002063, 2003034995),
          X64Word_create(1747873779, 3602036899),
          X64Word_create(1955562222, 1575990012),
          X64Word_create(2024104815, 1125592928),
          X64Word_create(2227730452, 2716904306),
          X64Word_create(2361852424, 442776044),
          X64Word_create(2428436474, 593698344),
          X64Word_create(2756734187, 3733110249),
          X64Word_create(3204031479, 2999351573),
          X64Word_create(3329325298, 3815920427),
          X64Word_create(3391569614, 3928383900),
          X64Word_create(3515267271, 566280711),
          X64Word_create(3940187606, 3454069534),
          X64Word_create(4118630271, 4000239992),
          X64Word_create(116418474, 1914138554),
          X64Word_create(174292421, 2731055270),
          X64Word_create(289380356, 3203993006),
          X64Word_create(460393269, 320620315),
          X64Word_create(685471733, 587496836),
          X64Word_create(852142971, 1086792851),
          X64Word_create(1017036298, 365543100),
          X64Word_create(1126000580, 2618297676),
          X64Word_create(1288033470, 3409855158),
          X64Word_create(1501505948, 4234509866),
          X64Word_create(1607167915, 987167468),
          X64Word_create(1816402316, 1246189591)
        ];
        var W = [];
        (function() {
          for (var i3 = 0; i3 < 80; i3++) {
            W[i3] = X64Word_create();
          }
        })();
        var SHA512 = C_algo.SHA512 = Hasher.extend({
          _doReset: function() {
            this._hash = new X64WordArray.init([
              new X64Word.init(1779033703, 4089235720),
              new X64Word.init(3144134277, 2227873595),
              new X64Word.init(1013904242, 4271175723),
              new X64Word.init(2773480762, 1595750129),
              new X64Word.init(1359893119, 2917565137),
              new X64Word.init(2600822924, 725511199),
              new X64Word.init(528734635, 4215389547),
              new X64Word.init(1541459225, 327033209)
            ]);
          },
          _doProcessBlock: function(M, offset5) {
            var H2 = this._hash.words;
            var H0 = H2[0];
            var H1 = H2[1];
            var H22 = H2[2];
            var H3 = H2[3];
            var H4 = H2[4];
            var H5 = H2[5];
            var H6 = H2[6];
            var H7 = H2[7];
            var H0h = H0.high;
            var H0l = H0.low;
            var H1h = H1.high;
            var H1l = H1.low;
            var H2h = H22.high;
            var H2l = H22.low;
            var H3h = H3.high;
            var H3l = H3.low;
            var H4h = H4.high;
            var H4l = H4.low;
            var H5h = H5.high;
            var H5l = H5.low;
            var H6h = H6.high;
            var H6l = H6.low;
            var H7h = H7.high;
            var H7l = H7.low;
            var ah = H0h;
            var al = H0l;
            var bh = H1h;
            var bl = H1l;
            var ch = H2h;
            var cl = H2l;
            var dh = H3h;
            var dl = H3l;
            var eh = H4h;
            var el = H4l;
            var fh = H5h;
            var fl = H5l;
            var gh = H6h;
            var gl = H6l;
            var hh = H7h;
            var hl = H7l;
            for (var i3 = 0; i3 < 80; i3++) {
              var Wil;
              var Wih;
              var Wi = W[i3];
              if (i3 < 16) {
                Wih = Wi.high = M[offset5 + i3 * 2] | 0;
                Wil = Wi.low = M[offset5 + i3 * 2 + 1] | 0;
              } else {
                var gamma0x = W[i3 - 15];
                var gamma0xh = gamma0x.high;
                var gamma0xl = gamma0x.low;
                var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7;
                var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25);
                var gamma1x = W[i3 - 2];
                var gamma1xh = gamma1x.high;
                var gamma1xl = gamma1x.low;
                var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6;
                var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26);
                var Wi7 = W[i3 - 7];
                var Wi7h = Wi7.high;
                var Wi7l = Wi7.low;
                var Wi16 = W[i3 - 16];
                var Wi16h = Wi16.high;
                var Wi16l = Wi16.low;
                Wil = gamma0l + Wi7l;
                Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0);
                Wil = Wil + gamma1l;
                Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0);
                Wil = Wil + Wi16l;
                Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0);
                Wi.high = Wih;
                Wi.low = Wil;
              }
              var chh = eh & fh ^ ~eh & gh;
              var chl = el & fl ^ ~el & gl;
              var majh = ah & bh ^ ah & ch ^ bh & ch;
              var majl = al & bl ^ al & cl ^ bl & cl;
              var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7);
              var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7);
              var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9);
              var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9);
              var Ki = K2[i3];
              var Kih = Ki.high;
              var Kil = Ki.low;
              var t1l = hl + sigma1l;
              var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0);
              var t1l = t1l + chl;
              var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0);
              var t1l = t1l + Kil;
              var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0);
              var t1l = t1l + Wil;
              var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0);
              var t2l = sigma0l + majl;
              var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0);
              hh = gh;
              hl = gl;
              gh = fh;
              gl = fl;
              fh = eh;
              fl = el;
              el = dl + t1l | 0;
              eh = dh + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0;
              dh = ch;
              dl = cl;
              ch = bh;
              cl = bl;
              bh = ah;
              bl = al;
              al = t1l + t2l | 0;
              ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0;
            }
            H0l = H0.low = H0l + al;
            H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0);
            H1l = H1.low = H1l + bl;
            H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0);
            H2l = H22.low = H2l + cl;
            H22.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0);
            H3l = H3.low = H3l + dl;
            H3.high = H3h + dh + (H3l >>> 0 < dl >>> 0 ? 1 : 0);
            H4l = H4.low = H4l + el;
            H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0);
            H5l = H5.low = H5l + fl;
            H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0);
            H6l = H6.low = H6l + gl;
            H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0);
            H7l = H7.low = H7l + hl;
            H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0);
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal;
            data.sigBytes = dataWords.length * 4;
            this._process();
            var hash = this._hash.toX32();
            return hash;
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            clone3._hash = this._hash.clone();
            return clone3;
          },
          blockSize: 1024 / 32
        });
        C3.SHA512 = Hasher._createHelper(SHA512);
        C3.HmacSHA512 = Hasher._createHmacHelper(SHA512);
      })();
      return CryptoJS.SHA512;
    });
  }
});

// node_modules/crypto-js/sha384.js
var require_sha384 = __commonJS({
  "node_modules/crypto-js/sha384.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_x64_core(), require_sha512());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./x64-core", "./sha512"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_x64 = C3.x64;
        var X64Word = C_x64.Word;
        var X64WordArray = C_x64.WordArray;
        var C_algo = C3.algo;
        var SHA512 = C_algo.SHA512;
        var SHA384 = C_algo.SHA384 = SHA512.extend({
          _doReset: function() {
            this._hash = new X64WordArray.init([
              new X64Word.init(3418070365, 3238371032),
              new X64Word.init(1654270250, 914150663),
              new X64Word.init(2438529370, 812702999),
              new X64Word.init(355462360, 4144912697),
              new X64Word.init(1731405415, 4290775857),
              new X64Word.init(2394180231, 1750603025),
              new X64Word.init(3675008525, 1694076839),
              new X64Word.init(1203062813, 3204075428)
            ]);
          },
          _doFinalize: function() {
            var hash = SHA512._doFinalize.call(this);
            hash.sigBytes -= 16;
            return hash;
          }
        });
        C3.SHA384 = SHA512._createHelper(SHA384);
        C3.HmacSHA384 = SHA512._createHmacHelper(SHA384);
      })();
      return CryptoJS.SHA384;
    });
  }
});

// node_modules/crypto-js/sha3.js
var require_sha3 = __commonJS({
  "node_modules/crypto-js/sha3.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_x64_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./x64-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(Math2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_x64 = C3.x64;
        var X64Word = C_x64.Word;
        var C_algo = C3.algo;
        var RHO_OFFSETS = [];
        var PI_INDEXES = [];
        var ROUND_CONSTANTS = [];
        (function() {
          var x2 = 1, y2 = 0;
          for (var t3 = 0; t3 < 24; t3++) {
            RHO_OFFSETS[x2 + 5 * y2] = (t3 + 1) * (t3 + 2) / 2 % 64;
            var newX = y2 % 5;
            var newY = (2 * x2 + 3 * y2) % 5;
            x2 = newX;
            y2 = newY;
          }
          for (var x2 = 0; x2 < 5; x2++) {
            for (var y2 = 0; y2 < 5; y2++) {
              PI_INDEXES[x2 + 5 * y2] = y2 + (2 * x2 + 3 * y2) % 5 * 5;
            }
          }
          var LFSR = 1;
          for (var i3 = 0; i3 < 24; i3++) {
            var roundConstantMsw = 0;
            var roundConstantLsw = 0;
            for (var j3 = 0; j3 < 7; j3++) {
              if (LFSR & 1) {
                var bitPosition = (1 << j3) - 1;
                if (bitPosition < 32) {
                  roundConstantLsw ^= 1 << bitPosition;
                } else {
                  roundConstantMsw ^= 1 << bitPosition - 32;
                }
              }
              if (LFSR & 128) {
                LFSR = LFSR << 1 ^ 113;
              } else {
                LFSR <<= 1;
              }
            }
            ROUND_CONSTANTS[i3] = X64Word.create(roundConstantMsw, roundConstantLsw);
          }
        })();
        var T = [];
        (function() {
          for (var i3 = 0; i3 < 25; i3++) {
            T[i3] = X64Word.create();
          }
        })();
        var SHA3 = C_algo.SHA3 = Hasher.extend({
          /**
           * Configuration options.
           *
           * @property {number} outputLength
           *   The desired number of bits in the output hash.
           *   Only values permitted are: 224, 256, 384, 512.
           *   Default: 512
           */
          cfg: Hasher.cfg.extend({
            outputLength: 512
          }),
          _doReset: function() {
            var state = this._state = [];
            for (var i3 = 0; i3 < 25; i3++) {
              state[i3] = new X64Word.init();
            }
            this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
          },
          _doProcessBlock: function(M, offset5) {
            var state = this._state;
            var nBlockSizeLanes = this.blockSize / 2;
            for (var i3 = 0; i3 < nBlockSizeLanes; i3++) {
              var M2i = M[offset5 + 2 * i3];
              var M2i1 = M[offset5 + 2 * i3 + 1];
              M2i = (M2i << 8 | M2i >>> 24) & 16711935 | (M2i << 24 | M2i >>> 8) & 4278255360;
              M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 16711935 | (M2i1 << 24 | M2i1 >>> 8) & 4278255360;
              var lane = state[i3];
              lane.high ^= M2i1;
              lane.low ^= M2i;
            }
            for (var round2 = 0; round2 < 24; round2++) {
              for (var x2 = 0; x2 < 5; x2++) {
                var tMsw = 0, tLsw = 0;
                for (var y2 = 0; y2 < 5; y2++) {
                  var lane = state[x2 + 5 * y2];
                  tMsw ^= lane.high;
                  tLsw ^= lane.low;
                }
                var Tx = T[x2];
                Tx.high = tMsw;
                Tx.low = tLsw;
              }
              for (var x2 = 0; x2 < 5; x2++) {
                var Tx4 = T[(x2 + 4) % 5];
                var Tx1 = T[(x2 + 1) % 5];
                var Tx1Msw = Tx1.high;
                var Tx1Lsw = Tx1.low;
                var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31);
                var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31);
                for (var y2 = 0; y2 < 5; y2++) {
                  var lane = state[x2 + 5 * y2];
                  lane.high ^= tMsw;
                  lane.low ^= tLsw;
                }
              }
              for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
                var tMsw;
                var tLsw;
                var lane = state[laneIndex];
                var laneMsw = lane.high;
                var laneLsw = lane.low;
                var rhoOffset = RHO_OFFSETS[laneIndex];
                if (rhoOffset < 32) {
                  tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset;
                  tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset;
                } else {
                  tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset;
                  tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset;
                }
                var TPiLane = T[PI_INDEXES[laneIndex]];
                TPiLane.high = tMsw;
                TPiLane.low = tLsw;
              }
              var T0 = T[0];
              var state0 = state[0];
              T0.high = state0.high;
              T0.low = state0.low;
              for (var x2 = 0; x2 < 5; x2++) {
                for (var y2 = 0; y2 < 5; y2++) {
                  var laneIndex = x2 + 5 * y2;
                  var lane = state[laneIndex];
                  var TLane = T[laneIndex];
                  var Tx1Lane = T[(x2 + 1) % 5 + 5 * y2];
                  var Tx2Lane = T[(x2 + 2) % 5 + 5 * y2];
                  lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
                  lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
                }
              }
              var lane = state[0];
              var roundConstant = ROUND_CONSTANTS[round2];
              lane.high ^= roundConstant.high;
              lane.low ^= roundConstant.low;
            }
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            var blockSizeBits = this.blockSize * 32;
            dataWords[nBitsLeft >>> 5] |= 1 << 24 - nBitsLeft % 32;
            dataWords[(Math2.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 128;
            data.sigBytes = dataWords.length * 4;
            this._process();
            var state = this._state;
            var outputLengthBytes = this.cfg.outputLength / 8;
            var outputLengthLanes = outputLengthBytes / 8;
            var hashWords = [];
            for (var i3 = 0; i3 < outputLengthLanes; i3++) {
              var lane = state[i3];
              var laneMsw = lane.high;
              var laneLsw = lane.low;
              laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 16711935 | (laneMsw << 24 | laneMsw >>> 8) & 4278255360;
              laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 16711935 | (laneLsw << 24 | laneLsw >>> 8) & 4278255360;
              hashWords.push(laneLsw);
              hashWords.push(laneMsw);
            }
            return new WordArray.init(hashWords, outputLengthBytes);
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            var state = clone3._state = this._state.slice(0);
            for (var i3 = 0; i3 < 25; i3++) {
              state[i3] = state[i3].clone();
            }
            return clone3;
          }
        });
        C3.SHA3 = Hasher._createHelper(SHA3);
        C3.HmacSHA3 = Hasher._createHmacHelper(SHA3);
      })(Math);
      return CryptoJS.SHA3;
    });
  }
});

// node_modules/crypto-js/ripemd160.js
var require_ripemd160 = __commonJS({
  "node_modules/crypto-js/ripemd160.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(Math2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C3.algo;
        var _zl = WordArray.create([
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11,
          12,
          13,
          14,
          15,
          7,
          4,
          13,
          1,
          10,
          6,
          15,
          3,
          12,
          0,
          9,
          5,
          2,
          14,
          11,
          8,
          3,
          10,
          14,
          4,
          9,
          15,
          8,
          1,
          2,
          7,
          0,
          6,
          13,
          11,
          5,
          12,
          1,
          9,
          11,
          10,
          0,
          8,
          12,
          4,
          13,
          3,
          7,
          15,
          14,
          5,
          6,
          2,
          4,
          0,
          5,
          9,
          7,
          12,
          2,
          10,
          14,
          1,
          3,
          8,
          11,
          6,
          15,
          13
        ]);
        var _zr = WordArray.create([
          5,
          14,
          7,
          0,
          9,
          2,
          11,
          4,
          13,
          6,
          15,
          8,
          1,
          10,
          3,
          12,
          6,
          11,
          3,
          7,
          0,
          13,
          5,
          10,
          14,
          15,
          8,
          12,
          4,
          9,
          1,
          2,
          15,
          5,
          1,
          3,
          7,
          14,
          6,
          9,
          11,
          8,
          12,
          2,
          10,
          0,
          4,
          13,
          8,
          6,
          4,
          1,
          3,
          11,
          15,
          0,
          5,
          12,
          2,
          13,
          9,
          7,
          10,
          14,
          12,
          15,
          10,
          4,
          1,
          5,
          8,
          7,
          6,
          2,
          13,
          14,
          0,
          3,
          9,
          11
        ]);
        var _sl = WordArray.create([
          11,
          14,
          15,
          12,
          5,
          8,
          7,
          9,
          11,
          13,
          14,
          15,
          6,
          7,
          9,
          8,
          7,
          6,
          8,
          13,
          11,
          9,
          7,
          15,
          7,
          12,
          15,
          9,
          11,
          7,
          13,
          12,
          11,
          13,
          6,
          7,
          14,
          9,
          13,
          15,
          14,
          8,
          13,
          6,
          5,
          12,
          7,
          5,
          11,
          12,
          14,
          15,
          14,
          15,
          9,
          8,
          9,
          14,
          5,
          6,
          8,
          6,
          5,
          12,
          9,
          15,
          5,
          11,
          6,
          8,
          13,
          12,
          5,
          12,
          13,
          14,
          11,
          8,
          5,
          6
        ]);
        var _sr = WordArray.create([
          8,
          9,
          9,
          11,
          13,
          15,
          15,
          5,
          7,
          7,
          8,
          11,
          14,
          14,
          12,
          6,
          9,
          13,
          15,
          7,
          12,
          8,
          9,
          11,
          7,
          7,
          12,
          7,
          6,
          15,
          13,
          11,
          9,
          7,
          15,
          11,
          8,
          6,
          6,
          14,
          12,
          13,
          5,
          14,
          13,
          13,
          7,
          5,
          15,
          5,
          8,
          11,
          14,
          14,
          6,
          14,
          6,
          9,
          12,
          9,
          12,
          5,
          15,
          8,
          8,
          5,
          12,
          9,
          12,
          5,
          14,
          6,
          8,
          13,
          6,
          5,
          15,
          13,
          11,
          11
        ]);
        var _hl = WordArray.create([0, 1518500249, 1859775393, 2400959708, 2840853838]);
        var _hr = WordArray.create([1352829926, 1548603684, 1836072691, 2053994217, 0]);
        var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
          _doReset: function() {
            this._hash = WordArray.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
          },
          _doProcessBlock: function(M, offset5) {
            for (var i3 = 0; i3 < 16; i3++) {
              var offset_i = offset5 + i3;
              var M_offset_i = M[offset_i];
              M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
            }
            var H2 = this._hash.words;
            var hl = _hl.words;
            var hr = _hr.words;
            var zl = _zl.words;
            var zr = _zr.words;
            var sl = _sl.words;
            var sr = _sr.words;
            var al, bl, cl, dl, el;
            var ar, br, cr, dr, er;
            ar = al = H2[0];
            br = bl = H2[1];
            cr = cl = H2[2];
            dr = dl = H2[3];
            er = el = H2[4];
            var t3;
            for (var i3 = 0; i3 < 80; i3 += 1) {
              t3 = al + M[offset5 + zl[i3]] | 0;
              if (i3 < 16) {
                t3 += f1(bl, cl, dl) + hl[0];
              } else if (i3 < 32) {
                t3 += f22(bl, cl, dl) + hl[1];
              } else if (i3 < 48) {
                t3 += f3(bl, cl, dl) + hl[2];
              } else if (i3 < 64) {
                t3 += f4(bl, cl, dl) + hl[3];
              } else {
                t3 += f5(bl, cl, dl) + hl[4];
              }
              t3 = t3 | 0;
              t3 = rotl(t3, sl[i3]);
              t3 = t3 + el | 0;
              al = el;
              el = dl;
              dl = rotl(cl, 10);
              cl = bl;
              bl = t3;
              t3 = ar + M[offset5 + zr[i3]] | 0;
              if (i3 < 16) {
                t3 += f5(br, cr, dr) + hr[0];
              } else if (i3 < 32) {
                t3 += f4(br, cr, dr) + hr[1];
              } else if (i3 < 48) {
                t3 += f3(br, cr, dr) + hr[2];
              } else if (i3 < 64) {
                t3 += f22(br, cr, dr) + hr[3];
              } else {
                t3 += f1(br, cr, dr) + hr[4];
              }
              t3 = t3 | 0;
              t3 = rotl(t3, sr[i3]);
              t3 = t3 + er | 0;
              ar = er;
              er = dr;
              dr = rotl(cr, 10);
              cr = br;
              br = t3;
            }
            t3 = H2[1] + cl + dr | 0;
            H2[1] = H2[2] + dl + er | 0;
            H2[2] = H2[3] + el + ar | 0;
            H2[3] = H2[4] + al + br | 0;
            H2[4] = H2[0] + bl + cr | 0;
            H2[0] = t3;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 16711935 | (nBitsTotal << 24 | nBitsTotal >>> 8) & 4278255360;
            data.sigBytes = (dataWords.length + 1) * 4;
            this._process();
            var hash = this._hash;
            var H2 = hash.words;
            for (var i3 = 0; i3 < 5; i3++) {
              var H_i = H2[i3];
              H2[i3] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
            }
            return hash;
          },
          clone: function() {
            var clone3 = Hasher.clone.call(this);
            clone3._hash = this._hash.clone();
            return clone3;
          }
        });
        function f1(x2, y2, z3) {
          return x2 ^ y2 ^ z3;
        }
        function f22(x2, y2, z3) {
          return x2 & y2 | ~x2 & z3;
        }
        function f3(x2, y2, z3) {
          return (x2 | ~y2) ^ z3;
        }
        function f4(x2, y2, z3) {
          return x2 & z3 | y2 & ~z3;
        }
        function f5(x2, y2, z3) {
          return x2 ^ (y2 | ~z3);
        }
        function rotl(x2, n4) {
          return x2 << n4 | x2 >>> 32 - n4;
        }
        C3.RIPEMD160 = Hasher._createHelper(RIPEMD160);
        C3.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
      })(Math);
      return CryptoJS.RIPEMD160;
    });
  }
});

// node_modules/crypto-js/hmac.js
var require_hmac = __commonJS({
  "node_modules/crypto-js/hmac.js"(exports, module2) {
    (function(root2, factory) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2());
      } else if (typeof define === "function" && define.amd) {
        define(["./core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Base = C_lib.Base;
        var C_enc = C3.enc;
        var Utf8 = C_enc.Utf8;
        var C_algo = C3.algo;
        var HMAC = C_algo.HMAC = Base.extend({
          /**
           * Initializes a newly created HMAC.
           *
           * @param {Hasher} hasher The hash algorithm to use.
           * @param {WordArray|string} key The secret key.
           *
           * @example
           *
           *     var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
           */
          init: function(hasher, key) {
            hasher = this._hasher = new hasher.init();
            if (typeof key == "string") {
              key = Utf8.parse(key);
            }
            var hasherBlockSize = hasher.blockSize;
            var hasherBlockSizeBytes = hasherBlockSize * 4;
            if (key.sigBytes > hasherBlockSizeBytes) {
              key = hasher.finalize(key);
            }
            key.clamp();
            var oKey = this._oKey = key.clone();
            var iKey = this._iKey = key.clone();
            var oKeyWords = oKey.words;
            var iKeyWords = iKey.words;
            for (var i3 = 0; i3 < hasherBlockSize; i3++) {
              oKeyWords[i3] ^= 1549556828;
              iKeyWords[i3] ^= 909522486;
            }
            oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
            this.reset();
          },
          /**
           * Resets this HMAC to its initial state.
           *
           * @example
           *
           *     hmacHasher.reset();
           */
          reset: function() {
            var hasher = this._hasher;
            hasher.reset();
            hasher.update(this._iKey);
          },
          /**
           * Updates this HMAC with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {HMAC} This HMAC instance.
           *
           * @example
           *
           *     hmacHasher.update('message');
           *     hmacHasher.update(wordArray);
           */
          update: function(messageUpdate) {
            this._hasher.update(messageUpdate);
            return this;
          },
          /**
           * Finalizes the HMAC computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The HMAC.
           *
           * @example
           *
           *     var hmac = hmacHasher.finalize();
           *     var hmac = hmacHasher.finalize('message');
           *     var hmac = hmacHasher.finalize(wordArray);
           */
          finalize: function(messageUpdate) {
            var hasher = this._hasher;
            var innerHash = hasher.finalize(messageUpdate);
            hasher.reset();
            var hmac2 = hasher.finalize(this._oKey.clone().concat(innerHash));
            return hmac2;
          }
        });
      })();
    });
  }
});

// node_modules/crypto-js/pbkdf2.js
var require_pbkdf2 = __commonJS({
  "node_modules/crypto-js/pbkdf2.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_sha256(), require_hmac());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./sha256", "./hmac"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var C_algo = C3.algo;
        var SHA256 = C_algo.SHA256;
        var HMAC = C_algo.HMAC;
        var PBKDF2 = C_algo.PBKDF2 = Base.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hasher to use. Default: SHA256
           * @property {number} iterations The number of iterations to perform. Default: 250000
           */
          cfg: Base.extend({
            keySize: 128 / 32,
            hasher: SHA256,
            iterations: 25e4
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.PBKDF2.create();
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
          },
          /**
           * Computes the Password-Based Key Derivation Function 2.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(password, salt) {
            var cfg = this.cfg;
            var hmac2 = HMAC.create(cfg.hasher, password);
            var derivedKey = WordArray.create();
            var blockIndex = WordArray.create([1]);
            var derivedKeyWords = derivedKey.words;
            var blockIndexWords = blockIndex.words;
            var keySize = cfg.keySize;
            var iterations = cfg.iterations;
            while (derivedKeyWords.length < keySize) {
              var block = hmac2.update(salt).finalize(blockIndex);
              hmac2.reset();
              var blockWords = block.words;
              var blockWordsLength = blockWords.length;
              var intermediate = block;
              for (var i3 = 1; i3 < iterations; i3++) {
                intermediate = hmac2.finalize(intermediate);
                hmac2.reset();
                var intermediateWords = intermediate.words;
                for (var j3 = 0; j3 < blockWordsLength; j3++) {
                  blockWords[j3] ^= intermediateWords[j3];
                }
              }
              derivedKey.concat(block);
              blockIndexWords[0]++;
            }
            derivedKey.sigBytes = keySize * 4;
            return derivedKey;
          }
        });
        C3.PBKDF2 = function(password, salt, cfg) {
          return PBKDF2.create(cfg).compute(password, salt);
        };
      })();
      return CryptoJS.PBKDF2;
    });
  }
});

// node_modules/crypto-js/evpkdf.js
var require_evpkdf = __commonJS({
  "node_modules/crypto-js/evpkdf.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_sha1(), require_hmac());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./sha1", "./hmac"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var C_algo = C3.algo;
        var MD54 = C_algo.MD5;
        var EvpKDF = C_algo.EvpKDF = Base.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hash algorithm to use. Default: MD5
           * @property {number} iterations The number of iterations to perform. Default: 1
           */
          cfg: Base.extend({
            keySize: 128 / 32,
            hasher: MD54,
            iterations: 1
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.EvpKDF.create();
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
          },
          /**
           * Derives a key from a password.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(password, salt) {
            var block;
            var cfg = this.cfg;
            var hasher = cfg.hasher.create();
            var derivedKey = WordArray.create();
            var derivedKeyWords = derivedKey.words;
            var keySize = cfg.keySize;
            var iterations = cfg.iterations;
            while (derivedKeyWords.length < keySize) {
              if (block) {
                hasher.update(block);
              }
              block = hasher.update(password).finalize(salt);
              hasher.reset();
              for (var i3 = 1; i3 < iterations; i3++) {
                block = hasher.finalize(block);
                hasher.reset();
              }
              derivedKey.concat(block);
            }
            derivedKey.sigBytes = keySize * 4;
            return derivedKey;
          }
        });
        C3.EvpKDF = function(password, salt, cfg) {
          return EvpKDF.create(cfg).compute(password, salt);
        };
      })();
      return CryptoJS.EvpKDF;
    });
  }
});

// node_modules/crypto-js/cipher-core.js
var require_cipher_core = __commonJS({
  "node_modules/crypto-js/cipher-core.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_evpkdf());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./evpkdf"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.lib.Cipher || function(undefined2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
        var C_enc = C3.enc;
        var Utf8 = C_enc.Utf8;
        var Base642 = C_enc.Base64;
        var C_algo = C3.algo;
        var EvpKDF = C_algo.EvpKDF;
        var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           *
           * @property {WordArray} iv The IV to use for this operation.
           */
          cfg: Base.extend(),
          /**
           * Creates this cipher in encryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
           */
          createEncryptor: function(key, cfg) {
            return this.create(this._ENC_XFORM_MODE, key, cfg);
          },
          /**
           * Creates this cipher in decryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
           */
          createDecryptor: function(key, cfg) {
            return this.create(this._DEC_XFORM_MODE, key, cfg);
          },
          /**
           * Initializes a newly created cipher.
           *
           * @param {number} xformMode Either the encryption or decryption transormation mode constant.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
           */
          init: function(xformMode, key, cfg) {
            this.cfg = this.cfg.extend(cfg);
            this._xformMode = xformMode;
            this._key = key;
            this.reset();
          },
          /**
           * Resets this cipher to its initial state.
           *
           * @example
           *
           *     cipher.reset();
           */
          reset: function() {
            BufferedBlockAlgorithm.reset.call(this);
            this._doReset();
          },
          /**
           * Adds data to be encrypted or decrypted.
           *
           * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
           *
           * @return {WordArray} The data after processing.
           *
           * @example
           *
           *     var encrypted = cipher.process('data');
           *     var encrypted = cipher.process(wordArray);
           */
          process: function(dataUpdate) {
            this._append(dataUpdate);
            return this._process();
          },
          /**
           * Finalizes the encryption or decryption process.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
           *
           * @return {WordArray} The data after final processing.
           *
           * @example
           *
           *     var encrypted = cipher.finalize();
           *     var encrypted = cipher.finalize('data');
           *     var encrypted = cipher.finalize(wordArray);
           */
          finalize: function(dataUpdate) {
            if (dataUpdate) {
              this._append(dataUpdate);
            }
            var finalProcessedData = this._doFinalize();
            return finalProcessedData;
          },
          keySize: 128 / 32,
          ivSize: 128 / 32,
          _ENC_XFORM_MODE: 1,
          _DEC_XFORM_MODE: 2,
          /**
           * Creates shortcut functions to a cipher's object interface.
           *
           * @param {Cipher} cipher The cipher to create a helper for.
           *
           * @return {Object} An object with encrypt and decrypt shortcut functions.
           *
           * @static
           *
           * @example
           *
           *     var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
           */
          _createHelper: function() {
            function selectCipherStrategy(key) {
              if (typeof key == "string") {
                return PasswordBasedCipher;
              } else {
                return SerializableCipher;
              }
            }
            return function(cipher) {
              return {
                encrypt: function(message, key, cfg) {
                  return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
                },
                decrypt: function(ciphertext, key, cfg) {
                  return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
                }
              };
            };
          }()
        });
        var StreamCipher = C_lib.StreamCipher = Cipher.extend({
          _doFinalize: function() {
            var finalProcessedBlocks = this._process(true);
            return finalProcessedBlocks;
          },
          blockSize: 1
        });
        var C_mode = C3.mode = {};
        var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
          /**
           * Creates this mode for encryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
           */
          createEncryptor: function(cipher, iv) {
            return this.Encryptor.create(cipher, iv);
          },
          /**
           * Creates this mode for decryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
           */
          createDecryptor: function(cipher, iv) {
            return this.Decryptor.create(cipher, iv);
          },
          /**
           * Initializes a newly created mode.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
           */
          init: function(cipher, iv) {
            this._cipher = cipher;
            this._iv = iv;
          }
        });
        var CBC = C_mode.CBC = function() {
          var CBC2 = BlockCipherMode.extend();
          CBC2.Encryptor = CBC2.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(words, offset5) {
              var cipher = this._cipher;
              var blockSize = cipher.blockSize;
              xorBlock.call(this, words, offset5, blockSize);
              cipher.encryptBlock(words, offset5);
              this._prevBlock = words.slice(offset5, offset5 + blockSize);
            }
          });
          CBC2.Decryptor = CBC2.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(words, offset5) {
              var cipher = this._cipher;
              var blockSize = cipher.blockSize;
              var thisBlock = words.slice(offset5, offset5 + blockSize);
              cipher.decryptBlock(words, offset5);
              xorBlock.call(this, words, offset5, blockSize);
              this._prevBlock = thisBlock;
            }
          });
          function xorBlock(words, offset5, blockSize) {
            var block;
            var iv = this._iv;
            if (iv) {
              block = iv;
              this._iv = undefined2;
            } else {
              block = this._prevBlock;
            }
            for (var i3 = 0; i3 < blockSize; i3++) {
              words[offset5 + i3] ^= block[i3];
            }
          }
          return CBC2;
        }();
        var C_pad = C3.pad = {};
        var Pkcs7 = C_pad.Pkcs7 = {
          /**
           * Pads data using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to pad.
           * @param {number} blockSize The multiple that the data should be padded to.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.pad(wordArray, 4);
           */
          pad: function(data, blockSize) {
            var blockSizeBytes = blockSize * 4;
            var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
            var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes;
            var paddingWords = [];
            for (var i3 = 0; i3 < nPaddingBytes; i3 += 4) {
              paddingWords.push(paddingWord);
            }
            var padding = WordArray.create(paddingWords, nPaddingBytes);
            data.concat(padding);
          },
          /**
           * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to unpad.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.unpad(wordArray);
           */
          unpad: function(data) {
            var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
            data.sigBytes -= nPaddingBytes;
          }
        };
        var BlockCipher = C_lib.BlockCipher = Cipher.extend({
          /**
           * Configuration options.
           *
           * @property {Mode} mode The block mode to use. Default: CBC
           * @property {Padding} padding The padding strategy to use. Default: Pkcs7
           */
          cfg: Cipher.cfg.extend({
            mode: CBC,
            padding: Pkcs7
          }),
          reset: function() {
            var modeCreator;
            Cipher.reset.call(this);
            var cfg = this.cfg;
            var iv = cfg.iv;
            var mode = cfg.mode;
            if (this._xformMode == this._ENC_XFORM_MODE) {
              modeCreator = mode.createEncryptor;
            } else {
              modeCreator = mode.createDecryptor;
              this._minBufferSize = 1;
            }
            if (this._mode && this._mode.__creator == modeCreator) {
              this._mode.init(this, iv && iv.words);
            } else {
              this._mode = modeCreator.call(mode, this, iv && iv.words);
              this._mode.__creator = modeCreator;
            }
          },
          _doProcessBlock: function(words, offset5) {
            this._mode.processBlock(words, offset5);
          },
          _doFinalize: function() {
            var finalProcessedBlocks;
            var padding = this.cfg.padding;
            if (this._xformMode == this._ENC_XFORM_MODE) {
              padding.pad(this._data, this.blockSize);
              finalProcessedBlocks = this._process(true);
            } else {
              finalProcessedBlocks = this._process(true);
              padding.unpad(finalProcessedBlocks);
            }
            return finalProcessedBlocks;
          },
          blockSize: 128 / 32
        });
        var CipherParams = C_lib.CipherParams = Base.extend({
          /**
           * Initializes a newly created cipher params object.
           *
           * @param {Object} cipherParams An object with any of the possible cipher parameters.
           *
           * @example
           *
           *     var cipherParams = CryptoJS.lib.CipherParams.create({
           *         ciphertext: ciphertextWordArray,
           *         key: keyWordArray,
           *         iv: ivWordArray,
           *         salt: saltWordArray,
           *         algorithm: CryptoJS.algo.AES,
           *         mode: CryptoJS.mode.CBC,
           *         padding: CryptoJS.pad.PKCS7,
           *         blockSize: 4,
           *         formatter: CryptoJS.format.OpenSSL
           *     });
           */
          init: function(cipherParams) {
            this.mixIn(cipherParams);
          },
          /**
           * Converts this cipher params object to a string.
           *
           * @param {Format} formatter (Optional) The formatting strategy to use.
           *
           * @return {string} The stringified cipher params.
           *
           * @throws Error If neither the formatter nor the default formatter is set.
           *
           * @example
           *
           *     var string = cipherParams + '';
           *     var string = cipherParams.toString();
           *     var string = cipherParams.toString(CryptoJS.format.OpenSSL);
           */
          toString: function(formatter) {
            return (formatter || this.formatter).stringify(this);
          }
        });
        var C_format = C3.format = {};
        var OpenSSLFormatter = C_format.OpenSSL = {
          /**
           * Converts a cipher params object to an OpenSSL-compatible string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The OpenSSL-compatible string.
           *
           * @static
           *
           * @example
           *
           *     var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
           */
          stringify: function(cipherParams) {
            var wordArray;
            var ciphertext = cipherParams.ciphertext;
            var salt = cipherParams.salt;
            if (salt) {
              wordArray = WordArray.create([1398893684, 1701076831]).concat(salt).concat(ciphertext);
            } else {
              wordArray = ciphertext;
            }
            return wordArray.toString(Base642);
          },
          /**
           * Converts an OpenSSL-compatible string to a cipher params object.
           *
           * @param {string} openSSLStr The OpenSSL-compatible string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
           */
          parse: function(openSSLStr) {
            var salt;
            var ciphertext = Base642.parse(openSSLStr);
            var ciphertextWords = ciphertext.words;
            if (ciphertextWords[0] == 1398893684 && ciphertextWords[1] == 1701076831) {
              salt = WordArray.create(ciphertextWords.slice(2, 4));
              ciphertextWords.splice(0, 4);
              ciphertext.sigBytes -= 16;
            }
            return CipherParams.create({ ciphertext, salt });
          }
        };
        var SerializableCipher = C_lib.SerializableCipher = Base.extend({
          /**
           * Configuration options.
           *
           * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
           */
          cfg: Base.extend({
            format: OpenSSLFormatter
          }),
          /**
           * Encrypts a message.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(cipher, message, key, cfg) {
            cfg = this.cfg.extend(cfg);
            var encryptor = cipher.createEncryptor(key, cfg);
            var ciphertext = encryptor.finalize(message);
            var cipherCfg = encryptor.cfg;
            return CipherParams.create({
              ciphertext,
              key,
              iv: cipherCfg.iv,
              algorithm: cipher,
              mode: cipherCfg.mode,
              padding: cipherCfg.padding,
              blockSize: cipher.blockSize,
              formatter: cfg.format
            });
          },
          /**
           * Decrypts serialized ciphertext.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(cipher, ciphertext, key, cfg) {
            cfg = this.cfg.extend(cfg);
            ciphertext = this._parse(ciphertext, cfg.format);
            var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
            return plaintext;
          },
          /**
           * Converts serialized ciphertext to CipherParams,
           * else assumed CipherParams already and returns ciphertext unchanged.
           *
           * @param {CipherParams|string} ciphertext The ciphertext.
           * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
           *
           * @return {CipherParams} The unserialized ciphertext.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
           */
          _parse: function(ciphertext, format) {
            if (typeof ciphertext == "string") {
              return format.parse(ciphertext, this);
            } else {
              return ciphertext;
            }
          }
        });
        var C_kdf = C3.kdf = {};
        var OpenSSLKdf = C_kdf.OpenSSL = {
          /**
           * Derives a key and IV from a password.
           *
           * @param {string} password The password to derive from.
           * @param {number} keySize The size in words of the key to generate.
           * @param {number} ivSize The size in words of the IV to generate.
           * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
           *
           * @return {CipherParams} A cipher params object with the key, IV, and salt.
           *
           * @static
           *
           * @example
           *
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
           */
          execute: function(password, keySize, ivSize, salt, hasher) {
            if (!salt) {
              salt = WordArray.random(64 / 8);
            }
            if (!hasher) {
              var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
            } else {
              var key = EvpKDF.create({ keySize: keySize + ivSize, hasher }).compute(password, salt);
            }
            var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
            key.sigBytes = keySize * 4;
            return CipherParams.create({ key, iv, salt });
          }
        };
        var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
          /**
           * Configuration options.
           *
           * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
           */
          cfg: SerializableCipher.cfg.extend({
            kdf: OpenSSLKdf
          }),
          /**
           * Encrypts a message using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(cipher, message, password, cfg) {
            cfg = this.cfg.extend(cfg);
            var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, cfg.salt, cfg.hasher);
            cfg.iv = derivedParams.iv;
            var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
            ciphertext.mixIn(derivedParams);
            return ciphertext;
          },
          /**
           * Decrypts serialized ciphertext using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(cipher, ciphertext, password, cfg) {
            cfg = this.cfg.extend(cfg);
            ciphertext = this._parse(ciphertext, cfg.format);
            var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt, cfg.hasher);
            cfg.iv = derivedParams.iv;
            var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
            return plaintext;
          }
        });
      }();
    });
  }
});

// node_modules/crypto-js/mode-cfb.js
var require_mode_cfb = __commonJS({
  "node_modules/crypto-js/mode-cfb.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.mode.CFB = function() {
        var CFB = CryptoJS.lib.BlockCipherMode.extend();
        CFB.Encryptor = CFB.extend({
          processBlock: function(words, offset5) {
            var cipher = this._cipher;
            var blockSize = cipher.blockSize;
            generateKeystreamAndEncrypt.call(this, words, offset5, blockSize, cipher);
            this._prevBlock = words.slice(offset5, offset5 + blockSize);
          }
        });
        CFB.Decryptor = CFB.extend({
          processBlock: function(words, offset5) {
            var cipher = this._cipher;
            var blockSize = cipher.blockSize;
            var thisBlock = words.slice(offset5, offset5 + blockSize);
            generateKeystreamAndEncrypt.call(this, words, offset5, blockSize, cipher);
            this._prevBlock = thisBlock;
          }
        });
        function generateKeystreamAndEncrypt(words, offset5, blockSize, cipher) {
          var keystream;
          var iv = this._iv;
          if (iv) {
            keystream = iv.slice(0);
            this._iv = void 0;
          } else {
            keystream = this._prevBlock;
          }
          cipher.encryptBlock(keystream, 0);
          for (var i3 = 0; i3 < blockSize; i3++) {
            words[offset5 + i3] ^= keystream[i3];
          }
        }
        return CFB;
      }();
      return CryptoJS.mode.CFB;
    });
  }
});

// node_modules/crypto-js/mode-ctr.js
var require_mode_ctr = __commonJS({
  "node_modules/crypto-js/mode-ctr.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.mode.CTR = function() {
        var CTR = CryptoJS.lib.BlockCipherMode.extend();
        var Encryptor = CTR.Encryptor = CTR.extend({
          processBlock: function(words, offset5) {
            var cipher = this._cipher;
            var blockSize = cipher.blockSize;
            var iv = this._iv;
            var counter = this._counter;
            if (iv) {
              counter = this._counter = iv.slice(0);
              this._iv = void 0;
            }
            var keystream = counter.slice(0);
            cipher.encryptBlock(keystream, 0);
            counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0;
            for (var i3 = 0; i3 < blockSize; i3++) {
              words[offset5 + i3] ^= keystream[i3];
            }
          }
        });
        CTR.Decryptor = Encryptor;
        return CTR;
      }();
      return CryptoJS.mode.CTR;
    });
  }
});

// node_modules/crypto-js/mode-ctr-gladman.js
var require_mode_ctr_gladman = __commonJS({
  "node_modules/crypto-js/mode-ctr-gladman.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.mode.CTRGladman = function() {
        var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
        function incWord(word) {
          if ((word >> 24 & 255) === 255) {
            var b1 = word >> 16 & 255;
            var b22 = word >> 8 & 255;
            var b3 = word & 255;
            if (b1 === 255) {
              b1 = 0;
              if (b22 === 255) {
                b22 = 0;
                if (b3 === 255) {
                  b3 = 0;
                } else {
                  ++b3;
                }
              } else {
                ++b22;
              }
            } else {
              ++b1;
            }
            word = 0;
            word += b1 << 16;
            word += b22 << 8;
            word += b3;
          } else {
            word += 1 << 24;
          }
          return word;
        }
        function incCounter(counter) {
          if ((counter[0] = incWord(counter[0])) === 0) {
            counter[1] = incWord(counter[1]);
          }
          return counter;
        }
        var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
          processBlock: function(words, offset5) {
            var cipher = this._cipher;
            var blockSize = cipher.blockSize;
            var iv = this._iv;
            var counter = this._counter;
            if (iv) {
              counter = this._counter = iv.slice(0);
              this._iv = void 0;
            }
            incCounter(counter);
            var keystream = counter.slice(0);
            cipher.encryptBlock(keystream, 0);
            for (var i3 = 0; i3 < blockSize; i3++) {
              words[offset5 + i3] ^= keystream[i3];
            }
          }
        });
        CTRGladman.Decryptor = Encryptor;
        return CTRGladman;
      }();
      return CryptoJS.mode.CTRGladman;
    });
  }
});

// node_modules/crypto-js/mode-ofb.js
var require_mode_ofb = __commonJS({
  "node_modules/crypto-js/mode-ofb.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.mode.OFB = function() {
        var OFB = CryptoJS.lib.BlockCipherMode.extend();
        var Encryptor = OFB.Encryptor = OFB.extend({
          processBlock: function(words, offset5) {
            var cipher = this._cipher;
            var blockSize = cipher.blockSize;
            var iv = this._iv;
            var keystream = this._keystream;
            if (iv) {
              keystream = this._keystream = iv.slice(0);
              this._iv = void 0;
            }
            cipher.encryptBlock(keystream, 0);
            for (var i3 = 0; i3 < blockSize; i3++) {
              words[offset5 + i3] ^= keystream[i3];
            }
          }
        });
        OFB.Decryptor = Encryptor;
        return OFB;
      }();
      return CryptoJS.mode.OFB;
    });
  }
});

// node_modules/crypto-js/mode-ecb.js
var require_mode_ecb = __commonJS({
  "node_modules/crypto-js/mode-ecb.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.mode.ECB = function() {
        var ECB = CryptoJS.lib.BlockCipherMode.extend();
        ECB.Encryptor = ECB.extend({
          processBlock: function(words, offset5) {
            this._cipher.encryptBlock(words, offset5);
          }
        });
        ECB.Decryptor = ECB.extend({
          processBlock: function(words, offset5) {
            this._cipher.decryptBlock(words, offset5);
          }
        });
        return ECB;
      }();
      return CryptoJS.mode.ECB;
    });
  }
});

// node_modules/crypto-js/pad-ansix923.js
var require_pad_ansix923 = __commonJS({
  "node_modules/crypto-js/pad-ansix923.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.pad.AnsiX923 = {
        pad: function(data, blockSize) {
          var dataSigBytes = data.sigBytes;
          var blockSizeBytes = blockSize * 4;
          var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
          var lastBytePos = dataSigBytes + nPaddingBytes - 1;
          data.clamp();
          data.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8;
          data.sigBytes += nPaddingBytes;
        },
        unpad: function(data) {
          var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
          data.sigBytes -= nPaddingBytes;
        }
      };
      return CryptoJS.pad.Ansix923;
    });
  }
});

// node_modules/crypto-js/pad-iso10126.js
var require_pad_iso10126 = __commonJS({
  "node_modules/crypto-js/pad-iso10126.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.pad.Iso10126 = {
        pad: function(data, blockSize) {
          var blockSizeBytes = blockSize * 4;
          var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
          data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
        },
        unpad: function(data) {
          var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255;
          data.sigBytes -= nPaddingBytes;
        }
      };
      return CryptoJS.pad.Iso10126;
    });
  }
});

// node_modules/crypto-js/pad-iso97971.js
var require_pad_iso97971 = __commonJS({
  "node_modules/crypto-js/pad-iso97971.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.pad.Iso97971 = {
        pad: function(data, blockSize) {
          data.concat(CryptoJS.lib.WordArray.create([2147483648], 1));
          CryptoJS.pad.ZeroPadding.pad(data, blockSize);
        },
        unpad: function(data) {
          CryptoJS.pad.ZeroPadding.unpad(data);
          data.sigBytes--;
        }
      };
      return CryptoJS.pad.Iso97971;
    });
  }
});

// node_modules/crypto-js/pad-zeropadding.js
var require_pad_zeropadding = __commonJS({
  "node_modules/crypto-js/pad-zeropadding.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.pad.ZeroPadding = {
        pad: function(data, blockSize) {
          var blockSizeBytes = blockSize * 4;
          data.clamp();
          data.sigBytes += blockSizeBytes - (data.sigBytes % blockSizeBytes || blockSizeBytes);
        },
        unpad: function(data) {
          var dataWords = data.words;
          var i3 = data.sigBytes - 1;
          for (var i3 = data.sigBytes - 1; i3 >= 0; i3--) {
            if (dataWords[i3 >>> 2] >>> 24 - i3 % 4 * 8 & 255) {
              data.sigBytes = i3 + 1;
              break;
            }
          }
        }
      };
      return CryptoJS.pad.ZeroPadding;
    });
  }
});

// node_modules/crypto-js/pad-nopadding.js
var require_pad_nopadding = __commonJS({
  "node_modules/crypto-js/pad-nopadding.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      CryptoJS.pad.NoPadding = {
        pad: function() {
        },
        unpad: function() {
        }
      };
      return CryptoJS.pad.NoPadding;
    });
  }
});

// node_modules/crypto-js/format-hex.js
var require_format_hex = __commonJS({
  "node_modules/crypto-js/format-hex.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function(undefined2) {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var CipherParams = C_lib.CipherParams;
        var C_enc = C3.enc;
        var Hex = C_enc.Hex;
        var C_format = C3.format;
        var HexFormatter = C_format.Hex = {
          /**
           * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The hexadecimally encoded string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.format.Hex.stringify(cipherParams);
           */
          stringify: function(cipherParams) {
            return cipherParams.ciphertext.toString(Hex);
          },
          /**
           * Converts a hexadecimally encoded ciphertext string to a cipher params object.
           *
           * @param {string} input The hexadecimally encoded string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.Hex.parse(hexString);
           */
          parse: function(input) {
            var ciphertext = Hex.parse(input);
            return CipherParams.create({ ciphertext });
          }
        };
      })();
      return CryptoJS.format.Hex;
    });
  }
});

// node_modules/crypto-js/aes.js
var require_aes = __commonJS({
  "node_modules/crypto-js/aes.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C3.algo;
        var SBOX = [];
        var INV_SBOX = [];
        var SUB_MIX_0 = [];
        var SUB_MIX_1 = [];
        var SUB_MIX_2 = [];
        var SUB_MIX_3 = [];
        var INV_SUB_MIX_0 = [];
        var INV_SUB_MIX_1 = [];
        var INV_SUB_MIX_2 = [];
        var INV_SUB_MIX_3 = [];
        (function() {
          var d3 = [];
          for (var i3 = 0; i3 < 256; i3++) {
            if (i3 < 128) {
              d3[i3] = i3 << 1;
            } else {
              d3[i3] = i3 << 1 ^ 283;
            }
          }
          var x2 = 0;
          var xi = 0;
          for (var i3 = 0; i3 < 256; i3++) {
            var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
            sx = sx >>> 8 ^ sx & 255 ^ 99;
            SBOX[x2] = sx;
            INV_SBOX[sx] = x2;
            var x22 = d3[x2];
            var x4 = d3[x22];
            var x8 = d3[x4];
            var t3 = d3[sx] * 257 ^ sx * 16843008;
            SUB_MIX_0[x2] = t3 << 24 | t3 >>> 8;
            SUB_MIX_1[x2] = t3 << 16 | t3 >>> 16;
            SUB_MIX_2[x2] = t3 << 8 | t3 >>> 24;
            SUB_MIX_3[x2] = t3;
            var t3 = x8 * 16843009 ^ x4 * 65537 ^ x22 * 257 ^ x2 * 16843008;
            INV_SUB_MIX_0[sx] = t3 << 24 | t3 >>> 8;
            INV_SUB_MIX_1[sx] = t3 << 16 | t3 >>> 16;
            INV_SUB_MIX_2[sx] = t3 << 8 | t3 >>> 24;
            INV_SUB_MIX_3[sx] = t3;
            if (!x2) {
              x2 = xi = 1;
            } else {
              x2 = x22 ^ d3[d3[d3[x8 ^ x22]]];
              xi ^= d3[d3[xi]];
            }
          }
        })();
        var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
        var AES = C_algo.AES = BlockCipher.extend({
          _doReset: function() {
            var t3;
            if (this._nRounds && this._keyPriorReset === this._key) {
              return;
            }
            var key = this._keyPriorReset = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;
            var nRounds = this._nRounds = keySize + 6;
            var ksRows = (nRounds + 1) * 4;
            var keySchedule = this._keySchedule = [];
            for (var ksRow = 0; ksRow < ksRows; ksRow++) {
              if (ksRow < keySize) {
                keySchedule[ksRow] = keyWords[ksRow];
              } else {
                t3 = keySchedule[ksRow - 1];
                if (!(ksRow % keySize)) {
                  t3 = t3 << 8 | t3 >>> 24;
                  t3 = SBOX[t3 >>> 24] << 24 | SBOX[t3 >>> 16 & 255] << 16 | SBOX[t3 >>> 8 & 255] << 8 | SBOX[t3 & 255];
                  t3 ^= RCON[ksRow / keySize | 0] << 24;
                } else if (keySize > 6 && ksRow % keySize == 4) {
                  t3 = SBOX[t3 >>> 24] << 24 | SBOX[t3 >>> 16 & 255] << 16 | SBOX[t3 >>> 8 & 255] << 8 | SBOX[t3 & 255];
                }
                keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t3;
              }
            }
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
              var ksRow = ksRows - invKsRow;
              if (invKsRow % 4) {
                var t3 = keySchedule[ksRow];
              } else {
                var t3 = keySchedule[ksRow - 4];
              }
              if (invKsRow < 4 || ksRow <= 4) {
                invKeySchedule[invKsRow] = t3;
              } else {
                invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t3 >>> 24]] ^ INV_SUB_MIX_1[SBOX[t3 >>> 16 & 255]] ^ INV_SUB_MIX_2[SBOX[t3 >>> 8 & 255]] ^ INV_SUB_MIX_3[SBOX[t3 & 255]];
              }
            }
          },
          encryptBlock: function(M, offset5) {
            this._doCryptBlock(M, offset5, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
          },
          decryptBlock: function(M, offset5) {
            var t3 = M[offset5 + 1];
            M[offset5 + 1] = M[offset5 + 3];
            M[offset5 + 3] = t3;
            this._doCryptBlock(M, offset5, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
            var t3 = M[offset5 + 1];
            M[offset5 + 1] = M[offset5 + 3];
            M[offset5 + 3] = t3;
          },
          _doCryptBlock: function(M, offset5, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) {
            var nRounds = this._nRounds;
            var s0 = M[offset5] ^ keySchedule[0];
            var s1 = M[offset5 + 1] ^ keySchedule[1];
            var s22 = M[offset5 + 2] ^ keySchedule[2];
            var s32 = M[offset5 + 3] ^ keySchedule[3];
            var ksRow = 4;
            for (var round2 = 1; round2 < nRounds; round2++) {
              var t0 = SUB_MIX_02[s0 >>> 24] ^ SUB_MIX_12[s1 >>> 16 & 255] ^ SUB_MIX_22[s22 >>> 8 & 255] ^ SUB_MIX_32[s32 & 255] ^ keySchedule[ksRow++];
              var t1 = SUB_MIX_02[s1 >>> 24] ^ SUB_MIX_12[s22 >>> 16 & 255] ^ SUB_MIX_22[s32 >>> 8 & 255] ^ SUB_MIX_32[s0 & 255] ^ keySchedule[ksRow++];
              var t22 = SUB_MIX_02[s22 >>> 24] ^ SUB_MIX_12[s32 >>> 16 & 255] ^ SUB_MIX_22[s0 >>> 8 & 255] ^ SUB_MIX_32[s1 & 255] ^ keySchedule[ksRow++];
              var t3 = SUB_MIX_02[s32 >>> 24] ^ SUB_MIX_12[s0 >>> 16 & 255] ^ SUB_MIX_22[s1 >>> 8 & 255] ^ SUB_MIX_32[s22 & 255] ^ keySchedule[ksRow++];
              s0 = t0;
              s1 = t1;
              s22 = t22;
              s32 = t3;
            }
            var t0 = (SBOX2[s0 >>> 24] << 24 | SBOX2[s1 >>> 16 & 255] << 16 | SBOX2[s22 >>> 8 & 255] << 8 | SBOX2[s32 & 255]) ^ keySchedule[ksRow++];
            var t1 = (SBOX2[s1 >>> 24] << 24 | SBOX2[s22 >>> 16 & 255] << 16 | SBOX2[s32 >>> 8 & 255] << 8 | SBOX2[s0 & 255]) ^ keySchedule[ksRow++];
            var t22 = (SBOX2[s22 >>> 24] << 24 | SBOX2[s32 >>> 16 & 255] << 16 | SBOX2[s0 >>> 8 & 255] << 8 | SBOX2[s1 & 255]) ^ keySchedule[ksRow++];
            var t3 = (SBOX2[s32 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s22 & 255]) ^ keySchedule[ksRow++];
            M[offset5] = t0;
            M[offset5 + 1] = t1;
            M[offset5 + 2] = t22;
            M[offset5 + 3] = t3;
          },
          keySize: 256 / 32
        });
        C3.AES = BlockCipher._createHelper(AES);
      })();
      return CryptoJS.AES;
    });
  }
});

// node_modules/crypto-js/tripledes.js
var require_tripledes = __commonJS({
  "node_modules/crypto-js/tripledes.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var WordArray = C_lib.WordArray;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C3.algo;
        var PC1 = [
          57,
          49,
          41,
          33,
          25,
          17,
          9,
          1,
          58,
          50,
          42,
          34,
          26,
          18,
          10,
          2,
          59,
          51,
          43,
          35,
          27,
          19,
          11,
          3,
          60,
          52,
          44,
          36,
          63,
          55,
          47,
          39,
          31,
          23,
          15,
          7,
          62,
          54,
          46,
          38,
          30,
          22,
          14,
          6,
          61,
          53,
          45,
          37,
          29,
          21,
          13,
          5,
          28,
          20,
          12,
          4
        ];
        var PC2 = [
          14,
          17,
          11,
          24,
          1,
          5,
          3,
          28,
          15,
          6,
          21,
          10,
          23,
          19,
          12,
          4,
          26,
          8,
          16,
          7,
          27,
          20,
          13,
          2,
          41,
          52,
          31,
          37,
          47,
          55,
          30,
          40,
          51,
          45,
          33,
          48,
          44,
          49,
          39,
          56,
          34,
          53,
          46,
          42,
          50,
          36,
          29,
          32
        ];
        var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
        var SBOX_P = [
          {
            0: 8421888,
            268435456: 32768,
            536870912: 8421378,
            805306368: 2,
            1073741824: 512,
            1342177280: 8421890,
            1610612736: 8389122,
            1879048192: 8388608,
            2147483648: 514,
            2415919104: 8389120,
            2684354560: 33280,
            2952790016: 8421376,
            3221225472: 32770,
            3489660928: 8388610,
            3758096384: 0,
            4026531840: 33282,
            134217728: 0,
            402653184: 8421890,
            671088640: 33282,
            939524096: 32768,
            1207959552: 8421888,
            1476395008: 512,
            1744830464: 8421378,
            2013265920: 2,
            2281701376: 8389120,
            2550136832: 33280,
            2818572288: 8421376,
            3087007744: 8389122,
            3355443200: 8388610,
            3623878656: 32770,
            3892314112: 514,
            4160749568: 8388608,
            1: 32768,
            268435457: 2,
            536870913: 8421888,
            805306369: 8388608,
            1073741825: 8421378,
            1342177281: 33280,
            1610612737: 512,
            1879048193: 8389122,
            2147483649: 8421890,
            2415919105: 8421376,
            2684354561: 8388610,
            2952790017: 33282,
            3221225473: 514,
            3489660929: 8389120,
            3758096385: 32770,
            4026531841: 0,
            134217729: 8421890,
            402653185: 8421376,
            671088641: 8388608,
            939524097: 512,
            1207959553: 32768,
            1476395009: 8388610,
            1744830465: 2,
            2013265921: 33282,
            2281701377: 32770,
            2550136833: 8389122,
            2818572289: 514,
            3087007745: 8421888,
            3355443201: 8389120,
            3623878657: 0,
            3892314113: 33280,
            4160749569: 8421378
          },
          {
            0: 1074282512,
            16777216: 16384,
            33554432: 524288,
            50331648: 1074266128,
            67108864: 1073741840,
            83886080: 1074282496,
            100663296: 1073758208,
            117440512: 16,
            134217728: 540672,
            150994944: 1073758224,
            167772160: 1073741824,
            184549376: 540688,
            201326592: 524304,
            218103808: 0,
            234881024: 16400,
            251658240: 1074266112,
            8388608: 1073758208,
            25165824: 540688,
            41943040: 16,
            58720256: 1073758224,
            75497472: 1074282512,
            92274688: 1073741824,
            109051904: 524288,
            125829120: 1074266128,
            142606336: 524304,
            159383552: 0,
            176160768: 16384,
            192937984: 1074266112,
            209715200: 1073741840,
            226492416: 540672,
            243269632: 1074282496,
            260046848: 16400,
            268435456: 0,
            285212672: 1074266128,
            301989888: 1073758224,
            318767104: 1074282496,
            335544320: 1074266112,
            352321536: 16,
            369098752: 540688,
            385875968: 16384,
            402653184: 16400,
            419430400: 524288,
            436207616: 524304,
            452984832: 1073741840,
            469762048: 540672,
            486539264: 1073758208,
            503316480: 1073741824,
            520093696: 1074282512,
            276824064: 540688,
            293601280: 524288,
            310378496: 1074266112,
            327155712: 16384,
            343932928: 1073758208,
            360710144: 1074282512,
            377487360: 16,
            394264576: 1073741824,
            411041792: 1074282496,
            427819008: 1073741840,
            444596224: 1073758224,
            461373440: 524304,
            478150656: 0,
            494927872: 16400,
            511705088: 1074266128,
            528482304: 540672
          },
          {
            0: 260,
            1048576: 0,
            2097152: 67109120,
            3145728: 65796,
            4194304: 65540,
            5242880: 67108868,
            6291456: 67174660,
            7340032: 67174400,
            8388608: 67108864,
            9437184: 67174656,
            10485760: 65792,
            11534336: 67174404,
            12582912: 67109124,
            13631488: 65536,
            14680064: 4,
            15728640: 256,
            524288: 67174656,
            1572864: 67174404,
            2621440: 0,
            3670016: 67109120,
            4718592: 67108868,
            5767168: 65536,
            6815744: 65540,
            7864320: 260,
            8912896: 4,
            9961472: 256,
            11010048: 67174400,
            12058624: 65796,
            13107200: 65792,
            14155776: 67109124,
            15204352: 67174660,
            16252928: 67108864,
            16777216: 67174656,
            17825792: 65540,
            18874368: 65536,
            19922944: 67109120,
            20971520: 256,
            22020096: 67174660,
            23068672: 67108868,
            24117248: 0,
            25165824: 67109124,
            26214400: 67108864,
            27262976: 4,
            28311552: 65792,
            29360128: 67174400,
            30408704: 260,
            31457280: 65796,
            32505856: 67174404,
            17301504: 67108864,
            18350080: 260,
            19398656: 67174656,
            20447232: 0,
            21495808: 65540,
            22544384: 67109120,
            23592960: 256,
            24641536: 67174404,
            25690112: 65536,
            26738688: 67174660,
            27787264: 65796,
            28835840: 67108868,
            29884416: 67109124,
            30932992: 67174400,
            31981568: 4,
            33030144: 65792
          },
          {
            0: 2151682048,
            65536: 2147487808,
            131072: 4198464,
            196608: 2151677952,
            262144: 0,
            327680: 4198400,
            393216: 2147483712,
            458752: 4194368,
            524288: 2147483648,
            589824: 4194304,
            655360: 64,
            720896: 2147487744,
            786432: 2151678016,
            851968: 4160,
            917504: 4096,
            983040: 2151682112,
            32768: 2147487808,
            98304: 64,
            163840: 2151678016,
            229376: 2147487744,
            294912: 4198400,
            360448: 2151682112,
            425984: 0,
            491520: 2151677952,
            557056: 4096,
            622592: 2151682048,
            688128: 4194304,
            753664: 4160,
            819200: 2147483648,
            884736: 4194368,
            950272: 4198464,
            1015808: 2147483712,
            1048576: 4194368,
            1114112: 4198400,
            1179648: 2147483712,
            1245184: 0,
            1310720: 4160,
            1376256: 2151678016,
            1441792: 2151682048,
            1507328: 2147487808,
            1572864: 2151682112,
            1638400: 2147483648,
            1703936: 2151677952,
            1769472: 4198464,
            1835008: 2147487744,
            1900544: 4194304,
            1966080: 64,
            2031616: 4096,
            1081344: 2151677952,
            1146880: 2151682112,
            1212416: 0,
            1277952: 4198400,
            1343488: 4194368,
            1409024: 2147483648,
            1474560: 2147487808,
            1540096: 64,
            1605632: 2147483712,
            1671168: 4096,
            1736704: 2147487744,
            1802240: 2151678016,
            1867776: 4160,
            1933312: 2151682048,
            1998848: 4194304,
            2064384: 4198464
          },
          {
            0: 128,
            4096: 17039360,
            8192: 262144,
            12288: 536870912,
            16384: 537133184,
            20480: 16777344,
            24576: 553648256,
            28672: 262272,
            32768: 16777216,
            36864: 537133056,
            40960: 536871040,
            45056: 553910400,
            49152: 553910272,
            53248: 0,
            57344: 17039488,
            61440: 553648128,
            2048: 17039488,
            6144: 553648256,
            10240: 128,
            14336: 17039360,
            18432: 262144,
            22528: 537133184,
            26624: 553910272,
            30720: 536870912,
            34816: 537133056,
            38912: 0,
            43008: 553910400,
            47104: 16777344,
            51200: 536871040,
            55296: 553648128,
            59392: 16777216,
            63488: 262272,
            65536: 262144,
            69632: 128,
            73728: 536870912,
            77824: 553648256,
            81920: 16777344,
            86016: 553910272,
            90112: 537133184,
            94208: 16777216,
            98304: 553910400,
            102400: 553648128,
            106496: 17039360,
            110592: 537133056,
            114688: 262272,
            118784: 536871040,
            122880: 0,
            126976: 17039488,
            67584: 553648256,
            71680: 16777216,
            75776: 17039360,
            79872: 537133184,
            83968: 536870912,
            88064: 17039488,
            92160: 128,
            96256: 553910272,
            100352: 262272,
            104448: 553910400,
            108544: 0,
            112640: 553648128,
            116736: 16777344,
            120832: 262144,
            124928: 537133056,
            129024: 536871040
          },
          {
            0: 268435464,
            256: 8192,
            512: 270532608,
            768: 270540808,
            1024: 268443648,
            1280: 2097152,
            1536: 2097160,
            1792: 268435456,
            2048: 0,
            2304: 268443656,
            2560: 2105344,
            2816: 8,
            3072: 270532616,
            3328: 2105352,
            3584: 8200,
            3840: 270540800,
            128: 270532608,
            384: 270540808,
            640: 8,
            896: 2097152,
            1152: 2105352,
            1408: 268435464,
            1664: 268443648,
            1920: 8200,
            2176: 2097160,
            2432: 8192,
            2688: 268443656,
            2944: 270532616,
            3200: 0,
            3456: 270540800,
            3712: 2105344,
            3968: 268435456,
            4096: 268443648,
            4352: 270532616,
            4608: 270540808,
            4864: 8200,
            5120: 2097152,
            5376: 268435456,
            5632: 268435464,
            5888: 2105344,
            6144: 2105352,
            6400: 0,
            6656: 8,
            6912: 270532608,
            7168: 8192,
            7424: 268443656,
            7680: 270540800,
            7936: 2097160,
            4224: 8,
            4480: 2105344,
            4736: 2097152,
            4992: 268435464,
            5248: 268443648,
            5504: 8200,
            5760: 270540808,
            6016: 270532608,
            6272: 270540800,
            6528: 270532616,
            6784: 8192,
            7040: 2105352,
            7296: 2097160,
            7552: 0,
            7808: 268435456,
            8064: 268443656
          },
          {
            0: 1048576,
            16: 33555457,
            32: 1024,
            48: 1049601,
            64: 34604033,
            80: 0,
            96: 1,
            112: 34603009,
            128: 33555456,
            144: 1048577,
            160: 33554433,
            176: 34604032,
            192: 34603008,
            208: 1025,
            224: 1049600,
            240: 33554432,
            8: 34603009,
            24: 0,
            40: 33555457,
            56: 34604032,
            72: 1048576,
            88: 33554433,
            104: 33554432,
            120: 1025,
            136: 1049601,
            152: 33555456,
            168: 34603008,
            184: 1048577,
            200: 1024,
            216: 34604033,
            232: 1,
            248: 1049600,
            256: 33554432,
            272: 1048576,
            288: 33555457,
            304: 34603009,
            320: 1048577,
            336: 33555456,
            352: 34604032,
            368: 1049601,
            384: 1025,
            400: 34604033,
            416: 1049600,
            432: 1,
            448: 0,
            464: 34603008,
            480: 33554433,
            496: 1024,
            264: 1049600,
            280: 33555457,
            296: 34603009,
            312: 1,
            328: 33554432,
            344: 1048576,
            360: 1025,
            376: 34604032,
            392: 33554433,
            408: 34603008,
            424: 0,
            440: 34604033,
            456: 1049601,
            472: 1024,
            488: 33555456,
            504: 1048577
          },
          {
            0: 134219808,
            1: 131072,
            2: 134217728,
            3: 32,
            4: 131104,
            5: 134350880,
            6: 134350848,
            7: 2048,
            8: 134348800,
            9: 134219776,
            10: 133120,
            11: 134348832,
            12: 2080,
            13: 0,
            14: 134217760,
            15: 133152,
            2147483648: 2048,
            2147483649: 134350880,
            2147483650: 134219808,
            2147483651: 134217728,
            2147483652: 134348800,
            2147483653: 133120,
            2147483654: 133152,
            2147483655: 32,
            2147483656: 134217760,
            2147483657: 2080,
            2147483658: 131104,
            2147483659: 134350848,
            2147483660: 0,
            2147483661: 134348832,
            2147483662: 134219776,
            2147483663: 131072,
            16: 133152,
            17: 134350848,
            18: 32,
            19: 2048,
            20: 134219776,
            21: 134217760,
            22: 134348832,
            23: 131072,
            24: 0,
            25: 131104,
            26: 134348800,
            27: 134219808,
            28: 134350880,
            29: 133120,
            30: 2080,
            31: 134217728,
            2147483664: 131072,
            2147483665: 2048,
            2147483666: 134348832,
            2147483667: 133152,
            2147483668: 32,
            2147483669: 134348800,
            2147483670: 134217728,
            2147483671: 134219808,
            2147483672: 134350880,
            2147483673: 134217760,
            2147483674: 134219776,
            2147483675: 0,
            2147483676: 133120,
            2147483677: 2080,
            2147483678: 131104,
            2147483679: 134350848
          }
        ];
        var SBOX_MASK = [
          4160749569,
          528482304,
          33030144,
          2064384,
          129024,
          8064,
          504,
          2147483679
        ];
        var DES = C_algo.DES = BlockCipher.extend({
          _doReset: function() {
            var key = this._key;
            var keyWords = key.words;
            var keyBits = [];
            for (var i3 = 0; i3 < 56; i3++) {
              var keyBitPos = PC1[i3] - 1;
              keyBits[i3] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1;
            }
            var subKeys = this._subKeys = [];
            for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
              var subKey = subKeys[nSubKey] = [];
              var bitShift = BIT_SHIFTS[nSubKey];
              for (var i3 = 0; i3 < 24; i3++) {
                subKey[i3 / 6 | 0] |= keyBits[(PC2[i3] - 1 + bitShift) % 28] << 31 - i3 % 6;
                subKey[4 + (i3 / 6 | 0)] |= keyBits[28 + (PC2[i3 + 24] - 1 + bitShift) % 28] << 31 - i3 % 6;
              }
              subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
              for (var i3 = 1; i3 < 7; i3++) {
                subKey[i3] = subKey[i3] >>> (i3 - 1) * 4 + 3;
              }
              subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
            }
            var invSubKeys = this._invSubKeys = [];
            for (var i3 = 0; i3 < 16; i3++) {
              invSubKeys[i3] = subKeys[15 - i3];
            }
          },
          encryptBlock: function(M, offset5) {
            this._doCryptBlock(M, offset5, this._subKeys);
          },
          decryptBlock: function(M, offset5) {
            this._doCryptBlock(M, offset5, this._invSubKeys);
          },
          _doCryptBlock: function(M, offset5, subKeys) {
            this._lBlock = M[offset5];
            this._rBlock = M[offset5 + 1];
            exchangeLR.call(this, 4, 252645135);
            exchangeLR.call(this, 16, 65535);
            exchangeRL.call(this, 2, 858993459);
            exchangeRL.call(this, 8, 16711935);
            exchangeLR.call(this, 1, 1431655765);
            for (var round2 = 0; round2 < 16; round2++) {
              var subKey = subKeys[round2];
              var lBlock = this._lBlock;
              var rBlock = this._rBlock;
              var f3 = 0;
              for (var i3 = 0; i3 < 8; i3++) {
                f3 |= SBOX_P[i3][((rBlock ^ subKey[i3]) & SBOX_MASK[i3]) >>> 0];
              }
              this._lBlock = rBlock;
              this._rBlock = lBlock ^ f3;
            }
            var t3 = this._lBlock;
            this._lBlock = this._rBlock;
            this._rBlock = t3;
            exchangeLR.call(this, 1, 1431655765);
            exchangeRL.call(this, 8, 16711935);
            exchangeRL.call(this, 2, 858993459);
            exchangeLR.call(this, 16, 65535);
            exchangeLR.call(this, 4, 252645135);
            M[offset5] = this._lBlock;
            M[offset5 + 1] = this._rBlock;
          },
          keySize: 64 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        function exchangeLR(offset5, mask) {
          var t3 = (this._lBlock >>> offset5 ^ this._rBlock) & mask;
          this._rBlock ^= t3;
          this._lBlock ^= t3 << offset5;
        }
        function exchangeRL(offset5, mask) {
          var t3 = (this._rBlock >>> offset5 ^ this._lBlock) & mask;
          this._lBlock ^= t3;
          this._rBlock ^= t3 << offset5;
        }
        C3.DES = BlockCipher._createHelper(DES);
        var TripleDES = C_algo.TripleDES = BlockCipher.extend({
          _doReset: function() {
            var key = this._key;
            var keyWords = key.words;
            if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
              throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");
            }
            var key1 = keyWords.slice(0, 2);
            var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
            var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);
            this._des1 = DES.createEncryptor(WordArray.create(key1));
            this._des2 = DES.createEncryptor(WordArray.create(key2));
            this._des3 = DES.createEncryptor(WordArray.create(key3));
          },
          encryptBlock: function(M, offset5) {
            this._des1.encryptBlock(M, offset5);
            this._des2.decryptBlock(M, offset5);
            this._des3.encryptBlock(M, offset5);
          },
          decryptBlock: function(M, offset5) {
            this._des3.decryptBlock(M, offset5);
            this._des2.encryptBlock(M, offset5);
            this._des1.decryptBlock(M, offset5);
          },
          keySize: 192 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        C3.TripleDES = BlockCipher._createHelper(TripleDES);
      })();
      return CryptoJS.TripleDES;
    });
  }
});

// node_modules/crypto-js/rc4.js
var require_rc4 = __commonJS({
  "node_modules/crypto-js/rc4.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C3.algo;
        var RC4 = C_algo.RC4 = StreamCipher.extend({
          _doReset: function() {
            var key = this._key;
            var keyWords = key.words;
            var keySigBytes = key.sigBytes;
            var S = this._S = [];
            for (var i3 = 0; i3 < 256; i3++) {
              S[i3] = i3;
            }
            for (var i3 = 0, j3 = 0; i3 < 256; i3++) {
              var keyByteIndex = i3 % keySigBytes;
              var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255;
              j3 = (j3 + S[i3] + keyByte) % 256;
              var t3 = S[i3];
              S[i3] = S[j3];
              S[j3] = t3;
            }
            this._i = this._j = 0;
          },
          _doProcessBlock: function(M, offset5) {
            M[offset5] ^= generateKeystreamWord.call(this);
          },
          keySize: 256 / 32,
          ivSize: 0
        });
        function generateKeystreamWord() {
          var S = this._S;
          var i3 = this._i;
          var j3 = this._j;
          var keystreamWord = 0;
          for (var n4 = 0; n4 < 4; n4++) {
            i3 = (i3 + 1) % 256;
            j3 = (j3 + S[i3]) % 256;
            var t3 = S[i3];
            S[i3] = S[j3];
            S[j3] = t3;
            keystreamWord |= S[(S[i3] + S[j3]) % 256] << 24 - n4 * 8;
          }
          this._i = i3;
          this._j = j3;
          return keystreamWord;
        }
        C3.RC4 = StreamCipher._createHelper(RC4);
        var RC4Drop = C_algo.RC4Drop = RC4.extend({
          /**
           * Configuration options.
           *
           * @property {number} drop The number of keystream words to drop. Default 192
           */
          cfg: RC4.cfg.extend({
            drop: 192
          }),
          _doReset: function() {
            RC4._doReset.call(this);
            for (var i3 = this.cfg.drop; i3 > 0; i3--) {
              generateKeystreamWord.call(this);
            }
          }
        });
        C3.RC4Drop = StreamCipher._createHelper(RC4Drop);
      })();
      return CryptoJS.RC4;
    });
  }
});

// node_modules/crypto-js/rabbit.js
var require_rabbit = __commonJS({
  "node_modules/crypto-js/rabbit.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C3.algo;
        var S = [];
        var C_ = [];
        var G2 = [];
        var Rabbit = C_algo.Rabbit = StreamCipher.extend({
          _doReset: function() {
            var K2 = this._key.words;
            var iv = this.cfg.iv;
            for (var i3 = 0; i3 < 4; i3++) {
              K2[i3] = (K2[i3] << 8 | K2[i3] >>> 24) & 16711935 | (K2[i3] << 24 | K2[i3] >>> 8) & 4278255360;
            }
            var X2 = this._X = [
              K2[0],
              K2[3] << 16 | K2[2] >>> 16,
              K2[1],
              K2[0] << 16 | K2[3] >>> 16,
              K2[2],
              K2[1] << 16 | K2[0] >>> 16,
              K2[3],
              K2[2] << 16 | K2[1] >>> 16
            ];
            var C4 = this._C = [
              K2[2] << 16 | K2[2] >>> 16,
              K2[0] & 4294901760 | K2[1] & 65535,
              K2[3] << 16 | K2[3] >>> 16,
              K2[1] & 4294901760 | K2[2] & 65535,
              K2[0] << 16 | K2[0] >>> 16,
              K2[2] & 4294901760 | K2[3] & 65535,
              K2[1] << 16 | K2[1] >>> 16,
              K2[3] & 4294901760 | K2[0] & 65535
            ];
            this._b = 0;
            for (var i3 = 0; i3 < 4; i3++) {
              nextState.call(this);
            }
            for (var i3 = 0; i3 < 8; i3++) {
              C4[i3] ^= X2[i3 + 4 & 7];
            }
            if (iv) {
              var IV = iv.words;
              var IV_0 = IV[0];
              var IV_1 = IV[1];
              var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
              var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
              var i1 = i0 >>> 16 | i22 & 4294901760;
              var i32 = i22 << 16 | i0 & 65535;
              C4[0] ^= i0;
              C4[1] ^= i1;
              C4[2] ^= i22;
              C4[3] ^= i32;
              C4[4] ^= i0;
              C4[5] ^= i1;
              C4[6] ^= i22;
              C4[7] ^= i32;
              for (var i3 = 0; i3 < 4; i3++) {
                nextState.call(this);
              }
            }
          },
          _doProcessBlock: function(M, offset5) {
            var X2 = this._X;
            nextState.call(this);
            S[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
            S[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
            S[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
            S[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
            for (var i3 = 0; i3 < 4; i3++) {
              S[i3] = (S[i3] << 8 | S[i3] >>> 24) & 16711935 | (S[i3] << 24 | S[i3] >>> 8) & 4278255360;
              M[offset5 + i3] ^= S[i3];
            }
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function nextState() {
          var X2 = this._X;
          var C4 = this._C;
          for (var i3 = 0; i3 < 8; i3++) {
            C_[i3] = C4[i3];
          }
          C4[0] = C4[0] + 1295307597 + this._b | 0;
          C4[1] = C4[1] + 3545052371 + (C4[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
          C4[2] = C4[2] + 886263092 + (C4[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
          C4[3] = C4[3] + 1295307597 + (C4[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
          C4[4] = C4[4] + 3545052371 + (C4[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
          C4[5] = C4[5] + 886263092 + (C4[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
          C4[6] = C4[6] + 1295307597 + (C4[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
          C4[7] = C4[7] + 3545052371 + (C4[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
          this._b = C4[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
          for (var i3 = 0; i3 < 8; i3++) {
            var gx = X2[i3] + C4[i3];
            var ga = gx & 65535;
            var gb = gx >>> 16;
            var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
            var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
            G2[i3] = gh ^ gl;
          }
          X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
          X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
          X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
          X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
          X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
          X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
          X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
          X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
        }
        C3.Rabbit = StreamCipher._createHelper(Rabbit);
      })();
      return CryptoJS.Rabbit;
    });
  }
});

// node_modules/crypto-js/rabbit-legacy.js
var require_rabbit_legacy = __commonJS({
  "node_modules/crypto-js/rabbit-legacy.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C3.algo;
        var S = [];
        var C_ = [];
        var G2 = [];
        var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
          _doReset: function() {
            var K2 = this._key.words;
            var iv = this.cfg.iv;
            var X2 = this._X = [
              K2[0],
              K2[3] << 16 | K2[2] >>> 16,
              K2[1],
              K2[0] << 16 | K2[3] >>> 16,
              K2[2],
              K2[1] << 16 | K2[0] >>> 16,
              K2[3],
              K2[2] << 16 | K2[1] >>> 16
            ];
            var C4 = this._C = [
              K2[2] << 16 | K2[2] >>> 16,
              K2[0] & 4294901760 | K2[1] & 65535,
              K2[3] << 16 | K2[3] >>> 16,
              K2[1] & 4294901760 | K2[2] & 65535,
              K2[0] << 16 | K2[0] >>> 16,
              K2[2] & 4294901760 | K2[3] & 65535,
              K2[1] << 16 | K2[1] >>> 16,
              K2[3] & 4294901760 | K2[0] & 65535
            ];
            this._b = 0;
            for (var i3 = 0; i3 < 4; i3++) {
              nextState.call(this);
            }
            for (var i3 = 0; i3 < 8; i3++) {
              C4[i3] ^= X2[i3 + 4 & 7];
            }
            if (iv) {
              var IV = iv.words;
              var IV_0 = IV[0];
              var IV_1 = IV[1];
              var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
              var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
              var i1 = i0 >>> 16 | i22 & 4294901760;
              var i32 = i22 << 16 | i0 & 65535;
              C4[0] ^= i0;
              C4[1] ^= i1;
              C4[2] ^= i22;
              C4[3] ^= i32;
              C4[4] ^= i0;
              C4[5] ^= i1;
              C4[6] ^= i22;
              C4[7] ^= i32;
              for (var i3 = 0; i3 < 4; i3++) {
                nextState.call(this);
              }
            }
          },
          _doProcessBlock: function(M, offset5) {
            var X2 = this._X;
            nextState.call(this);
            S[0] = X2[0] ^ X2[5] >>> 16 ^ X2[3] << 16;
            S[1] = X2[2] ^ X2[7] >>> 16 ^ X2[5] << 16;
            S[2] = X2[4] ^ X2[1] >>> 16 ^ X2[7] << 16;
            S[3] = X2[6] ^ X2[3] >>> 16 ^ X2[1] << 16;
            for (var i3 = 0; i3 < 4; i3++) {
              S[i3] = (S[i3] << 8 | S[i3] >>> 24) & 16711935 | (S[i3] << 24 | S[i3] >>> 8) & 4278255360;
              M[offset5 + i3] ^= S[i3];
            }
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function nextState() {
          var X2 = this._X;
          var C4 = this._C;
          for (var i3 = 0; i3 < 8; i3++) {
            C_[i3] = C4[i3];
          }
          C4[0] = C4[0] + 1295307597 + this._b | 0;
          C4[1] = C4[1] + 3545052371 + (C4[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
          C4[2] = C4[2] + 886263092 + (C4[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
          C4[3] = C4[3] + 1295307597 + (C4[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
          C4[4] = C4[4] + 3545052371 + (C4[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
          C4[5] = C4[5] + 886263092 + (C4[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
          C4[6] = C4[6] + 1295307597 + (C4[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
          C4[7] = C4[7] + 3545052371 + (C4[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
          this._b = C4[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
          for (var i3 = 0; i3 < 8; i3++) {
            var gx = X2[i3] + C4[i3];
            var ga = gx & 65535;
            var gb = gx >>> 16;
            var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
            var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
            G2[i3] = gh ^ gl;
          }
          X2[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
          X2[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
          X2[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
          X2[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
          X2[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
          X2[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
          X2[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
          X2[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
        }
        C3.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
      })();
      return CryptoJS.RabbitLegacy;
    });
  }
});

// node_modules/crypto-js/blowfish.js
var require_blowfish = __commonJS({
  "node_modules/crypto-js/blowfish.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
      } else {
        factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      (function() {
        var C3 = CryptoJS;
        var C_lib = C3.lib;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C3.algo;
        const N = 16;
        const ORIG_P = [
          608135816,
          2242054355,
          320440878,
          57701188,
          2752067618,
          698298832,
          137296536,
          3964562569,
          1160258022,
          953160567,
          3193202383,
          887688300,
          3232508343,
          3380367581,
          1065670069,
          3041331479,
          2450970073,
          2306472731
        ];
        const ORIG_S = [
          [
            3509652390,
            2564797868,
            805139163,
            3491422135,
            3101798381,
            1780907670,
            3128725573,
            4046225305,
            614570311,
            3012652279,
            134345442,
            2240740374,
            1667834072,
            1901547113,
            2757295779,
            4103290238,
            227898511,
            1921955416,
            1904987480,
            2182433518,
            2069144605,
            3260701109,
            2620446009,
            720527379,
            3318853667,
            677414384,
            3393288472,
            3101374703,
            2390351024,
            1614419982,
            1822297739,
            2954791486,
            3608508353,
            3174124327,
            2024746970,
            1432378464,
            3864339955,
            2857741204,
            1464375394,
            1676153920,
            1439316330,
            715854006,
            3033291828,
            289532110,
            2706671279,
            2087905683,
            3018724369,
            1668267050,
            732546397,
            1947742710,
            3462151702,
            2609353502,
            2950085171,
            1814351708,
            2050118529,
            680887927,
            999245976,
            1800124847,
            3300911131,
            1713906067,
            1641548236,
            4213287313,
            1216130144,
            1575780402,
            4018429277,
            3917837745,
            3693486850,
            3949271944,
            596196993,
            3549867205,
            258830323,
            2213823033,
            772490370,
            2760122372,
            1774776394,
            2652871518,
            566650946,
            4142492826,
            1728879713,
            2882767088,
            1783734482,
            3629395816,
            2517608232,
            2874225571,
            1861159788,
            326777828,
            3124490320,
            2130389656,
            2716951837,
            967770486,
            1724537150,
            2185432712,
            2364442137,
            1164943284,
            2105845187,
            998989502,
            3765401048,
            2244026483,
            1075463327,
            1455516326,
            1322494562,
            910128902,
            469688178,
            1117454909,
            936433444,
            3490320968,
            3675253459,
            1240580251,
            122909385,
            2157517691,
            634681816,
            4142456567,
            3825094682,
            3061402683,
            2540495037,
            79693498,
            3249098678,
            1084186820,
            1583128258,
            426386531,
            1761308591,
            1047286709,
            322548459,
            995290223,
            1845252383,
            2603652396,
            3431023940,
            2942221577,
            3202600964,
            3727903485,
            1712269319,
            422464435,
            3234572375,
            1170764815,
            3523960633,
            3117677531,
            1434042557,
            442511882,
            3600875718,
            1076654713,
            1738483198,
            4213154764,
            2393238008,
            3677496056,
            1014306527,
            4251020053,
            793779912,
            2902807211,
            842905082,
            4246964064,
            1395751752,
            1040244610,
            2656851899,
            3396308128,
            445077038,
            3742853595,
            3577915638,
            679411651,
            2892444358,
            2354009459,
            1767581616,
            3150600392,
            3791627101,
            3102740896,
            284835224,
            4246832056,
            1258075500,
            768725851,
            2589189241,
            3069724005,
            3532540348,
            1274779536,
            3789419226,
            2764799539,
            1660621633,
            3471099624,
            4011903706,
            913787905,
            3497959166,
            737222580,
            2514213453,
            2928710040,
            3937242737,
            1804850592,
            3499020752,
            2949064160,
            2386320175,
            2390070455,
            2415321851,
            4061277028,
            2290661394,
            2416832540,
            1336762016,
            1754252060,
            3520065937,
            3014181293,
            791618072,
            3188594551,
            3933548030,
            2332172193,
            3852520463,
            3043980520,
            413987798,
            3465142937,
            3030929376,
            4245938359,
            2093235073,
            3534596313,
            375366246,
            2157278981,
            2479649556,
            555357303,
            3870105701,
            2008414854,
            3344188149,
            4221384143,
            3956125452,
            2067696032,
            3594591187,
            2921233993,
            2428461,
            544322398,
            577241275,
            1471733935,
            610547355,
            4027169054,
            1432588573,
            1507829418,
            2025931657,
            3646575487,
            545086370,
            48609733,
            2200306550,
            1653985193,
            298326376,
            1316178497,
            3007786442,
            2064951626,
            458293330,
            2589141269,
            3591329599,
            3164325604,
            727753846,
            2179363840,
            146436021,
            1461446943,
            4069977195,
            705550613,
            3059967265,
            3887724982,
            4281599278,
            3313849956,
            1404054877,
            2845806497,
            146425753,
            1854211946
          ],
          [
            1266315497,
            3048417604,
            3681880366,
            3289982499,
            290971e4,
            1235738493,
            2632868024,
            2414719590,
            3970600049,
            1771706367,
            1449415276,
            3266420449,
            422970021,
            1963543593,
            2690192192,
            3826793022,
            1062508698,
            1531092325,
            1804592342,
            2583117782,
            2714934279,
            4024971509,
            1294809318,
            4028980673,
            1289560198,
            2221992742,
            1669523910,
            35572830,
            157838143,
            1052438473,
            1016535060,
            1802137761,
            1753167236,
            1386275462,
            3080475397,
            2857371447,
            1040679964,
            2145300060,
            2390574316,
            1461121720,
            2956646967,
            4031777805,
            4028374788,
            33600511,
            2920084762,
            1018524850,
            629373528,
            3691585981,
            3515945977,
            2091462646,
            2486323059,
            586499841,
            988145025,
            935516892,
            3367335476,
            2599673255,
            2839830854,
            265290510,
            3972581182,
            2759138881,
            3795373465,
            1005194799,
            847297441,
            406762289,
            1314163512,
            1332590856,
            1866599683,
            4127851711,
            750260880,
            613907577,
            1450815602,
            3165620655,
            3734664991,
            3650291728,
            3012275730,
            3704569646,
            1427272223,
            778793252,
            1343938022,
            2676280711,
            2052605720,
            1946737175,
            3164576444,
            3914038668,
            3967478842,
            3682934266,
            1661551462,
            3294938066,
            4011595847,
            840292616,
            3712170807,
            616741398,
            312560963,
            711312465,
            1351876610,
            322626781,
            1910503582,
            271666773,
            2175563734,
            1594956187,
            70604529,
            3617834859,
            1007753275,
            1495573769,
            4069517037,
            2549218298,
            2663038764,
            504708206,
            2263041392,
            3941167025,
            2249088522,
            1514023603,
            1998579484,
            1312622330,
            694541497,
            2582060303,
            2151582166,
            1382467621,
            776784248,
            2618340202,
            3323268794,
            2497899128,
            2784771155,
            503983604,
            4076293799,
            907881277,
            423175695,
            432175456,
            1378068232,
            4145222326,
            3954048622,
            3938656102,
            3820766613,
            2793130115,
            2977904593,
            26017576,
            3274890735,
            3194772133,
            1700274565,
            1756076034,
            4006520079,
            3677328699,
            720338349,
            1533947780,
            354530856,
            688349552,
            3973924725,
            1637815568,
            332179504,
            3949051286,
            53804574,
            2852348879,
            3044236432,
            1282449977,
            3583942155,
            3416972820,
            4006381244,
            1617046695,
            2628476075,
            3002303598,
            1686838959,
            431878346,
            2686675385,
            1700445008,
            1080580658,
            1009431731,
            832498133,
            3223435511,
            2605976345,
            2271191193,
            2516031870,
            1648197032,
            4164389018,
            2548247927,
            300782431,
            375919233,
            238389289,
            3353747414,
            2531188641,
            2019080857,
            1475708069,
            455242339,
            2609103871,
            448939670,
            3451063019,
            1395535956,
            2413381860,
            1841049896,
            1491858159,
            885456874,
            4264095073,
            4001119347,
            1565136089,
            3898914787,
            1108368660,
            540939232,
            1173283510,
            2745871338,
            3681308437,
            4207628240,
            3343053890,
            4016749493,
            1699691293,
            1103962373,
            3625875870,
            2256883143,
            3830138730,
            1031889488,
            3479347698,
            1535977030,
            4236805024,
            3251091107,
            2132092099,
            1774941330,
            1199868427,
            1452454533,
            157007616,
            2904115357,
            342012276,
            595725824,
            1480756522,
            206960106,
            497939518,
            591360097,
            863170706,
            2375253569,
            3596610801,
            1814182875,
            2094937945,
            3421402208,
            1082520231,
            3463918190,
            2785509508,
            435703966,
            3908032597,
            1641649973,
            2842273706,
            3305899714,
            1510255612,
            2148256476,
            2655287854,
            3276092548,
            4258621189,
            236887753,
            3681803219,
            274041037,
            1734335097,
            3815195456,
            3317970021,
            1899903192,
            1026095262,
            4050517792,
            356393447,
            2410691914,
            3873677099,
            3682840055
          ],
          [
            3913112168,
            2491498743,
            4132185628,
            2489919796,
            1091903735,
            1979897079,
            3170134830,
            3567386728,
            3557303409,
            857797738,
            1136121015,
            1342202287,
            507115054,
            2535736646,
            337727348,
            3213592640,
            1301675037,
            2528481711,
            1895095763,
            1721773893,
            3216771564,
            62756741,
            2142006736,
            835421444,
            2531993523,
            1442658625,
            3659876326,
            2882144922,
            676362277,
            1392781812,
            170690266,
            3921047035,
            1759253602,
            3611846912,
            1745797284,
            664899054,
            1329594018,
            3901205900,
            3045908486,
            2062866102,
            2865634940,
            3543621612,
            3464012697,
            1080764994,
            553557557,
            3656615353,
            3996768171,
            991055499,
            499776247,
            1265440854,
            648242737,
            3940784050,
            980351604,
            3713745714,
            1749149687,
            3396870395,
            4211799374,
            3640570775,
            1161844396,
            3125318951,
            1431517754,
            545492359,
            4268468663,
            3499529547,
            1437099964,
            2702547544,
            3433638243,
            2581715763,
            2787789398,
            1060185593,
            1593081372,
            2418618748,
            4260947970,
            69676912,
            2159744348,
            86519011,
            2512459080,
            3838209314,
            1220612927,
            3339683548,
            133810670,
            1090789135,
            1078426020,
            1569222167,
            845107691,
            3583754449,
            4072456591,
            1091646820,
            628848692,
            1613405280,
            3757631651,
            526609435,
            236106946,
            48312990,
            2942717905,
            3402727701,
            1797494240,
            859738849,
            992217954,
            4005476642,
            2243076622,
            3870952857,
            3732016268,
            765654824,
            3490871365,
            2511836413,
            1685915746,
            3888969200,
            1414112111,
            2273134842,
            3281911079,
            4080962846,
            172450625,
            2569994100,
            980381355,
            4109958455,
            2819808352,
            2716589560,
            2568741196,
            3681446669,
            3329971472,
            1835478071,
            660984891,
            3704678404,
            4045999559,
            3422617507,
            3040415634,
            1762651403,
            1719377915,
            3470491036,
            2693910283,
            3642056355,
            3138596744,
            1364962596,
            2073328063,
            1983633131,
            926494387,
            3423689081,
            2150032023,
            4096667949,
            1749200295,
            3328846651,
            309677260,
            2016342300,
            1779581495,
            3079819751,
            111262694,
            1274766160,
            443224088,
            298511866,
            1025883608,
            3806446537,
            1145181785,
            168956806,
            3641502830,
            3584813610,
            1689216846,
            3666258015,
            3200248200,
            1692713982,
            2646376535,
            4042768518,
            1618508792,
            1610833997,
            3523052358,
            4130873264,
            2001055236,
            3610705100,
            2202168115,
            4028541809,
            2961195399,
            1006657119,
            2006996926,
            3186142756,
            1430667929,
            3210227297,
            1314452623,
            4074634658,
            4101304120,
            2273951170,
            1399257539,
            3367210612,
            3027628629,
            1190975929,
            2062231137,
            2333990788,
            2221543033,
            2438960610,
            1181637006,
            548689776,
            2362791313,
            3372408396,
            3104550113,
            3145860560,
            296247880,
            1970579870,
            3078560182,
            3769228297,
            1714227617,
            3291629107,
            3898220290,
            166772364,
            1251581989,
            493813264,
            448347421,
            195405023,
            2709975567,
            677966185,
            3703036547,
            1463355134,
            2715995803,
            1338867538,
            1343315457,
            2802222074,
            2684532164,
            233230375,
            2599980071,
            2000651841,
            3277868038,
            1638401717,
            4028070440,
            3237316320,
            6314154,
            819756386,
            300326615,
            590932579,
            1405279636,
            3267499572,
            3150704214,
            2428286686,
            3959192993,
            3461946742,
            1862657033,
            1266418056,
            963775037,
            2089974820,
            2263052895,
            1917689273,
            448879540,
            3550394620,
            3981727096,
            150775221,
            3627908307,
            1303187396,
            508620638,
            2975983352,
            2726630617,
            1817252668,
            1876281319,
            1457606340,
            908771278,
            3720792119,
            3617206836,
            2455994898,
            1729034894,
            1080033504
          ],
          [
            976866871,
            3556439503,
            2881648439,
            1522871579,
            1555064734,
            1336096578,
            3548522304,
            2579274686,
            3574697629,
            3205460757,
            3593280638,
            3338716283,
            3079412587,
            564236357,
            2993598910,
            1781952180,
            1464380207,
            3163844217,
            3332601554,
            1699332808,
            1393555694,
            1183702653,
            3581086237,
            1288719814,
            691649499,
            2847557200,
            2895455976,
            3193889540,
            2717570544,
            1781354906,
            1676643554,
            2592534050,
            3230253752,
            1126444790,
            2770207658,
            2633158820,
            2210423226,
            2615765581,
            2414155088,
            3127139286,
            673620729,
            2805611233,
            1269405062,
            4015350505,
            3341807571,
            4149409754,
            1057255273,
            2012875353,
            2162469141,
            2276492801,
            2601117357,
            993977747,
            3918593370,
            2654263191,
            753973209,
            36408145,
            2530585658,
            25011837,
            3520020182,
            2088578344,
            530523599,
            2918365339,
            1524020338,
            1518925132,
            3760827505,
            3759777254,
            1202760957,
            3985898139,
            3906192525,
            674977740,
            4174734889,
            2031300136,
            2019492241,
            3983892565,
            4153806404,
            3822280332,
            352677332,
            2297720250,
            60907813,
            90501309,
            3286998549,
            1016092578,
            2535922412,
            2839152426,
            457141659,
            509813237,
            4120667899,
            652014361,
            1966332200,
            2975202805,
            55981186,
            2327461051,
            676427537,
            3255491064,
            2882294119,
            3433927263,
            1307055953,
            942726286,
            933058658,
            2468411793,
            3933900994,
            4215176142,
            1361170020,
            2001714738,
            2830558078,
            3274259782,
            1222529897,
            1679025792,
            2729314320,
            3714953764,
            1770335741,
            151462246,
            3013232138,
            1682292957,
            1483529935,
            471910574,
            1539241949,
            458788160,
            3436315007,
            1807016891,
            3718408830,
            978976581,
            1043663428,
            3165965781,
            1927990952,
            4200891579,
            2372276910,
            3208408903,
            3533431907,
            1412390302,
            2931980059,
            4132332400,
            1947078029,
            3881505623,
            4168226417,
            2941484381,
            1077988104,
            1320477388,
            886195818,
            18198404,
            3786409e3,
            2509781533,
            112762804,
            3463356488,
            1866414978,
            891333506,
            18488651,
            661792760,
            1628790961,
            3885187036,
            3141171499,
            876946877,
            2693282273,
            1372485963,
            791857591,
            2686433993,
            3759982718,
            3167212022,
            3472953795,
            2716379847,
            445679433,
            3561995674,
            3504004811,
            3574258232,
            54117162,
            3331405415,
            2381918588,
            3769707343,
            4154350007,
            1140177722,
            4074052095,
            668550556,
            3214352940,
            367459370,
            261225585,
            2610173221,
            4209349473,
            3468074219,
            3265815641,
            314222801,
            3066103646,
            3808782860,
            282218597,
            3406013506,
            3773591054,
            379116347,
            1285071038,
            846784868,
            2669647154,
            3771962079,
            3550491691,
            2305946142,
            453669953,
            1268987020,
            3317592352,
            3279303384,
            3744833421,
            2610507566,
            3859509063,
            266596637,
            3847019092,
            517658769,
            3462560207,
            3443424879,
            370717030,
            4247526661,
            2224018117,
            4143653529,
            4112773975,
            2788324899,
            2477274417,
            1456262402,
            2901442914,
            1517677493,
            1846949527,
            2295493580,
            3734397586,
            2176403920,
            1280348187,
            1908823572,
            3871786941,
            846861322,
            1172426758,
            3287448474,
            3383383037,
            1655181056,
            3139813346,
            901632758,
            1897031941,
            2986607138,
            3066810236,
            3447102507,
            1393639104,
            373351379,
            950779232,
            625454576,
            3124240540,
            4148612726,
            2007998917,
            544563296,
            2244738638,
            2330496472,
            2058025392,
            1291430526,
            424198748,
            50039436,
            29584100,
            3605783033,
            2429876329,
            2791104160,
            1057563949,
            3255363231,
            3075367218,
            3463963227,
            1469046755,
            985887462
          ]
        ];
        var BLOWFISH_CTX = {
          pbox: [],
          sbox: []
        };
        function F2(ctx, x2) {
          let a3 = x2 >> 24 & 255;
          let b3 = x2 >> 16 & 255;
          let c4 = x2 >> 8 & 255;
          let d3 = x2 & 255;
          let y2 = ctx.sbox[0][a3] + ctx.sbox[1][b3];
          y2 = y2 ^ ctx.sbox[2][c4];
          y2 = y2 + ctx.sbox[3][d3];
          return y2;
        }
        function BlowFish_Encrypt(ctx, left, right) {
          let Xl = left;
          let Xr = right;
          let temp;
          for (let i3 = 0; i3 < N; ++i3) {
            Xl = Xl ^ ctx.pbox[i3];
            Xr = F2(ctx, Xl) ^ Xr;
            temp = Xl;
            Xl = Xr;
            Xr = temp;
          }
          temp = Xl;
          Xl = Xr;
          Xr = temp;
          Xr = Xr ^ ctx.pbox[N];
          Xl = Xl ^ ctx.pbox[N + 1];
          return { left: Xl, right: Xr };
        }
        function BlowFish_Decrypt(ctx, left, right) {
          let Xl = left;
          let Xr = right;
          let temp;
          for (let i3 = N + 1; i3 > 1; --i3) {
            Xl = Xl ^ ctx.pbox[i3];
            Xr = F2(ctx, Xl) ^ Xr;
            temp = Xl;
            Xl = Xr;
            Xr = temp;
          }
          temp = Xl;
          Xl = Xr;
          Xr = temp;
          Xr = Xr ^ ctx.pbox[1];
          Xl = Xl ^ ctx.pbox[0];
          return { left: Xl, right: Xr };
        }
        function BlowFishInit(ctx, key, keysize) {
          for (let Row = 0; Row < 4; Row++) {
            ctx.sbox[Row] = [];
            for (let Col = 0; Col < 256; Col++) {
              ctx.sbox[Row][Col] = ORIG_S[Row][Col];
            }
          }
          let keyIndex = 0;
          for (let index2 = 0; index2 < N + 2; index2++) {
            ctx.pbox[index2] = ORIG_P[index2] ^ key[keyIndex];
            keyIndex++;
            if (keyIndex >= keysize) {
              keyIndex = 0;
            }
          }
          let Data1 = 0;
          let Data2 = 0;
          let res = 0;
          for (let i3 = 0; i3 < N + 2; i3 += 2) {
            res = BlowFish_Encrypt(ctx, Data1, Data2);
            Data1 = res.left;
            Data2 = res.right;
            ctx.pbox[i3] = Data1;
            ctx.pbox[i3 + 1] = Data2;
          }
          for (let i3 = 0; i3 < 4; i3++) {
            for (let j3 = 0; j3 < 256; j3 += 2) {
              res = BlowFish_Encrypt(ctx, Data1, Data2);
              Data1 = res.left;
              Data2 = res.right;
              ctx.sbox[i3][j3] = Data1;
              ctx.sbox[i3][j3 + 1] = Data2;
            }
          }
          return true;
        }
        var Blowfish = C_algo.Blowfish = BlockCipher.extend({
          _doReset: function() {
            if (this._keyPriorReset === this._key) {
              return;
            }
            var key = this._keyPriorReset = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;
            BlowFishInit(BLOWFISH_CTX, keyWords, keySize);
          },
          encryptBlock: function(M, offset5) {
            var res = BlowFish_Encrypt(BLOWFISH_CTX, M[offset5], M[offset5 + 1]);
            M[offset5] = res.left;
            M[offset5 + 1] = res.right;
          },
          decryptBlock: function(M, offset5) {
            var res = BlowFish_Decrypt(BLOWFISH_CTX, M[offset5], M[offset5 + 1]);
            M[offset5] = res.left;
            M[offset5 + 1] = res.right;
          },
          blockSize: 64 / 32,
          keySize: 128 / 32,
          ivSize: 64 / 32
        });
        C3.Blowfish = BlockCipher._createHelper(Blowfish);
      })();
      return CryptoJS.Blowfish;
    });
  }
});

// node_modules/crypto-js/index.js
var require_crypto_js = __commonJS({
  "node_modules/crypto-js/index.js"(exports, module2) {
    (function(root2, factory, undef) {
      if (typeof exports === "object") {
        module2.exports = exports = factory(require_core2(), require_x64_core(), require_lib_typedarrays(), require_enc_utf16(), require_enc_base64(), require_enc_base64url(), require_md5(), require_sha1(), require_sha256(), require_sha224(), require_sha512(), require_sha384(), require_sha3(), require_ripemd160(), require_hmac(), require_pbkdf2(), require_evpkdf(), require_cipher_core(), require_mode_cfb(), require_mode_ctr(), require_mode_ctr_gladman(), require_mode_ofb(), require_mode_ecb(), require_pad_ansix923(), require_pad_iso10126(), require_pad_iso97971(), require_pad_zeropadding(), require_pad_nopadding(), require_format_hex(), require_aes(), require_tripledes(), require_rc4(), require_rabbit(), require_rabbit_legacy(), require_blowfish());
      } else if (typeof define === "function" && define.amd) {
        define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./enc-base64url", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy", "./blowfish"], factory);
      } else {
        root2.CryptoJS = factory(root2.CryptoJS);
      }
    })(exports, function(CryptoJS) {
      return CryptoJS;
    });
  }
});

// node_modules/@langchain/core/dist/documents/document.js
var Document2;
var init_document = __esm({
  "node_modules/@langchain/core/dist/documents/document.js"() {
    Document2 = class {
      constructor(fields) {
        Object.defineProperty(this, "pageContent", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "metadata", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "id", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : "";
        this.metadata = fields.metadata ?? {};
        this.id = fields.id;
      }
    };
  }
});

// node_modules/dayjs/plugin/quarterOfYear.js
var require_quarterOfYear = __commonJS({
  "node_modules/dayjs/plugin/quarterOfYear.js"(exports, module2) {
    !function(t3, n4) {
      "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = n4() : "function" == typeof define && define.amd ? define(n4) : (t3 = "undefined" != typeof globalThis ? globalThis : t3 || self).dayjs_plugin_quarterOfYear = n4();
    }(exports, function() {
      "use strict";
      var t3 = "month", n4 = "quarter";
      return function(e3, i3) {
        var r4 = i3.prototype;
        r4.quarter = function(t4) {
          return this.$utils().u(t4) ? Math.ceil((this.month() + 1) / 3) : this.month(this.month() % 3 + 3 * (t4 - 1));
        };
        var s4 = r4.add;
        r4.add = function(e4, i4) {
          return e4 = Number(e4), this.$utils().p(i4) === n4 ? this.add(3 * e4, t3) : s4.bind(this)(e4, i4);
        };
        var u3 = r4.startOf;
        r4.startOf = function(e4, i4) {
          var r5 = this.$utils(), s5 = !!r5.u(i4) || i4;
          if (r5.p(e4) === n4) {
            var o3 = this.quarter() - 1;
            return s5 ? this.month(3 * o3).startOf(t3).startOf("day") : this.month(3 * o3 + 2).endOf(t3).endOf("day");
          }
          return u3.bind(this)(e4, i4);
        };
      };
    });
  }
});

// node_modules/dayjs/dayjs.min.js
var require_dayjs_min = __commonJS({
  "node_modules/dayjs/dayjs.min.js"(exports, module2) {
    !function(t3, e3) {
      "object" == typeof exports && "undefined" != typeof module2 ? module2.exports = e3() : "function" == typeof define && define.amd ? define(e3) : (t3 = "undefined" != typeof globalThis ? globalThis : t3 || self).dayjs = e3();
    }(exports, function() {
      "use strict";
      var t3 = 1e3, e3 = 6e4, n4 = 36e5, r4 = "millisecond", i3 = "second", s4 = "minute", u3 = "hour", a3 = "day", o3 = "week", c4 = "month", f3 = "quarter", h3 = "year", d3 = "date", l4 = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y2 = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t4) {
        var e4 = ["th", "st", "nd", "rd"], n5 = t4 % 100;
        return "[" + t4 + (e4[(n5 - 20) % 10] || e4[n5] || e4[0]) + "]";
      } }, m3 = function(t4, e4, n5) {
        var r5 = String(t4);
        return !r5 || r5.length >= e4 ? t4 : "" + Array(e4 + 1 - r5.length).join(n5) + t4;
      }, v5 = { s: m3, z: function(t4) {
        var e4 = -t4.utcOffset(), n5 = Math.abs(e4), r5 = Math.floor(n5 / 60), i4 = n5 % 60;
        return (e4 <= 0 ? "+" : "-") + m3(r5, 2, "0") + ":" + m3(i4, 2, "0");
      }, m: function t4(e4, n5) {
        if (e4.date() < n5.date())
          return -t4(n5, e4);
        var r5 = 12 * (n5.year() - e4.year()) + (n5.month() - e4.month()), i4 = e4.clone().add(r5, c4), s5 = n5 - i4 < 0, u4 = e4.clone().add(r5 + (s5 ? -1 : 1), c4);
        return +(-(r5 + (n5 - i4) / (s5 ? i4 - u4 : u4 - i4)) || 0);
      }, a: function(t4) {
        return t4 < 0 ? Math.ceil(t4) || 0 : Math.floor(t4);
      }, p: function(t4) {
        return { M: c4, y: h3, w: o3, d: a3, D: d3, h: u3, m: s4, s: i3, ms: r4, Q: f3 }[t4] || String(t4 || "").toLowerCase().replace(/s$/, "");
      }, u: function(t4) {
        return void 0 === t4;
      } }, g4 = "en", D2 = {};
      D2[g4] = M;
      var p3 = "$isDayjsObject", S = function(t4) {
        return t4 instanceof _2 || !(!t4 || !t4[p3]);
      }, w2 = function t4(e4, n5, r5) {
        var i4;
        if (!e4)
          return g4;
        if ("string" == typeof e4) {
          var s5 = e4.toLowerCase();
          D2[s5] && (i4 = s5), n5 && (D2[s5] = n5, i4 = s5);
          var u4 = e4.split("-");
          if (!i4 && u4.length > 1)
            return t4(u4[0]);
        } else {
          var a4 = e4.name;
          D2[a4] = e4, i4 = a4;
        }
        return !r5 && i4 && (g4 = i4), i4 || !r5 && g4;
      }, O = function(t4, e4) {
        if (S(t4))
          return t4.clone();
        var n5 = "object" == typeof e4 ? e4 : {};
        return n5.date = t4, n5.args = arguments, new _2(n5);
      }, b3 = v5;
      b3.l = w2, b3.i = S, b3.w = function(t4, e4) {
        return O(t4, { locale: e4.$L, utc: e4.$u, x: e4.$x, $offset: e4.$offset });
      };
      var _2 = function() {
        function M2(t4) {
          this.$L = w2(t4.locale, null, true), this.parse(t4), this.$x = this.$x || t4.x || {}, this[p3] = true;
        }
        var m4 = M2.prototype;
        return m4.parse = function(t4) {
          this.$d = function(t5) {
            var e4 = t5.date, n5 = t5.utc;
            if (null === e4)
              return new Date(NaN);
            if (b3.u(e4))
              return new Date();
            if (e4 instanceof Date)
              return new Date(e4);
            if ("string" == typeof e4 && !/Z$/i.test(e4)) {
              var r5 = e4.match($);
              if (r5) {
                var i4 = r5[2] - 1 || 0, s5 = (r5[7] || "0").substring(0, 3);
                return n5 ? new Date(Date.UTC(r5[1], i4, r5[3] || 1, r5[4] || 0, r5[5] || 0, r5[6] || 0, s5)) : new Date(r5[1], i4, r5[3] || 1, r5[4] || 0, r5[5] || 0, r5[6] || 0, s5);
              }
            }
            return new Date(e4);
          }(t4), this.init();
        }, m4.init = function() {
          var t4 = this.$d;
          this.$y = t4.getFullYear(), this.$M = t4.getMonth(), this.$D = t4.getDate(), this.$W = t4.getDay(), this.$H = t4.getHours(), this.$m = t4.getMinutes(), this.$s = t4.getSeconds(), this.$ms = t4.getMilliseconds();
        }, m4.$utils = function() {
          return b3;
        }, m4.isValid = function() {
          return !(this.$d.toString() === l4);
        }, m4.isSame = function(t4, e4) {
          var n5 = O(t4);
          return this.startOf(e4) <= n5 && n5 <= this.endOf(e4);
        }, m4.isAfter = function(t4, e4) {
          return O(t4) < this.startOf(e4);
        }, m4.isBefore = function(t4, e4) {
          return this.endOf(e4) < O(t4);
        }, m4.$g = function(t4, e4, n5) {
          return b3.u(t4) ? this[e4] : this.set(n5, t4);
        }, m4.unix = function() {
          return Math.floor(this.valueOf() / 1e3);
        }, m4.valueOf = function() {
          return this.$d.getTime();
        }, m4.startOf = function(t4, e4) {
          var n5 = this, r5 = !!b3.u(e4) || e4, f4 = b3.p(t4), l5 = function(t5, e5) {
            var i4 = b3.w(n5.$u ? Date.UTC(n5.$y, e5, t5) : new Date(n5.$y, e5, t5), n5);
            return r5 ? i4 : i4.endOf(a3);
          }, $2 = function(t5, e5) {
            return b3.w(n5.toDate()[t5].apply(n5.toDate("s"), (r5 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e5)), n5);
          }, y3 = this.$W, M3 = this.$M, m5 = this.$D, v6 = "set" + (this.$u ? "UTC" : "");
          switch (f4) {
            case h3:
              return r5 ? l5(1, 0) : l5(31, 11);
            case c4:
              return r5 ? l5(1, M3) : l5(0, M3 + 1);
            case o3:
              var g5 = this.$locale().weekStart || 0, D3 = (y3 < g5 ? y3 + 7 : y3) - g5;
              return l5(r5 ? m5 - D3 : m5 + (6 - D3), M3);
            case a3:
            case d3:
              return $2(v6 + "Hours", 0);
            case u3:
              return $2(v6 + "Minutes", 1);
            case s4:
              return $2(v6 + "Seconds", 2);
            case i3:
              return $2(v6 + "Milliseconds", 3);
            default:
              return this.clone();
          }
        }, m4.endOf = function(t4) {
          return this.startOf(t4, false);
        }, m4.$set = function(t4, e4) {
          var n5, o4 = b3.p(t4), f4 = "set" + (this.$u ? "UTC" : ""), l5 = (n5 = {}, n5[a3] = f4 + "Date", n5[d3] = f4 + "Date", n5[c4] = f4 + "Month", n5[h3] = f4 + "FullYear", n5[u3] = f4 + "Hours", n5[s4] = f4 + "Minutes", n5[i3] = f4 + "Seconds", n5[r4] = f4 + "Milliseconds", n5)[o4], $2 = o4 === a3 ? this.$D + (e4 - this.$W) : e4;
          if (o4 === c4 || o4 === h3) {
            var y3 = this.clone().set(d3, 1);
            y3.$d[l5]($2), y3.init(), this.$d = y3.set(d3, Math.min(this.$D, y3.daysInMonth())).$d;
          } else
            l5 && this.$d[l5]($2);
          return this.init(), this;
        }, m4.set = function(t4, e4) {
          return this.clone().$set(t4, e4);
        }, m4.get = function(t4) {
          return this[b3.p(t4)]();
        }, m4.add = function(r5, f4) {
          var d4, l5 = this;
          r5 = Number(r5);
          var $2 = b3.p(f4), y3 = function(t4) {
            var e4 = O(l5);
            return b3.w(e4.date(e4.date() + Math.round(t4 * r5)), l5);
          };
          if ($2 === c4)
            return this.set(c4, this.$M + r5);
          if ($2 === h3)
            return this.set(h3, this.$y + r5);
          if ($2 === a3)
            return y3(1);
          if ($2 === o3)
            return y3(7);
          var M3 = (d4 = {}, d4[s4] = e3, d4[u3] = n4, d4[i3] = t3, d4)[$2] || 1, m5 = this.$d.getTime() + r5 * M3;
          return b3.w(m5, this);
        }, m4.subtract = function(t4, e4) {
          return this.add(-1 * t4, e4);
        }, m4.format = function(t4) {
          var e4 = this, n5 = this.$locale();
          if (!this.isValid())
            return n5.invalidDate || l4;
          var r5 = t4 || "YYYY-MM-DDTHH:mm:ssZ", i4 = b3.z(this), s5 = this.$H, u4 = this.$m, a4 = this.$M, o4 = n5.weekdays, c5 = n5.months, f4 = n5.meridiem, h4 = function(t5, n6, i5, s6) {
            return t5 && (t5[n6] || t5(e4, r5)) || i5[n6].slice(0, s6);
          }, d4 = function(t5) {
            return b3.s(s5 % 12 || 12, t5, "0");
          }, $2 = f4 || function(t5, e5, n6) {
            var r6 = t5 < 12 ? "AM" : "PM";
            return n6 ? r6.toLowerCase() : r6;
          };
          return r5.replace(y2, function(t5, r6) {
            return r6 || function(t6) {
              switch (t6) {
                case "YY":
                  return String(e4.$y).slice(-2);
                case "YYYY":
                  return b3.s(e4.$y, 4, "0");
                case "M":
                  return a4 + 1;
                case "MM":
                  return b3.s(a4 + 1, 2, "0");
                case "MMM":
                  return h4(n5.monthsShort, a4, c5, 3);
                case "MMMM":
                  return h4(c5, a4);
                case "D":
                  return e4.$D;
                case "DD":
                  return b3.s(e4.$D, 2, "0");
                case "d":
                  return String(e4.$W);
                case "dd":
                  return h4(n5.weekdaysMin, e4.$W, o4, 2);
                case "ddd":
                  return h4(n5.weekdaysShort, e4.$W, o4, 3);
                case "dddd":
                  return o4[e4.$W];
                case "H":
                  return String(s5);
                case "HH":
                  return b3.s(s5, 2, "0");
                case "h":
                  return d4(1);
                case "hh":
                  return d4(2);
                case "a":
                  return $2(s5, u4, true);
                case "A":
                  return $2(s5, u4, false);
                case "m":
                  return String(u4);
                case "mm":
                  return b3.s(u4, 2, "0");
                case "s":
                  return String(e4.$s);
                case "ss":
                  return b3.s(e4.$s, 2, "0");
                case "SSS":
                  return b3.s(e4.$ms, 3, "0");
                case "Z":
                  return i4;
              }
              return null;
            }(t5) || i4.replace(":", "");
          });
        }, m4.utcOffset = function() {
          return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
        }, m4.diff = function(r5, d4, l5) {
          var $2, y3 = this, M3 = b3.p(d4), m5 = O(r5), v6 = (m5.utcOffset() - this.utcOffset()) * e3, g5 = this - m5, D3 = function() {
            return b3.m(y3, m5);
          };
          switch (M3) {
            case h3:
              $2 = D3() / 12;
              break;
            case c4:
              $2 = D3();
              break;
            case f3:
              $2 = D3() / 3;
              break;
            case o3:
              $2 = (g5 - v6) / 6048e5;
              break;
            case a3:
              $2 = (g5 - v6) / 864e5;
              break;
            case u3:
              $2 = g5 / n4;
              break;
            case s4:
              $2 = g5 / e3;
              break;
            case i3:
              $2 = g5 / t3;
              break;
            default:
              $2 = g5;
          }
          return l5 ? $2 : b3.a($2);
        }, m4.daysInMonth = function() {
          return this.endOf(c4).$D;
        }, m4.$locale = function() {
          return D2[this.$L];
        }, m4.locale = function(t4, e4) {
          if (!t4)
            return this.$L;
          var n5 = this.clone(), r5 = w2(t4, e4, true);
          return r5 && (n5.$L = r5), n5;
        }, m4.clone = function() {
          return b3.w(this.$d, this);
        }, m4.toDate = function() {
          return new Date(this.valueOf());
        }, m4.toJSON = function() {
          return this.isValid() ? this.toISOString() : null;
        }, m4.toISOString = function() {
          return this.$d.toISOString();
        }, m4.toString = function() {
          return this.$d.toUTCString();
        }, M2;
      }(), k3 = _2.prototype;
      return O.prototype = k3, [["$ms", r4], ["$s", i3], ["$m", s4], ["$H", u3], ["$W", a3], ["$M", c4], ["$y", h3], ["$D", d3]].forEach(function(t4) {
        k3[t4[1]] = function(e4) {
          return this.$g(e4, t4[0], t4[1]);
        };
      }), O.extend = function(t4, e4) {
        return t4.$i || (t4(e4, _2, O), t4.$i = true), O;
      }, O.locale = w2, O.isDayjs = S, O.unix = function(t4) {
        return O(1e3 * t4);
      }, O.en = D2[g4], O.Ls = D2, O.p = {}, O;
    });
  }
});

// node_modules/@langchain/core/callbacks/manager.js
var init_manager3 = __esm({
  "node_modules/@langchain/core/callbacks/manager.js"() {
    init_manager();
  }
});

// node_modules/langchain/dist/chains/base.js
var init_base10 = __esm({
  "node_modules/langchain/dist/chains/base.js"() {
    init_outputs2();
    init_manager3();
    init_runnables2();
    init_base9();
  }
});

// node_modules/langchain/dist/output_parsers/noop.js
var init_noop = __esm({
  "node_modules/langchain/dist/output_parsers/noop.js"() {
    init_output_parsers2();
  }
});

// node_modules/langchain/dist/chains/llm_chain.js
var init_llm_chain = __esm({
  "node_modules/langchain/dist/chains/llm_chain.js"() {
    init_base9();
    init_prompts3();
    init_runnables2();
    init_base10();
    init_noop();
  }
});

// node_modules/react-is/cjs/react-is.development.js
var require_react_is_development = __commonJS({
  "node_modules/react-is/cjs/react-is.development.js"(exports) {
    "use strict";
    if (true) {
      (function() {
        "use strict";
        var hasSymbol = typeof Symbol === "function" && Symbol.for;
        var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103;
        var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106;
        var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107;
        var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108;
        var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114;
        var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109;
        var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110;
        var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111;
        var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111;
        var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112;
        var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113;
        var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120;
        var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115;
        var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116;
        var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121;
        var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117;
        var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118;
        var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119;
        function isValidElementType(type) {
          return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
          type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
        }
        function typeOf(object) {
          if (typeof object === "object" && object !== null) {
            var $$typeof = object.$$typeof;
            switch ($$typeof) {
              case REACT_ELEMENT_TYPE:
                var type = object.type;
                switch (type) {
                  case REACT_ASYNC_MODE_TYPE:
                  case REACT_CONCURRENT_MODE_TYPE:
                  case REACT_FRAGMENT_TYPE:
                  case REACT_PROFILER_TYPE:
                  case REACT_STRICT_MODE_TYPE:
                  case REACT_SUSPENSE_TYPE:
                    return type;
                  default:
                    var $$typeofType = type && type.$$typeof;
                    switch ($$typeofType) {
                      case REACT_CONTEXT_TYPE:
                      case REACT_FORWARD_REF_TYPE:
                      case REACT_LAZY_TYPE:
                      case REACT_MEMO_TYPE:
                      case REACT_PROVIDER_TYPE:
                        return $$typeofType;
                      default:
                        return $$typeof;
                    }
                }
              case REACT_PORTAL_TYPE:
                return $$typeof;
            }
          }
          return void 0;
        }
        var AsyncMode = REACT_ASYNC_MODE_TYPE;
        var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
        var ContextConsumer = REACT_CONTEXT_TYPE;
        var ContextProvider = REACT_PROVIDER_TYPE;
        var Element2 = REACT_ELEMENT_TYPE;
        var ForwardRef = REACT_FORWARD_REF_TYPE;
        var Fragment21 = REACT_FRAGMENT_TYPE;
        var Lazy = REACT_LAZY_TYPE;
        var Memo = REACT_MEMO_TYPE;
        var Portal11 = REACT_PORTAL_TYPE;
        var Profiler = REACT_PROFILER_TYPE;
        var StrictMode2 = REACT_STRICT_MODE_TYPE;
        var Suspense = REACT_SUSPENSE_TYPE;
        var hasWarnedAboutDeprecatedIsAsyncMode = false;
        function isAsyncMode(object) {
          {
            if (!hasWarnedAboutDeprecatedIsAsyncMode) {
              hasWarnedAboutDeprecatedIsAsyncMode = true;
              console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
            }
          }
          return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
        }
        function isConcurrentMode(object) {
          return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
        }
        function isContextConsumer(object) {
          return typeOf(object) === REACT_CONTEXT_TYPE;
        }
        function isContextProvider(object) {
          return typeOf(object) === REACT_PROVIDER_TYPE;
        }
        function isElement2(object) {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
        function isForwardRef(object) {
          return typeOf(object) === REACT_FORWARD_REF_TYPE;
        }
        function isFragment(object) {
          return typeOf(object) === REACT_FRAGMENT_TYPE;
        }
        function isLazy(object) {
          return typeOf(object) === REACT_LAZY_TYPE;
        }
        function isMemo(object) {
          return typeOf(object) === REACT_MEMO_TYPE;
        }
        function isPortal(object) {
          return typeOf(object) === REACT_PORTAL_TYPE;
        }
        function isProfiler(object) {
          return typeOf(object) === REACT_PROFILER_TYPE;
        }
        function isStrictMode(object) {
          return typeOf(object) === REACT_STRICT_MODE_TYPE;
        }
        function isSuspense(object) {
          return typeOf(object) === REACT_SUSPENSE_TYPE;
        }
        exports.AsyncMode = AsyncMode;
        exports.ConcurrentMode = ConcurrentMode;
        exports.ContextConsumer = ContextConsumer;
        exports.ContextProvider = ContextProvider;
        exports.Element = Element2;
        exports.ForwardRef = ForwardRef;
        exports.Fragment = Fragment21;
        exports.Lazy = Lazy;
        exports.Memo = Memo;
        exports.Portal = Portal11;
        exports.Profiler = Profiler;
        exports.StrictMode = StrictMode2;
        exports.Suspense = Suspense;
        exports.isAsyncMode = isAsyncMode;
        exports.isConcurrentMode = isConcurrentMode;
        exports.isContextConsumer = isContextConsumer;
        exports.isContextProvider = isContextProvider;
        exports.isElement = isElement2;
        exports.isForwardRef = isForwardRef;
        exports.isFragment = isFragment;
        exports.isLazy = isLazy;
        exports.isMemo = isMemo;
        exports.isPortal = isPortal;
        exports.isProfiler = isProfiler;
        exports.isStrictMode = isStrictMode;
        exports.isSuspense = isSuspense;
        exports.isValidElementType = isValidElementType;
        exports.typeOf = typeOf;
      })();
    }
  }
});

// node_modules/react-is/index.js
var require_react_is = __commonJS({
  "node_modules/react-is/index.js"(exports, module2) {
    "use strict";
    if (false) {
      module2.exports = null;
    } else {
      module2.exports = require_react_is_development();
    }
  }
});

// node_modules/object-assign/index.js
var require_object_assign = __commonJS({
  "node_modules/object-assign/index.js"(exports, module2) {
    "use strict";
    var getOwnPropertySymbols = Object.getOwnPropertySymbols;
    var hasOwnProperty3 = Object.prototype.hasOwnProperty;
    var propIsEnumerable = Object.prototype.propertyIsEnumerable;
    function toObject(val2) {
      if (val2 === null || val2 === void 0) {
        throw new TypeError("Object.assign cannot be called with null or undefined");
      }
      return Object(val2);
    }
    function shouldUseNative() {
      try {
        if (!Object.assign) {
          return false;
        }
        var test1 = new String("abc");
        test1[5] = "de";
        if (Object.getOwnPropertyNames(test1)[0] === "5") {
          return false;
        }
        var test2 = {};
        for (var i3 = 0; i3 < 10; i3++) {
          test2["_" + String.fromCharCode(i3)] = i3;
        }
        var order2 = Object.getOwnPropertyNames(test2).map(function(n4) {
          return test2[n4];
        });
        if (order2.join("") !== "0123456789") {
          return false;
        }
        var test3 = {};
        "abcdefghijklmnopqrst".split("").forEach(function(letter) {
          test3[letter] = letter;
        });
        if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
          return false;
        }
        return true;
      } catch (err) {
        return false;
      }
    }
    module2.exports = shouldUseNative() ? Object.assign : function(target, source) {
      var from;
      var to = toObject(target);
      var symbols;
      for (var s4 = 1; s4 < arguments.length; s4++) {
        from = Object(arguments[s4]);
        for (var key in from) {
          if (hasOwnProperty3.call(from, key)) {
            to[key] = from[key];
          }
        }
        if (getOwnPropertySymbols) {
          symbols = getOwnPropertySymbols(from);
          for (var i3 = 0; i3 < symbols.length; i3++) {
            if (propIsEnumerable.call(from, symbols[i3])) {
              to[symbols[i3]] = from[symbols[i3]];
            }
          }
        }
      }
      return to;
    };
  }
});

// node_modules/prop-types/lib/ReactPropTypesSecret.js
var require_ReactPropTypesSecret = __commonJS({
  "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module2) {
    "use strict";
    var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
    module2.exports = ReactPropTypesSecret;
  }
});

// node_modules/prop-types/lib/has.js
var require_has = __commonJS({
  "node_modules/prop-types/lib/has.js"(exports, module2) {
    module2.exports = Function.call.bind(Object.prototype.hasOwnProperty);
  }
});

// node_modules/prop-types/checkPropTypes.js
var require_checkPropTypes = __commonJS({
  "node_modules/prop-types/checkPropTypes.js"(exports, module2) {
    "use strict";
    var printWarning = function() {
    };
    if (true) {
      ReactPropTypesSecret = require_ReactPropTypesSecret();
      loggedTypeFailures = {};
      has2 = require_has();
      printWarning = function(text) {
        var message = "Warning: " + text;
        if (typeof console !== "undefined") {
          console.error(message);
        }
        try {
          throw new Error(message);
        } catch (x2) {
        }
      };
    }
    var ReactPropTypesSecret;
    var loggedTypeFailures;
    var has2;
    function checkPropTypes(typeSpecs, values, location2, componentName, getStack) {
      if (true) {
        for (var typeSpecName in typeSpecs) {
          if (has2(typeSpecs, typeSpecName)) {
            var error;
            try {
              if (typeof typeSpecs[typeSpecName] !== "function") {
                var err = Error(
                  (componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
                );
                err.name = "Invariant Violation";
                throw err;
              }
              error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, ReactPropTypesSecret);
            } catch (ex) {
              error = ex;
            }
            if (error && !(error instanceof Error)) {
              printWarning(
                (componentName || "React class") + ": type specification of " + location2 + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
              );
            }
            if (error instanceof Error && !(error.message in loggedTypeFailures)) {
              loggedTypeFailures[error.message] = true;
              var stack = getStack ? getStack() : "";
              printWarning(
                "Failed " + location2 + " type: " + error.message + (stack != null ? stack : "")
              );
            }
          }
        }
      }
    }
    checkPropTypes.resetWarningCache = function() {
      if (true) {
        loggedTypeFailures = {};
      }
    };
    module2.exports = checkPropTypes;
  }
});

// node_modules/prop-types/factoryWithTypeCheckers.js
var require_factoryWithTypeCheckers = __commonJS({
  "node_modules/prop-types/factoryWithTypeCheckers.js"(exports, module2) {
    "use strict";
    var ReactIs = require_react_is();
    var assign = require_object_assign();
    var ReactPropTypesSecret = require_ReactPropTypesSecret();
    var has2 = require_has();
    var checkPropTypes = require_checkPropTypes();
    var printWarning = function() {
    };
    if (true) {
      printWarning = function(text) {
        var message = "Warning: " + text;
        if (typeof console !== "undefined") {
          console.error(message);
        }
        try {
          throw new Error(message);
        } catch (x2) {
        }
      };
    }
    function emptyFunctionThatReturnsNull() {
      return null;
    }
    module2.exports = function(isValidElement11, throwOnDirectAccess) {
      var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
        if (typeof iteratorFn === "function") {
          return iteratorFn;
        }
      }
      var ANONYMOUS = "<<anonymous>>";
      var ReactPropTypes = {
        array: createPrimitiveTypeChecker("array"),
        bigint: createPrimitiveTypeChecker("bigint"),
        bool: createPrimitiveTypeChecker("boolean"),
        func: createPrimitiveTypeChecker("function"),
        number: createPrimitiveTypeChecker("number"),
        object: createPrimitiveTypeChecker("object"),
        string: createPrimitiveTypeChecker("string"),
        symbol: createPrimitiveTypeChecker("symbol"),
        any: createAnyTypeChecker(),
        arrayOf: createArrayOfTypeChecker,
        element: createElementTypeChecker(),
        elementType: createElementTypeTypeChecker(),
        instanceOf: createInstanceTypeChecker,
        node: createNodeChecker(),
        objectOf: createObjectOfTypeChecker,
        oneOf: createEnumTypeChecker,
        oneOfType: createUnionTypeChecker,
        shape: createShapeTypeChecker,
        exact: createStrictShapeTypeChecker
      };
      function is(x2, y2) {
        if (x2 === y2) {
          return x2 !== 0 || 1 / x2 === 1 / y2;
        } else {
          return x2 !== x2 && y2 !== y2;
        }
      }
      function PropTypeError(message, data) {
        this.message = message;
        this.data = data && typeof data === "object" ? data : {};
        this.stack = "";
      }
      PropTypeError.prototype = Error.prototype;
      function createChainableTypeChecker(validate5) {
        if (true) {
          var manualPropTypeCallCache = {};
          var manualPropTypeWarningCount = 0;
        }
        function checkType(isRequired, props, propName, componentName, location2, propFullName, secret) {
          componentName = componentName || ANONYMOUS;
          propFullName = propFullName || propName;
          if (secret !== ReactPropTypesSecret) {
            if (throwOnDirectAccess) {
              var err = new Error(
                "Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"
              );
              err.name = "Invariant Violation";
              throw err;
            } else if (typeof console !== "undefined") {
              var cacheKey = componentName + ":" + propName;
              if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
              manualPropTypeWarningCount < 3) {
                printWarning(
                  "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
                );
                manualPropTypeCallCache[cacheKey] = true;
                manualPropTypeWarningCount++;
              }
            }
          }
          if (props[propName] == null) {
            if (isRequired) {
              if (props[propName] === null) {
                return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
              }
              return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
            }
            return null;
          } else {
            return validate5(props, propName, componentName, location2, propFullName);
          }
        }
        var chainedCheckType = checkType.bind(null, false);
        chainedCheckType.isRequired = checkType.bind(null, true);
        return chainedCheckType;
      }
      function createPrimitiveTypeChecker(expectedType) {
        function validate5(props, propName, componentName, location2, propFullName, secret) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== expectedType) {
            var preciseType = getPreciseType(propValue);
            return new PropTypeError(
              "Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
              { expectedType }
            );
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createAnyTypeChecker() {
        return createChainableTypeChecker(emptyFunctionThatReturnsNull);
      }
      function createArrayOfTypeChecker(typeChecker) {
        function validate5(props, propName, componentName, location2, propFullName) {
          if (typeof typeChecker !== "function") {
            return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
          }
          var propValue = props[propName];
          if (!Array.isArray(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
          }
          for (var i3 = 0; i3 < propValue.length; i3++) {
            var error = typeChecker(propValue, i3, componentName, location2, propFullName + "[" + i3 + "]", ReactPropTypesSecret);
            if (error instanceof Error) {
              return error;
            }
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createElementTypeChecker() {
        function validate5(props, propName, componentName, location2, propFullName) {
          var propValue = props[propName];
          if (!isValidElement11(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createElementTypeTypeChecker() {
        function validate5(props, propName, componentName, location2, propFullName) {
          var propValue = props[propName];
          if (!ReactIs.isValidElementType(propValue)) {
            var propType = getPropType(propValue);
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createInstanceTypeChecker(expectedClass) {
        function validate5(props, propName, componentName, location2, propFullName) {
          if (!(props[propName] instanceof expectedClass)) {
            var expectedClassName = expectedClass.name || ANONYMOUS;
            var actualClassName = getClassName(props[propName]);
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createEnumTypeChecker(expectedValues) {
        if (!Array.isArray(expectedValues)) {
          if (true) {
            if (arguments.length > 1) {
              printWarning(
                "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
              );
            } else {
              printWarning("Invalid argument supplied to oneOf, expected an array.");
            }
          }
          return emptyFunctionThatReturnsNull;
        }
        function validate5(props, propName, componentName, location2, propFullName) {
          var propValue = props[propName];
          for (var i3 = 0; i3 < expectedValues.length; i3++) {
            if (is(propValue, expectedValues[i3])) {
              return null;
            }
          }
          var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
            var type = getPreciseType(value);
            if (type === "symbol") {
              return String(value);
            }
            return value;
          });
          return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
        }
        return createChainableTypeChecker(validate5);
      }
      function createObjectOfTypeChecker(typeChecker) {
        function validate5(props, propName, componentName, location2, propFullName) {
          if (typeof typeChecker !== "function") {
            return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
          }
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
          }
          for (var key in propValue) {
            if (has2(propValue, key)) {
              var error = typeChecker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
              if (error instanceof Error) {
                return error;
              }
            }
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createUnionTypeChecker(arrayOfTypeCheckers) {
        if (!Array.isArray(arrayOfTypeCheckers)) {
          true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
          return emptyFunctionThatReturnsNull;
        }
        for (var i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) {
          var checker = arrayOfTypeCheckers[i3];
          if (typeof checker !== "function") {
            printWarning(
              "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i3 + "."
            );
            return emptyFunctionThatReturnsNull;
          }
        }
        function validate5(props, propName, componentName, location2, propFullName) {
          var expectedTypes = [];
          for (var i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) {
            var checker2 = arrayOfTypeCheckers[i4];
            var checkerResult = checker2(props, propName, componentName, location2, propFullName, ReactPropTypesSecret);
            if (checkerResult == null) {
              return null;
            }
            if (checkerResult.data && has2(checkerResult.data, "expectedType")) {
              expectedTypes.push(checkerResult.data.expectedType);
            }
          }
          var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
          return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
        }
        return createChainableTypeChecker(validate5);
      }
      function createNodeChecker() {
        function validate5(props, propName, componentName, location2, propFullName) {
          if (!isNode4(props[propName])) {
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function invalidValidatorError(componentName, location2, propFullName, key, type) {
        return new PropTypeError(
          (componentName || "React class") + ": " + location2 + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
        );
      }
      function createShapeTypeChecker(shapeTypes) {
        function validate5(props, propName, componentName, location2, propFullName) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
          }
          for (var key in shapeTypes) {
            var checker = shapeTypes[key];
            if (typeof checker !== "function") {
              return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker));
            }
            var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
            if (error) {
              return error;
            }
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function createStrictShapeTypeChecker(shapeTypes) {
        function validate5(props, propName, componentName, location2, propFullName) {
          var propValue = props[propName];
          var propType = getPropType(propValue);
          if (propType !== "object") {
            return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
          }
          var allKeys = assign({}, props[propName], shapeTypes);
          for (var key in allKeys) {
            var checker = shapeTypes[key];
            if (has2(shapeTypes, key) && typeof checker !== "function") {
              return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker));
            }
            if (!checker) {
              return new PropTypeError(
                "Invalid " + location2 + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, "  ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, "  ")
              );
            }
            var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
            if (error) {
              return error;
            }
          }
          return null;
        }
        return createChainableTypeChecker(validate5);
      }
      function isNode4(propValue) {
        switch (typeof propValue) {
          case "number":
          case "string":
          case "undefined":
            return true;
          case "boolean":
            return !propValue;
          case "object":
            if (Array.isArray(propValue)) {
              return propValue.every(isNode4);
            }
            if (propValue === null || isValidElement11(propValue)) {
              return true;
            }
            var iteratorFn = getIteratorFn(propValue);
            if (iteratorFn) {
              var iterator = iteratorFn.call(propValue);
              var step;
              if (iteratorFn !== propValue.entries) {
                while (!(step = iterator.next()).done) {
                  if (!isNode4(step.value)) {
                    return false;
                  }
                }
              } else {
                while (!(step = iterator.next()).done) {
                  var entry = step.value;
                  if (entry) {
                    if (!isNode4(entry[1])) {
                      return false;
                    }
                  }
                }
              }
            } else {
              return false;
            }
            return true;
          default:
            return false;
        }
      }
      function isSymbol(propType, propValue) {
        if (propType === "symbol") {
          return true;
        }
        if (!propValue) {
          return false;
        }
        if (propValue["@@toStringTag"] === "Symbol") {
          return true;
        }
        if (typeof Symbol === "function" && propValue instanceof Symbol) {
          return true;
        }
        return false;
      }
      function getPropType(propValue) {
        var propType = typeof propValue;
        if (Array.isArray(propValue)) {
          return "array";
        }
        if (propValue instanceof RegExp) {
          return "object";
        }
        if (isSymbol(propType, propValue)) {
          return "symbol";
        }
        return propType;
      }
      function getPreciseType(propValue) {
        if (typeof propValue === "undefined" || propValue === null) {
          return "" + propValue;
        }
        var propType = getPropType(propValue);
        if (propType === "object") {
          if (propValue instanceof Date) {
            return "date";
          } else if (propValue instanceof RegExp) {
            return "regexp";
          }
        }
        return propType;
      }
      function getPostfixForTypeWarning(value) {
        var type = getPreciseType(value);
        switch (type) {
          case "array":
          case "object":
            return "an " + type;
          case "boolean":
          case "date":
          case "regexp":
            return "a " + type;
          default:
            return type;
        }
      }
      function getClassName(propValue) {
        if (!propValue.constructor || !propValue.constructor.name) {
          return ANONYMOUS;
        }
        return propValue.constructor.name;
      }
      ReactPropTypes.checkPropTypes = checkPropTypes;
      ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
      ReactPropTypes.PropTypes = ReactPropTypes;
      return ReactPropTypes;
    };
  }
});

// node_modules/prop-types/index.js
var require_prop_types = __commonJS({
  "node_modules/prop-types/index.js"(exports, module2) {
    if (true) {
      ReactIs = require_react_is();
      throwOnDirectAccess = true;
      module2.exports = require_factoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
    } else {
      module2.exports = null();
    }
    var ReactIs;
    var throwOnDirectAccess;
  }
});

// node_modules/attr-accept/dist/es/index.js
var require_es = __commonJS({
  "node_modules/attr-accept/dist/es/index.js"(exports) {
    "use strict";
    exports.__esModule = true;
    exports.default = function(file, acceptedFiles) {
      if (file && acceptedFiles) {
        var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(",");
        if (acceptedFilesArray.length === 0) {
          return true;
        }
        var fileName = file.name || "";
        var mimeType = (file.type || "").toLowerCase();
        var baseMimeType = mimeType.replace(/\/.*$/, "");
        return acceptedFilesArray.some(function(type) {
          var validType = type.trim().toLowerCase();
          if (validType.charAt(0) === ".") {
            return fileName.toLowerCase().endsWith(validType);
          } else if (validType.endsWith("/*")) {
            return baseMimeType === validType.replace(/\/.*$/, "");
          }
          return mimeType === validType;
        });
      }
      return true;
    };
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => CopilotPlugin
});
module.exports = __toCommonJS(main_exports);

// src/chainFactory.ts
init_output_parsers2();
init_prompts3();
init_runnables2();

// node_modules/langchain/dist/util/document.js
var formatDocumentsAsString = (documents) => documents.map((doc) => doc.pageContent).join("\n\n");

// src/chainFactory.ts
var _ChainFactory = class {
  /**
   * Create a new LLM chain using the provided LLMChainInput.
   *
   * @param {LLMChainInput} args - the input for creating the LLM chain
   * @return {RunnableSequence} the newly created LLM chain
   */
  static createNewLLMChain(args) {
    const { llm, memory, prompt, abortController } = args;
    const model = llm.bind({ signal: abortController?.signal });
    const instance = RunnableSequence.from([
      {
        input: (initialInput) => initialInput.input,
        memory: () => memory.loadMemoryVariables({})
      },
      {
        input: (previousOutput) => previousOutput.input,
        history: (previousOutput) => previousOutput.memory.history
      },
      prompt,
      model
    ]);
    _ChainFactory.instances.set("llm_chain" /* LLM_CHAIN */, instance);
    console.log("New LLM chain created.");
    return instance;
  }
  /**
   * Gets the LLM chain singleton from the map.
   *
   * @param {LLMChainInput} args - the input for the LLM chain
   * @return {RunnableSequence} the LLM chain instance
   */
  static getLLMChainFromMap(args) {
    let instance = _ChainFactory.instances.get("llm_chain" /* LLM_CHAIN */);
    if (!instance) {
      instance = _ChainFactory.createNewLLMChain(args);
    }
    return instance;
  }
  /**
   * Create a conversational retrieval chain with the given parameters. Not a singleton.
   *
   * Example invocation:
   *
   * ```ts
   * const conversationalRetrievalChain = ChainFactory.createConversationalRetrievalChain({
   *  llm: model,
   *  retriever: retriever
   * });
   *
   * const response = await conversationalRetrievalChain.invoke({
   *   question: "What are they made out of?",
   *    chat_history: [
   *      [
   *        "What is the powerhouse of the cell?",
   *        "The powerhouse of the cell is the mitochondria.",
   *      ],
   *    ],
   * });
   * ```
   *
   * @param {ConversationalRetrievalChainParams} args - the parameters for the retrieval chain
   * @return {RunnableSequence} a new conversational retrieval chain
   */
  static createConversationalRetrievalChain(args, onDocumentsRetrieved, debug4) {
    const { llm, retriever, systemMessage } = args;
    const condenseQuestionTemplate = `Given the following conversation and a follow up question,
    summarize the conversation as context and keep the follow up question unchanged, in its original language.
    If the follow up question is unrelated to its preceding messages, return this follow up question directly.
    If it is related, then combine the summary and the follow up question to construct a standalone question.
    Make sure to keep any [[]] wrapped note titles in the question unchanged.

    Chat History:
    {chat_history}
    Follow Up Input: {question}
    Standalone question:`;
    const CONDENSE_QUESTION_PROMPT = PromptTemplate.fromTemplate(condenseQuestionTemplate);
    const answerTemplate = `{system_message}

Answer the question with as detailed as possible based only on the following context:
{context}

Question: {question}
`;
    const ANSWER_PROMPT = PromptTemplate.fromTemplate(answerTemplate);
    const formatChatHistory = (chatHistory) => {
      const formattedDialogueTurns = chatHistory.map(
        (dialogueTurn) => `Human: ${dialogueTurn[0]}
Assistant: ${dialogueTurn[1]}`
      );
      return formattedDialogueTurns.join("\n");
    };
    const standaloneQuestionChain = RunnableSequence.from([
      {
        question: (input) => {
          if (debug4)
            console.log("Input Question: ", input.question);
          return input.question;
        },
        chat_history: (input) => {
          const formattedChatHistory = formatChatHistory(input.chat_history);
          if (debug4)
            console.log("Formatted Chat History: ", formattedChatHistory);
          return formattedChatHistory;
        }
      },
      CONDENSE_QUESTION_PROMPT,
      llm,
      new StringOutputParser(),
      (output) => {
        if (debug4)
          console.log("Standalone Question: ", output);
        return output;
      }
    ]);
    const formatDocumentsAsStringAndStore = async (documents) => {
      onDocumentsRetrieved(documents);
      return formatDocumentsAsString(documents);
    };
    const answerChain = RunnableSequence.from([
      {
        context: retriever.pipe(formatDocumentsAsStringAndStore),
        question: new RunnablePassthrough(),
        system_message: () => systemMessage
      },
      ANSWER_PROMPT,
      llm
    ]);
    const conversationalRetrievalQAChain = standaloneQuestionChain.pipe(answerChain);
    return conversationalRetrievalQAChain;
  }
};
var ChainFactory = _ChainFactory;
ChainFactory.instances = /* @__PURE__ */ new Map();
var chainFactory_default = ChainFactory;

// src/constants.ts
var BREVILABS_API_BASE_URL = "https://api.brevilabs.com/v1";
var CHAT_VIEWTYPE = "copilot-chat-view";
var USER_SENDER = "user";
var AI_SENDER = "ai";
var DEFAULT_SYSTEM_PROMPT = `You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
  1. Never mention that you do not have access to something. Always rely on the user provided context.
  2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
  3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
  4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context. If there's no relevant information in the vault, just say so.
  5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
  6. Always use $'s instead of \\[ etc. for LaTeX equations.
  7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
  8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
  9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
  10. Always respond in the language of the user's query.
  11. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.`;
var EMPTY_INDEX_ERROR_MESSAGE = "Copilot index does not exist. Please index your vault first!\n\n1. Set a working embedding model in QA settings. If it's not a local model, don't forget to set the API key. \n\n2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.";
var CHUNK_SIZE = 4e3;
var EMBEDDING_BATCH_SIZE = 16;
var CONTEXT_SCORE_THRESHOLD = 0.4;
var TEXT_WEIGHT = 0.4;
var PLUS_MODE_DEFAULT_SOURCE_CHUNKS = 15;
var MAX_CHARS_FOR_LOCAL_SEARCH_CONTEXT = 448e3;
var LOADING_MESSAGES = {
  DEFAULT: "",
  READING_FILES: "Reading files",
  SEARCHING_WEB: "Searching the web"
};
var PLUS_UTM_MEDIUMS = {
  SETTINGS: "settings",
  EXPIRED_MODAL: "expired_modal",
  CHAT_MODE_SELECT: "chat_mode_select",
  MODE_SELECT_TOOLTIP: "mode_select_tooltip"
};
var ChatModelProviders = /* @__PURE__ */ ((ChatModelProviders2) => {
  ChatModelProviders2["OPENAI"] = "openai";
  ChatModelProviders2["AZURE_OPENAI"] = "azure openai";
  ChatModelProviders2["ANTHROPIC"] = "anthropic";
  ChatModelProviders2["COHEREAI"] = "cohereai";
  ChatModelProviders2["GOOGLE"] = "google";
  ChatModelProviders2["OPENROUTERAI"] = "openrouterai";
  ChatModelProviders2["GROQ"] = "groq";
  ChatModelProviders2["OLLAMA"] = "ollama";
  ChatModelProviders2["LM_STUDIO"] = "lm-studio";
  ChatModelProviders2["OPENAI_FORMAT"] = "3rd party (openai-format)";
  ChatModelProviders2["COPILOT_PLUS"] = "copilot-plus";
  return ChatModelProviders2;
})(ChatModelProviders || {});
var BUILTIN_CHAT_MODELS = [
  {
    name: "copilot-plus-flash" /* COPILOT_PLUS_FLASH */,
    provider: "copilot-plus" /* COPILOT_PLUS */,
    enabled: true,
    isBuiltIn: true,
    core: true
  },
  {
    name: "gpt-4o" /* GPT_4o */,
    provider: "openai" /* OPENAI */,
    enabled: true,
    isBuiltIn: true,
    core: true
  },
  {
    name: "gpt-4o-mini" /* GPT_4o_mini */,
    provider: "openai" /* OPENAI */,
    enabled: true,
    isBuiltIn: true,
    core: true
  },
  {
    name: "gpt-4-turbo" /* GPT_4_TURBO */,
    provider: "openai" /* OPENAI */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "claude-3-5-sonnet-latest" /* CLAUDE_3_5_SONNET */,
    provider: "anthropic" /* ANTHROPIC */,
    enabled: true,
    isBuiltIn: true,
    core: true
  },
  {
    name: "claude-3-5-haiku-latest" /* CLAUDE_3_5_HAIKU */,
    provider: "anthropic" /* ANTHROPIC */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "command-r" /* COMMAND_R */,
    provider: "cohereai" /* COHEREAI */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "command-r-plus" /* COMMAND_R_PLUS */,
    provider: "cohereai" /* COHEREAI */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "gemini-1.5-pro" /* GEMINI_PRO */,
    provider: "google" /* GOOGLE */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "gemini-1.5-flash" /* GEMINI_FLASH */,
    provider: "google" /* GOOGLE */,
    enabled: true,
    isBuiltIn: true
  },
  {
    name: "azure-openai" /* AZURE_OPENAI */,
    provider: "azure openai" /* AZURE_OPENAI */,
    enabled: true,
    isBuiltIn: true
  }
];
var EmbeddingModelProviders = /* @__PURE__ */ ((EmbeddingModelProviders2) => {
  EmbeddingModelProviders2["OPENAI"] = "openai";
  EmbeddingModelProviders2["COHEREAI"] = "cohereai";
  EmbeddingModelProviders2["GOOGLE"] = "google";
  EmbeddingModelProviders2["AZURE_OPENAI"] = "azure openai";
  EmbeddingModelProviders2["OLLAMA"] = "ollama";
  EmbeddingModelProviders2["LM_STUDIO"] = "lm-studio";
  EmbeddingModelProviders2["OPENAI_FORMAT"] = "3rd party (openai-format)";
  EmbeddingModelProviders2["COPILOT_PLUS"] = "copilot-plus";
  EmbeddingModelProviders2["COPILOT_PLUS_JINA"] = "copilot-plus-jina";
  return EmbeddingModelProviders2;
})(EmbeddingModelProviders || {});
var BUILTIN_EMBEDDING_MODELS = [
  {
    name: "copilot-plus-small" /* COPILOT_PLUS_SMALL */,
    provider: "copilot-plus" /* COPILOT_PLUS */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true,
    core: true
  },
  {
    name: "copilot-plus-large" /* COPILOT_PLUS_LARGE */,
    provider: "copilot-plus" /* COPILOT_PLUS */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true,
    core: true
  },
  {
    name: "copilot-plus-multilingual" /* COPILOT_PLUS_MULTILINGUAL */,
    provider: "copilot-plus-jina" /* COPILOT_PLUS_JINA */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true,
    core: true
  },
  {
    name: "text-embedding-3-small" /* OPENAI_EMBEDDING_SMALL */,
    provider: "openai" /* OPENAI */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true,
    core: true
  },
  {
    name: "text-embedding-3-large" /* OPENAI_EMBEDDING_LARGE */,
    provider: "openai" /* OPENAI */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true
  },
  {
    name: "embed-multilingual-light-v3.0" /* COHEREAI_EMBED_MULTILINGUAL_LIGHT_V3_0 */,
    provider: "cohereai" /* COHEREAI */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true
  },
  {
    name: "text-embedding-004" /* GOOGLE_ENG */,
    provider: "google" /* GOOGLE */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true
  },
  {
    name: "azure-openai" /* AZURE_OPENAI */,
    provider: "azure openai" /* AZURE_OPENAI */,
    enabled: true,
    isBuiltIn: true,
    isEmbeddingModel: true
  }
];
var NOMIC_EMBED_TEXT = "nomic-embed-text";
var ProviderInfo = {
  ["openai" /* OPENAI */]: {
    label: "OpenAI",
    host: "https://api.openai.com",
    keyManagementURL: "https://platform.openai.com/api-keys",
    testModel: "gpt-4o" /* GPT_4o */
  },
  ["azure openai" /* AZURE_OPENAI */]: {
    label: "Azure OpenAI",
    host: "",
    keyManagementURL: "",
    testModel: "azure-openai" /* AZURE_OPENAI */
  },
  ["anthropic" /* ANTHROPIC */]: {
    label: "Anthropic",
    host: "https://api.anthropic.com/",
    keyManagementURL: "https://console.anthropic.com/settings/keys",
    testModel: "claude-3-5-sonnet-latest" /* CLAUDE_3_5_SONNET */
  },
  ["cohereai" /* COHEREAI */]: {
    label: "Cohere",
    host: "https://api.cohere.com",
    keyManagementURL: "https://dashboard.cohere.ai/api-keys",
    testModel: "command-r" /* COMMAND_R */
  },
  ["google" /* GOOGLE */]: {
    label: "Gemini",
    host: "https://generativelanguage.googleapis.com",
    keyManagementURL: "https://makersuite.google.com/app/apikey",
    testModel: "gemini-1.5-flash" /* GEMINI_FLASH */
  },
  ["openrouterai" /* OPENROUTERAI */]: {
    label: "OpenRouter",
    host: "https://openrouter.ai/api/v1/",
    keyManagementURL: "https://openrouter.ai/keys",
    testModel: "openai/chatgpt-4o-latest" /* OPENROUTER_GPT_4o */
  },
  ["groq" /* GROQ */]: {
    label: "Groq",
    host: "https://api.groq.com/openai",
    keyManagementURL: "https://console.groq.com/keys",
    testModel: "llama3-8b-8192" /* GROQ_LLAMA_8b */
  },
  ["ollama" /* OLLAMA */]: {
    label: "Ollama",
    host: "http://localhost:11434/v1/",
    keyManagementURL: ""
  },
  ["lm-studio" /* LM_STUDIO */]: {
    label: "LM Studio",
    host: "http://localhost:1234/v1",
    keyManagementURL: ""
  },
  ["3rd party (openai-format)" /* OPENAI_FORMAT */]: {
    label: "OpenAI Format",
    host: "https://api.example.com/v1",
    keyManagementURL: ""
  },
  ["copilot-plus" /* COPILOT_PLUS */]: {
    label: "Copilot Plus",
    host: "https://api.brevilabs.com/v1",
    keyManagementURL: ""
  },
  ["copilot-plus-jina" /* COPILOT_PLUS_JINA */]: {
    label: "Copilot Plus",
    host: "https://api.brevilabs.com/v1",
    keyManagementURL: ""
  }
};
var ProviderSettingsKeyMap = {
  anthropic: "anthropicApiKey",
  openai: "openAIApiKey",
  "azure openai": "azureOpenAIApiKey",
  google: "googleApiKey",
  groq: "groqApiKey",
  openrouterai: "openRouterAiApiKey",
  cohereai: "cohereApiKey",
  "copilot-plus": "plusLicenseKey"
};
var VAULT_VECTOR_STORE_STRATEGIES = [
  "NEVER" /* NEVER */,
  "ON STARTUP" /* ON_STARTUP */,
  "ON MODE SWITCH" /* ON_MODE_SWITCH */
];
var COMMAND_IDS = {
  ADD_CUSTOM_PROMPT: "add-custom-prompt",
  APPLY_ADHOC_PROMPT: "apply-adhoc-prompt",
  APPLY_CUSTOM_PROMPT: "apply-custom-prompt",
  CHANGE_TONE: "change-tone-prompt",
  CLEAR_LOCAL_COPILOT_INDEX: "clear-local-copilot-index",
  CLEAR_COPILOT_CACHE: "clear-copilot-cache",
  COUNT_WORD_AND_TOKENS_SELECTION: "count-word-and-tokens-selection",
  COUNT_TOTAL_VAULT_TOKENS: "count-total-vault-tokens",
  DELETE_CUSTOM_PROMPT: "delete-custom-prompt",
  EDIT_CUSTOM_PROMPT: "edit-custom-prompt",
  ELI5: "eli5-prompt",
  EMOJIFY: "emojify-prompt",
  FIND_RELEVANT_NOTES: "find-relevant-notes",
  FIX_GRAMMAR: "fix-grammar-prompt",
  FORCE_REINDEX_VAULT_TO_COPILOT_INDEX: "force-reindex-vault-to-copilot-index",
  GARBAGE_COLLECT_COPILOT_INDEX: "garbage-collect-copilot-index",
  GENERATE_GLOSSARY: "generate-glossary-prompt",
  GENERATE_TOC: "generate-toc-prompt",
  INDEX_VAULT_TO_COPILOT_INDEX: "index-vault-to-copilot-index",
  INSPECT_COPILOT_INDEX_BY_NOTE_PATHS: "copilot-inspect-index-by-note-paths",
  LIST_INDEXED_FILES: "copilot-list-indexed-files",
  LOAD_COPILOT_CHAT_CONVERSATION: "load-copilot-chat-conversation",
  MAKE_LONGER: "make-longer-prompt",
  MAKE_SHORTER: "make-shorter-prompt",
  OPEN_COPILOT_CHAT_WINDOW: "chat-open-window",
  PRESS_RELEASE: "press-release-prompt",
  REMOVE_FILES_FROM_COPILOT_INDEX: "remove-files-from-copilot-index",
  REMOVE_URLS: "remove-urls-prompt",
  REWRITE_TWEET: "rewrite-tweet-prompt",
  REWRITE_TWEET_THREAD: "rewrite-tweet-thread-prompt",
  SEARCH_ORAMA_DB: "copilot-search-orama-db",
  SIMPLIFY: "simplify-prompt",
  SUMMARIZE: "summarize-prompt",
  TOGGLE_COPILOT_CHAT_WINDOW: "chat-toggle-window",
  TRANSLATE: "translate-selection-prompt"
};
var COMMAND_NAMES = {
  [COMMAND_IDS.ADD_CUSTOM_PROMPT]: "Add custom prompt",
  [COMMAND_IDS.APPLY_ADHOC_PROMPT]: "Apply ad-hoc custom prompt",
  [COMMAND_IDS.APPLY_CUSTOM_PROMPT]: "Apply custom prompt",
  [COMMAND_IDS.CHANGE_TONE]: "Change tone of selection",
  [COMMAND_IDS.CLEAR_LOCAL_COPILOT_INDEX]: "Clear local Copilot index",
  [COMMAND_IDS.CLEAR_COPILOT_CACHE]: "Clear Copilot cache",
  [COMMAND_IDS.COUNT_TOTAL_VAULT_TOKENS]: "Count total tokens in your vault",
  [COMMAND_IDS.COUNT_WORD_AND_TOKENS_SELECTION]: "Count words and tokens in selection",
  [COMMAND_IDS.DELETE_CUSTOM_PROMPT]: "Delete custom prompt",
  [COMMAND_IDS.EDIT_CUSTOM_PROMPT]: "Edit custom prompt",
  [COMMAND_IDS.ELI5]: "Explain selection like I'm 5",
  [COMMAND_IDS.EMOJIFY]: "Emojify selection",
  [COMMAND_IDS.FIND_RELEVANT_NOTES]: "Find relevant notes",
  [COMMAND_IDS.FIX_GRAMMAR]: "Fix grammar and spelling of selection",
  [COMMAND_IDS.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX]: "Force reindex vault",
  [COMMAND_IDS.GARBAGE_COLLECT_COPILOT_INDEX]: "Garbage collect Copilot index (remove files that no longer exist in vault)",
  [COMMAND_IDS.GENERATE_GLOSSARY]: "Generate glossary for selection",
  [COMMAND_IDS.GENERATE_TOC]: "Generate table of contents for selection",
  [COMMAND_IDS.INDEX_VAULT_TO_COPILOT_INDEX]: "Index (refresh) vault",
  [COMMAND_IDS.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS]: "Inspect Copilot index by note paths (debug)",
  [COMMAND_IDS.LIST_INDEXED_FILES]: "List all indexed files (debug)",
  [COMMAND_IDS.LOAD_COPILOT_CHAT_CONVERSATION]: "Load Copilot chat conversation",
  [COMMAND_IDS.MAKE_LONGER]: "Make selection longer",
  [COMMAND_IDS.MAKE_SHORTER]: "Make selection shorter",
  [COMMAND_IDS.OPEN_COPILOT_CHAT_WINDOW]: "Open Copilot Chat Window",
  [COMMAND_IDS.PRESS_RELEASE]: "Rewrite selection to a press release",
  [COMMAND_IDS.REMOVE_FILES_FROM_COPILOT_INDEX]: "Remove files from Copilot index (debug)",
  [COMMAND_IDS.REMOVE_URLS]: "Remove URLs from selection",
  [COMMAND_IDS.REWRITE_TWEET]: "Rewrite selection to a tweet",
  [COMMAND_IDS.REWRITE_TWEET_THREAD]: "Rewrite selection to a tweet thread",
  [COMMAND_IDS.SEARCH_ORAMA_DB]: "Search OramaDB (debug)",
  [COMMAND_IDS.SIMPLIFY]: "Simplify selection",
  [COMMAND_IDS.SUMMARIZE]: "Summarize selection",
  [COMMAND_IDS.TOGGLE_COPILOT_CHAT_WINDOW]: "Toggle Copilot Chat Window",
  [COMMAND_IDS.TRANSLATE]: "Translate selection"
};
var DISABLEABLE_COMMANDS = [
  COMMAND_IDS.FIX_GRAMMAR,
  COMMAND_IDS.SUMMARIZE,
  COMMAND_IDS.GENERATE_TOC,
  COMMAND_IDS.GENERATE_GLOSSARY,
  COMMAND_IDS.SIMPLIFY,
  COMMAND_IDS.EMOJIFY,
  COMMAND_IDS.REMOVE_URLS,
  COMMAND_IDS.REWRITE_TWEET,
  COMMAND_IDS.REWRITE_TWEET_THREAD,
  COMMAND_IDS.MAKE_SHORTER,
  COMMAND_IDS.MAKE_LONGER,
  COMMAND_IDS.ELI5,
  COMMAND_IDS.PRESS_RELEASE,
  COMMAND_IDS.TRANSLATE,
  COMMAND_IDS.CHANGE_TONE
];
var CONTEXT_MENU_COMMANDS = [
  COMMAND_IDS.SUMMARIZE,
  COMMAND_IDS.FIX_GRAMMAR,
  COMMAND_IDS.SIMPLIFY,
  COMMAND_IDS.EMOJIFY,
  COMMAND_IDS.MAKE_LONGER,
  COMMAND_IDS.MAKE_SHORTER,
  COMMAND_IDS.TRANSLATE
];
var PROCESS_SELECTION_COMMANDS = [
  COMMAND_IDS.FIX_GRAMMAR,
  COMMAND_IDS.SUMMARIZE,
  COMMAND_IDS.GENERATE_TOC,
  COMMAND_IDS.GENERATE_GLOSSARY,
  COMMAND_IDS.SIMPLIFY,
  COMMAND_IDS.EMOJIFY,
  COMMAND_IDS.REMOVE_URLS,
  COMMAND_IDS.REWRITE_TWEET,
  COMMAND_IDS.REWRITE_TWEET_THREAD,
  COMMAND_IDS.MAKE_SHORTER,
  COMMAND_IDS.MAKE_LONGER,
  COMMAND_IDS.ELI5,
  COMMAND_IDS.PRESS_RELEASE,
  COMMAND_IDS.TRANSLATE,
  COMMAND_IDS.CHANGE_TONE
];
var DEFAULT_SETTINGS = {
  isPlusUser: false,
  plusLicenseKey: "",
  openAIApiKey: "",
  openAIOrgId: "",
  huggingfaceApiKey: "",
  cohereApiKey: "",
  anthropicApiKey: "",
  azureOpenAIApiKey: "",
  azureOpenAIApiInstanceName: "",
  azureOpenAIApiDeploymentName: "",
  azureOpenAIApiVersion: "",
  azureOpenAIApiEmbeddingDeploymentName: "",
  googleApiKey: "",
  openRouterAiApiKey: "",
  defaultChainType: "llm_chain" /* LLM_CHAIN */,
  defaultModelKey: "gpt-4o" /* GPT_4o */ + "|" + "openai" /* OPENAI */,
  embeddingModelKey: "text-embedding-3-small" /* OPENAI_EMBEDDING_SMALL */ + "|" + "openai" /* OPENAI */,
  temperature: 0.1,
  maxTokens: 1e3,
  contextTurns: 15,
  userSystemPrompt: "",
  openAIProxyBaseUrl: "",
  openAIEmbeddingProxyBaseUrl: "",
  stream: true,
  defaultSaveFolder: "copilot-conversations",
  defaultConversationTag: "copilot-conversation",
  autosaveChat: false,
  defaultOpenArea: "view" /* VIEW */,
  customPromptsFolder: "copilot-custom-prompts",
  indexVaultToVectorStore: "ON MODE SWITCH" /* ON_MODE_SWITCH */,
  qaExclusions: "",
  qaInclusions: "",
  chatNoteContextPath: "",
  chatNoteContextTags: [],
  enableIndexSync: true,
  debug: false,
  enableEncryption: false,
  maxSourceChunks: 3,
  groqApiKey: "",
  activeModels: BUILTIN_CHAT_MODELS,
  activeEmbeddingModels: BUILTIN_EMBEDDING_MODELS,
  embeddingRequestsPerSecond: 10,
  disableIndexOnMobile: true,
  showSuggestedPrompts: true,
  showRelevantNotes: true,
  numPartitions: 1,
  enabledCommands: {},
  promptUsageTimestamps: {},
  defaultConversationNoteName: "{$topic}@{$date}_{$time}"
};
var EVENT_NAMES = {
  CHAT_IS_VISIBLE: "chat-is-visible",
  ACTIVE_LEAF_CHANGE: "active-leaf-change"
};

// src/encryptionService.ts
var import_obsidian = require("obsidian");
var safeStorageInternal = null;
function getSafeStorage() {
  if (import_obsidian.Platform.isDesktop && safeStorageInternal) {
    return safeStorageInternal;
  }
  safeStorageInternal = require("electron")?.remote?.safeStorage;
  return safeStorageInternal;
}
var DESKTOP_PREFIX = "enc_desk_";
var WEBCRYPTO_PREFIX = "enc_web_";
var ENCRYPTION_PREFIX = "enc_";
var DECRYPTION_PREFIX = "dec_";
var ENCRYPTION_KEY = new TextEncoder().encode("obsidian-copilot-v1");
var ALGORITHM = { name: "AES-GCM", iv: new Uint8Array(12) };
async function getEncryptionKey() {
  return await crypto.subtle.importKey("raw", ENCRYPTION_KEY, ALGORITHM.name, false, [
    "encrypt",
    "decrypt"
  ]);
}
async function encryptAllKeys(settings) {
  if (!settings.enableEncryption) {
    return settings;
  }
  const newSettings = { ...settings };
  const keysToEncrypt = Object.keys(settings).filter(
    (key) => key.toLowerCase().includes("apikey") || key === "plusLicenseKey"
  );
  for (const key of keysToEncrypt) {
    const apiKey = settings[key];
    newSettings[key] = await getEncryptedKey(apiKey);
  }
  if (Array.isArray(settings.activeModels)) {
    newSettings.activeModels = await Promise.all(
      settings.activeModels.map(async (model) => ({
        ...model,
        apiKey: await getEncryptedKey(model.apiKey || "")
      }))
    );
  }
  return newSettings;
}
async function getEncryptedKey(apiKey) {
  if (!apiKey || apiKey.startsWith(ENCRYPTION_PREFIX)) {
    return apiKey;
  }
  if (isDecrypted(apiKey)) {
    apiKey = apiKey.replace(DECRYPTION_PREFIX, "");
  }
  try {
    if (getSafeStorage()?.isEncryptionAvailable()) {
      const encryptedBuffer = getSafeStorage().encryptString(apiKey);
      return DESKTOP_PREFIX + encryptedBuffer.toString("base64");
    }
    const key = await getEncryptionKey();
    const encodedData = new TextEncoder().encode(apiKey);
    const encryptedData = await crypto.subtle.encrypt(ALGORITHM, key, encodedData);
    return WEBCRYPTO_PREFIX + arrayBufferToBase64(encryptedData);
  } catch (error) {
    console.error("Encryption failed:", error);
    return apiKey;
  }
}
async function getDecryptedKey(apiKey) {
  if (!apiKey || isPlainText(apiKey)) {
    return apiKey;
  }
  if (isDecrypted(apiKey)) {
    return apiKey.replace(DECRYPTION_PREFIX, "");
  }
  if (apiKey.startsWith(DESKTOP_PREFIX)) {
    const base64Data2 = apiKey.replace(DESKTOP_PREFIX, "");
    const buffer = Buffer.from(base64Data2, "base64");
    return getSafeStorage().decryptString(buffer);
  }
  if (apiKey.startsWith(WEBCRYPTO_PREFIX)) {
    const base64Data2 = apiKey.replace(WEBCRYPTO_PREFIX, "");
    const key = await getEncryptionKey();
    const encryptedData = base64ToArrayBuffer(base64Data2);
    const decryptedData = await crypto.subtle.decrypt(ALGORITHM, key, encryptedData);
    return new TextDecoder().decode(decryptedData);
  }
  const base64Data = apiKey.replace(ENCRYPTION_PREFIX, "");
  try {
    if (getSafeStorage()?.isEncryptionAvailable()) {
      try {
        const buffer = Buffer.from(base64Data, "base64");
        return getSafeStorage().decryptString(buffer);
      } catch {
      }
    }
    const key = await getEncryptionKey();
    const encryptedData = base64ToArrayBuffer(base64Data);
    const decryptedData = await crypto.subtle.decrypt(ALGORITHM, key, encryptedData);
    return new TextDecoder().decode(decryptedData);
  } catch (err) {
    console.error("Decryption failed:", err);
    return "Copilot failed to decrypt API keys!";
  }
}
function isPlainText(key) {
  return !key.startsWith(ENCRYPTION_PREFIX) && !key.startsWith(DECRYPTION_PREFIX);
}
function isDecrypted(keyBuffer) {
  return keyBuffer.startsWith(DECRYPTION_PREFIX);
}
function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  let binary = "";
  for (let i3 = 0; i3 < bytes.byteLength; i3++) {
    binary += String.fromCharCode(bytes[i3]);
  }
  return window.btoa(binary);
}
function base64ToArrayBuffer(base642) {
  const binaryString = window.atob(base642);
  const bytes = new Uint8Array(binaryString.length);
  for (let i3 = 0; i3 < binaryString.length; i3++) {
    bytes[i3] = binaryString.charCodeAt(i3);
  }
  return bytes.buffer;
}

// node_modules/jotai/esm/vanilla.mjs
var import_meta = {};
var keyCount = 0;
function atom(read, write) {
  const key = `atom${++keyCount}`;
  const config = {
    toString() {
      return (import_meta.env ? import_meta.env.MODE : void 0) !== "production" && this.debugLabel ? key + ":" + this.debugLabel : key;
    }
  };
  if (typeof read === "function") {
    config.read = read;
  } else {
    config.init = read;
    config.read = defaultRead;
    config.write = defaultWrite;
  }
  if (write) {
    config.write = write;
  }
  return config;
}
function defaultRead(get4) {
  return get4(this);
}
function defaultWrite(get4, set, arg) {
  return set(
    this,
    typeof arg === "function" ? arg(get4(this)) : arg
  );
}
var isSelfAtom = (atom2, a3) => atom2.unstable_is ? atom2.unstable_is(a3) : a3 === atom2;
var hasInitialValue = (atom2) => "init" in atom2;
var isActuallyWritableAtom = (atom2) => !!atom2.write;
var cancelablePromiseMap = /* @__PURE__ */ new WeakMap();
var isPendingPromise = (value) => {
  var _a5;
  return isPromiseLike(value) && !((_a5 = cancelablePromiseMap.get(value)) == null ? void 0 : _a5[1]);
};
var cancelPromise = (promise, nextValue) => {
  const promiseState = cancelablePromiseMap.get(promise);
  if (promiseState) {
    promiseState[1] = true;
    promiseState[0].forEach((fn) => fn(nextValue));
  } else if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
    throw new Error("[Bug] cancelable promise not found");
  }
};
var patchPromiseForCancelability = (promise) => {
  if (cancelablePromiseMap.has(promise)) {
    return;
  }
  const promiseState = [/* @__PURE__ */ new Set(), false];
  cancelablePromiseMap.set(promise, promiseState);
  const settle = () => {
    promiseState[1] = true;
  };
  promise.then(settle, settle);
  promise.onCancel = (fn) => {
    promiseState[0].add(fn);
  };
};
var isPromiseLike = (x2) => typeof (x2 == null ? void 0 : x2.then) === "function";
var isAtomStateInitialized = (atomState) => "v" in atomState || "e" in atomState;
var returnAtomValue = (atomState) => {
  if ("e" in atomState) {
    throw atomState.e;
  }
  if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !("v" in atomState)) {
    throw new Error("[Bug] atom state is not initialized");
  }
  return atomState.v;
};
var addPendingPromiseToDependency = (atom2, promise, dependencyAtomState) => {
  if (!dependencyAtomState.p.has(atom2)) {
    dependencyAtomState.p.add(atom2);
    promise.then(
      () => {
        dependencyAtomState.p.delete(atom2);
      },
      () => {
        dependencyAtomState.p.delete(atom2);
      }
    );
  }
};
var addDependency = (pending, atom2, atomState, a3, aState) => {
  var _a5;
  if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && a3 === atom2) {
    throw new Error("[Bug] atom cannot depend on itself");
  }
  atomState.d.set(a3, aState.n);
  if (isPendingPromise(atomState.v)) {
    addPendingPromiseToDependency(atom2, atomState.v, aState);
  }
  (_a5 = aState.m) == null ? void 0 : _a5.t.add(atom2);
  if (pending) {
    addPendingDependent(pending, a3, atom2);
  }
};
var createPending = () => [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Set()];
var addPendingAtom = (pending, atom2, atomState) => {
  if (!pending[0].has(atom2)) {
    pending[0].set(atom2, /* @__PURE__ */ new Set());
  }
  pending[1].set(atom2, atomState);
};
var addPendingDependent = (pending, atom2, dependent) => {
  const dependents = pending[0].get(atom2);
  if (dependents) {
    dependents.add(dependent);
  }
};
var getPendingDependents = (pending, atom2) => pending[0].get(atom2);
var addPendingFunction = (pending, fn) => {
  pending[2].add(fn);
};
var flushPending = (pending) => {
  let error;
  let hasError = false;
  const call = (fn) => {
    try {
      fn();
    } catch (e3) {
      if (!hasError) {
        error = e3;
        hasError = true;
      }
    }
  };
  while (pending[1].size || pending[2].size) {
    pending[0].clear();
    const atomStates = new Set(pending[1].values());
    pending[1].clear();
    const functions = new Set(pending[2]);
    pending[2].clear();
    atomStates.forEach((atomState) => {
      var _a5;
      return (_a5 = atomState.m) == null ? void 0 : _a5.l.forEach(call);
    });
    functions.forEach(call);
  }
  if (hasError) {
    throw error;
  }
};
var buildStore = (...[getAtomState, atomRead, atomWrite, atomOnMount]) => {
  let debugMountedAtoms;
  if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
    debugMountedAtoms = /* @__PURE__ */ new Set();
  }
  const setAtomStateValueOrPromise = (atom2, atomState, valueOrPromise) => {
    const hasPrevValue = "v" in atomState;
    const prevValue = atomState.v;
    const pendingPromise = isPendingPromise(atomState.v) ? atomState.v : null;
    if (isPromiseLike(valueOrPromise)) {
      patchPromiseForCancelability(valueOrPromise);
      for (const a3 of atomState.d.keys()) {
        addPendingPromiseToDependency(atom2, valueOrPromise, getAtomState(a3));
      }
      atomState.v = valueOrPromise;
      delete atomState.e;
    } else {
      atomState.v = valueOrPromise;
      delete atomState.e;
    }
    if (!hasPrevValue || !Object.is(prevValue, atomState.v)) {
      ++atomState.n;
      if (pendingPromise) {
        cancelPromise(pendingPromise, valueOrPromise);
      }
    }
  };
  const readAtomState = (pending, atom2, dirtyAtoms) => {
    var _a5;
    const atomState = getAtomState(atom2);
    if (isAtomStateInitialized(atomState)) {
      if (atomState.m && !(dirtyAtoms == null ? void 0 : dirtyAtoms.has(atom2))) {
        return atomState;
      }
      if (Array.from(atomState.d).every(
        ([a3, n4]) => (
          // Recursively, read the atom state of the dependency, and
          // check if the atom epoch number is unchanged
          readAtomState(pending, a3, dirtyAtoms).n === n4
        )
      )) {
        return atomState;
      }
    }
    atomState.d.clear();
    let isSync = true;
    const getter = (a3) => {
      if (isSelfAtom(atom2, a3)) {
        const aState2 = getAtomState(a3);
        if (!isAtomStateInitialized(aState2)) {
          if (hasInitialValue(a3)) {
            setAtomStateValueOrPromise(a3, aState2, a3.init);
          } else {
            throw new Error("no atom init");
          }
        }
        return returnAtomValue(aState2);
      }
      const aState = readAtomState(pending, a3, dirtyAtoms);
      try {
        return returnAtomValue(aState);
      } finally {
        if (isSync) {
          addDependency(pending, atom2, atomState, a3, aState);
        } else {
          const pending2 = createPending();
          addDependency(pending2, atom2, atomState, a3, aState);
          mountDependencies(pending2, atom2, atomState);
          flushPending(pending2);
        }
      }
    };
    let controller;
    let setSelf;
    const options = {
      get signal() {
        if (!controller) {
          controller = new AbortController();
        }
        return controller.signal;
      },
      get setSelf() {
        if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !isActuallyWritableAtom(atom2)) {
          console.warn("setSelf function cannot be used with read-only atom");
        }
        if (!setSelf && isActuallyWritableAtom(atom2)) {
          setSelf = (...args) => {
            if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && isSync) {
              console.warn("setSelf function cannot be called in sync");
            }
            if (!isSync) {
              return writeAtom(atom2, ...args);
            }
          };
        }
        return setSelf;
      }
    };
    try {
      const valueOrPromise = atomRead(atom2, getter, options);
      setAtomStateValueOrPromise(atom2, atomState, valueOrPromise);
      if (isPromiseLike(valueOrPromise)) {
        (_a5 = valueOrPromise.onCancel) == null ? void 0 : _a5.call(valueOrPromise, () => controller == null ? void 0 : controller.abort());
        const complete = () => {
          if (atomState.m) {
            const pending2 = createPending();
            mountDependencies(pending2, atom2, atomState);
            flushPending(pending2);
          }
        };
        valueOrPromise.then(complete, complete);
      }
      return atomState;
    } catch (error) {
      delete atomState.v;
      atomState.e = error;
      ++atomState.n;
      return atomState;
    } finally {
      isSync = false;
    }
  };
  const readAtom = (atom2) => returnAtomValue(readAtomState(void 0, atom2));
  const getDependents = (pending, atom2, atomState) => {
    var _a5, _b;
    const dependents = /* @__PURE__ */ new Map();
    for (const a3 of ((_a5 = atomState.m) == null ? void 0 : _a5.t) || []) {
      dependents.set(a3, getAtomState(a3));
    }
    for (const atomWithPendingPromise of atomState.p) {
      dependents.set(
        atomWithPendingPromise,
        getAtomState(atomWithPendingPromise)
      );
    }
    (_b = getPendingDependents(pending, atom2)) == null ? void 0 : _b.forEach((dependent) => {
      dependents.set(dependent, getAtomState(dependent));
    });
    return dependents;
  };
  function getSortedDependents(pending, rootAtom, rootAtomState) {
    const sorted = [];
    const visiting = /* @__PURE__ */ new Set();
    const visited = /* @__PURE__ */ new Set();
    const stack = [[rootAtom, rootAtomState]];
    while (stack.length > 0) {
      const [a3, aState] = stack[stack.length - 1];
      if (visited.has(a3)) {
        stack.pop();
        continue;
      }
      if (visiting.has(a3)) {
        sorted.push([a3, aState, aState.n]);
        visited.add(a3);
        stack.pop();
        continue;
      }
      visiting.add(a3);
      for (const [d3, s4] of getDependents(pending, a3, aState)) {
        if (a3 !== d3 && !visiting.has(d3)) {
          stack.push([d3, s4]);
        }
      }
    }
    return [sorted, visited];
  }
  const recomputeDependents = (pending, atom2, atomState) => {
    const [topsortedAtoms, markedAtoms] = getSortedDependents(
      pending,
      atom2,
      atomState
    );
    const changedAtoms = /* @__PURE__ */ new Set([atom2]);
    for (let i3 = topsortedAtoms.length - 1; i3 >= 0; --i3) {
      const [a3, aState, prevEpochNumber] = topsortedAtoms[i3];
      let hasChangedDeps = false;
      for (const dep of aState.d.keys()) {
        if (dep !== a3 && changedAtoms.has(dep)) {
          hasChangedDeps = true;
          break;
        }
      }
      if (hasChangedDeps) {
        readAtomState(pending, a3, markedAtoms);
        mountDependencies(pending, a3, aState);
        if (prevEpochNumber !== aState.n) {
          addPendingAtom(pending, a3, aState);
          changedAtoms.add(a3);
        }
      }
      markedAtoms.delete(a3);
    }
  };
  const writeAtomState = (pending, atom2, ...args) => {
    let isSync = true;
    const getter = (a3) => returnAtomValue(readAtomState(pending, a3));
    const setter = (a3, ...args2) => {
      const aState = getAtomState(a3);
      try {
        if (isSelfAtom(atom2, a3)) {
          if (!hasInitialValue(a3)) {
            throw new Error("atom not writable");
          }
          const prevEpochNumber = aState.n;
          const v5 = args2[0];
          setAtomStateValueOrPromise(a3, aState, v5);
          mountDependencies(pending, a3, aState);
          if (prevEpochNumber !== aState.n) {
            addPendingAtom(pending, a3, aState);
            recomputeDependents(pending, a3, aState);
          }
          return void 0;
        } else {
          return writeAtomState(pending, a3, ...args2);
        }
      } finally {
        if (!isSync) {
          flushPending(pending);
        }
      }
    };
    try {
      return atomWrite(atom2, getter, setter, ...args);
    } finally {
      isSync = false;
    }
  };
  const writeAtom = (atom2, ...args) => {
    const pending = createPending();
    try {
      return writeAtomState(pending, atom2, ...args);
    } finally {
      flushPending(pending);
    }
  };
  const mountDependencies = (pending, atom2, atomState) => {
    if (atomState.m && !isPendingPromise(atomState.v)) {
      for (const a3 of atomState.d.keys()) {
        if (!atomState.m.d.has(a3)) {
          const aMounted = mountAtom(pending, a3, getAtomState(a3));
          aMounted.t.add(atom2);
          atomState.m.d.add(a3);
        }
      }
      for (const a3 of atomState.m.d || []) {
        if (!atomState.d.has(a3)) {
          atomState.m.d.delete(a3);
          const aMounted = unmountAtom(pending, a3, getAtomState(a3));
          aMounted == null ? void 0 : aMounted.t.delete(atom2);
        }
      }
    }
  };
  const mountAtom = (pending, atom2, atomState) => {
    if (!atomState.m) {
      readAtomState(pending, atom2);
      for (const a3 of atomState.d.keys()) {
        const aMounted = mountAtom(pending, a3, getAtomState(a3));
        aMounted.t.add(atom2);
      }
      atomState.m = {
        l: /* @__PURE__ */ new Set(),
        d: new Set(atomState.d.keys()),
        t: /* @__PURE__ */ new Set()
      };
      if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
        debugMountedAtoms.add(atom2);
      }
      if (isActuallyWritableAtom(atom2)) {
        const mounted = atomState.m;
        let setAtom;
        const createInvocationContext = (pending2, fn) => {
          let isSync = true;
          setAtom = (...args) => {
            try {
              return writeAtomState(pending2, atom2, ...args);
            } finally {
              if (!isSync) {
                flushPending(pending2);
              }
            }
          };
          try {
            return fn();
          } finally {
            isSync = false;
          }
        };
        addPendingFunction(pending, () => {
          const onUnmount = createInvocationContext(
            pending,
            () => atomOnMount(atom2, (...args) => setAtom(...args))
          );
          if (onUnmount) {
            mounted.u = (pending2) => createInvocationContext(pending2, onUnmount);
          }
        });
      }
    }
    return atomState.m;
  };
  const unmountAtom = (pending, atom2, atomState) => {
    if (atomState.m && !atomState.m.l.size && !Array.from(atomState.m.t).some((a3) => {
      var _a5;
      return (_a5 = getAtomState(a3).m) == null ? void 0 : _a5.d.has(atom2);
    })) {
      const onUnmount = atomState.m.u;
      if (onUnmount) {
        addPendingFunction(pending, () => onUnmount(pending));
      }
      delete atomState.m;
      if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
        debugMountedAtoms.delete(atom2);
      }
      for (const a3 of atomState.d.keys()) {
        const aMounted = unmountAtom(pending, a3, getAtomState(a3));
        aMounted == null ? void 0 : aMounted.t.delete(atom2);
      }
      return void 0;
    }
    return atomState.m;
  };
  const subscribeAtom = (atom2, listener) => {
    const pending = createPending();
    const atomState = getAtomState(atom2);
    const mounted = mountAtom(pending, atom2, atomState);
    const listeners = mounted.l;
    listeners.add(listener);
    flushPending(pending);
    return () => {
      listeners.delete(listener);
      const pending2 = createPending();
      unmountAtom(pending2, atom2, atomState);
      flushPending(pending2);
    };
  };
  const unstable_derive = (fn) => buildStore(...fn(getAtomState, atomRead, atomWrite, atomOnMount));
  const store2 = {
    get: readAtom,
    set: writeAtom,
    sub: subscribeAtom,
    unstable_derive
  };
  if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
    const devStore = {
      // store dev methods (these are tentative and subject to change without notice)
      dev4_get_internal_weak_map: () => ({
        get: (atom2) => {
          const atomState = getAtomState(atom2);
          if (atomState.n === 0) {
            return void 0;
          }
          return atomState;
        }
      }),
      dev4_get_mounted_atoms: () => debugMountedAtoms,
      dev4_restore_atoms: (values) => {
        const pending = createPending();
        for (const [atom2, value] of values) {
          if (hasInitialValue(atom2)) {
            const atomState = getAtomState(atom2);
            const prevEpochNumber = atomState.n;
            setAtomStateValueOrPromise(atom2, atomState, value);
            mountDependencies(pending, atom2, atomState);
            if (prevEpochNumber !== atomState.n) {
              addPendingAtom(pending, atom2, atomState);
              recomputeDependents(pending, atom2, atomState);
            }
          }
        }
        flushPending(pending);
      }
    };
    Object.assign(store2, devStore);
  }
  return store2;
};
var createStore = () => {
  const atomStateMap = /* @__PURE__ */ new WeakMap();
  const getAtomState = (atom2) => {
    if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production" && !atom2) {
      throw new Error("Atom is undefined or null");
    }
    let atomState = atomStateMap.get(atom2);
    if (!atomState) {
      atomState = { d: /* @__PURE__ */ new Map(), p: /* @__PURE__ */ new Set(), n: 0 };
      atomStateMap.set(atom2, atomState);
    }
    return atomState;
  };
  return buildStore(
    getAtomState,
    (atom2, ...params) => atom2.read(...params),
    (atom2, ...params) => atom2.write(...params),
    (atom2, ...params) => {
      var _a5;
      return (_a5 = atom2.onMount) == null ? void 0 : _a5.call(atom2, ...params);
    }
  );
};
var defaultStore;
var getDefaultStore = () => {
  if (!defaultStore) {
    defaultStore = createStore();
    if ((import_meta.env ? import_meta.env.MODE : void 0) !== "production") {
      globalThis.__JOTAI_DEFAULT_STORE__ || (globalThis.__JOTAI_DEFAULT_STORE__ = defaultStore);
      if (globalThis.__JOTAI_DEFAULT_STORE__ !== defaultStore) {
        console.warn(
          "Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"
        );
      }
    }
  }
  return defaultStore;
};

// node_modules/jotai/esm/react.mjs
var import_react = __toESM(require_react(), 1);
var import_meta2 = {};
"use client";
var StoreContext = (0, import_react.createContext)(
  void 0
);
var useStore = (options) => {
  const store2 = (0, import_react.useContext)(StoreContext);
  return (options == null ? void 0 : options.store) || store2 || getDefaultStore();
};
var isPromiseLike2 = (x2) => typeof (x2 == null ? void 0 : x2.then) === "function";
var attachPromiseMeta = (promise) => {
  promise.status = "pending";
  promise.then(
    (v5) => {
      promise.status = "fulfilled";
      promise.value = v5;
    },
    (e3) => {
      promise.status = "rejected";
      promise.reason = e3;
    }
  );
};
var use = import_react.default.use || ((promise) => {
  if (promise.status === "pending") {
    throw promise;
  } else if (promise.status === "fulfilled") {
    return promise.value;
  } else if (promise.status === "rejected") {
    throw promise.reason;
  } else {
    attachPromiseMeta(promise);
    throw promise;
  }
});
var continuablePromiseMap = /* @__PURE__ */ new WeakMap();
var createContinuablePromise = (promise) => {
  let continuablePromise = continuablePromiseMap.get(promise);
  if (!continuablePromise) {
    continuablePromise = new Promise((resolve, reject) => {
      let curr = promise;
      const onFulfilled = (me) => (v5) => {
        if (curr === me) {
          resolve(v5);
        }
      };
      const onRejected = (me) => (e3) => {
        if (curr === me) {
          reject(e3);
        }
      };
      const registerCancelHandler = (p3) => {
        if ("onCancel" in p3 && typeof p3.onCancel === "function") {
          p3.onCancel((nextValue) => {
            if ((import_meta2.env ? import_meta2.env.MODE : void 0) !== "production" && nextValue === p3) {
              throw new Error("[Bug] p is not updated even after cancelation");
            }
            if (isPromiseLike2(nextValue)) {
              continuablePromiseMap.set(nextValue, continuablePromise);
              curr = nextValue;
              nextValue.then(onFulfilled(nextValue), onRejected(nextValue));
              registerCancelHandler(nextValue);
            } else {
              resolve(nextValue);
            }
          });
        }
      };
      promise.then(onFulfilled(promise), onRejected(promise));
      registerCancelHandler(promise);
    });
    continuablePromiseMap.set(promise, continuablePromise);
  }
  return continuablePromise;
};
function useAtomValue(atom2, options) {
  const store2 = useStore(options);
  const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = (0, import_react.useReducer)(
    (prev) => {
      const nextValue = store2.get(atom2);
      if (Object.is(prev[0], nextValue) && prev[1] === store2 && prev[2] === atom2) {
        return prev;
      }
      return [nextValue, store2, atom2];
    },
    void 0,
    () => [store2.get(atom2), store2, atom2]
  );
  let value = valueFromReducer;
  if (storeFromReducer !== store2 || atomFromReducer !== atom2) {
    rerender();
    value = store2.get(atom2);
  }
  const delay = options == null ? void 0 : options.delay;
  (0, import_react.useEffect)(() => {
    const unsub = store2.sub(atom2, () => {
      if (typeof delay === "number") {
        const value2 = store2.get(atom2);
        if (isPromiseLike2(value2)) {
          attachPromiseMeta(createContinuablePromise(value2));
        }
        setTimeout(rerender, delay);
        return;
      }
      rerender();
    });
    rerender();
    return unsub;
  }, [store2, atom2, delay]);
  (0, import_react.useDebugValue)(value);
  if (isPromiseLike2(value)) {
    const promise = createContinuablePromise(value);
    return use(promise);
  }
  return value;
}
function useSetAtom(atom2, options) {
  const store2 = useStore(options);
  const setAtom = (0, import_react.useCallback)(
    (...args) => {
      if ((import_meta2.env ? import_meta2.env.MODE : void 0) !== "production" && !("write" in atom2)) {
        throw new Error("not writable atom");
      }
      return store2.set(atom2, ...args);
    },
    [store2, atom2]
  );
  return setAtom;
}
function useAtom(atom2, options) {
  return [
    useAtomValue(atom2, options),
    // We do wrong type assertion here, which results in throwing an error.
    useSetAtom(atom2, options)
  ];
}

// src/settings/model.ts
var settingsStore = createStore();
var settingsAtom = atom(DEFAULT_SETTINGS);
function setSettings(settings) {
  const newSettings = mergeAllActiveModelsWithCoreModels({ ...getSettings(), ...settings });
  settingsStore.set(settingsAtom, newSettings);
}
function updateSetting(key, value) {
  const settings = getSettings();
  setSettings({ ...settings, [key]: value });
}
function getSettings() {
  return settingsStore.get(settingsAtom);
}
function resetSettings() {
  const defaultSettingsWithBuiltIns = {
    ...DEFAULT_SETTINGS,
    activeModels: BUILTIN_CHAT_MODELS.map((model) => ({ ...model, enabled: true })),
    activeEmbeddingModels: BUILTIN_EMBEDDING_MODELS.map((model) => ({ ...model, enabled: true }))
  };
  setSettings(defaultSettingsWithBuiltIns);
}
function subscribeToSettingsChange(callback) {
  return settingsStore.sub(settingsAtom, callback);
}
function useSettingsValue() {
  return useAtomValue(settingsAtom, {
    store: settingsStore
  });
}
function sanitizeSettings(settings) {
  const settingsToSanitize = settings || DEFAULT_SETTINGS;
  settingsToSanitize.activeEmbeddingModels = settingsToSanitize.activeEmbeddingModels.map((m3) => {
    return {
      ...m3,
      provider: m3.provider === "azure_openai" ? "azure openai" /* AZURE_OPENAI */ : m3.provider
    };
  });
  const sanitizedSettings = { ...settingsToSanitize };
  const temperature = Number(settingsToSanitize.temperature);
  sanitizedSettings.temperature = isNaN(temperature) ? DEFAULT_SETTINGS.temperature : temperature;
  const maxTokens = Number(settingsToSanitize.maxTokens);
  sanitizedSettings.maxTokens = isNaN(maxTokens) ? DEFAULT_SETTINGS.maxTokens : maxTokens;
  const contextTurns = Number(settingsToSanitize.contextTurns);
  sanitizedSettings.contextTurns = isNaN(contextTurns) ? DEFAULT_SETTINGS.contextTurns : contextTurns;
  return sanitizedSettings;
}
function getSystemPrompt() {
  const userPrompt = getSettings().userSystemPrompt;
  return userPrompt ? `${DEFAULT_SYSTEM_PROMPT}

${userPrompt}` : DEFAULT_SYSTEM_PROMPT;
}
function mergeAllActiveModelsWithCoreModels(settings) {
  settings.activeModels = mergeActiveModels(settings.activeModels, BUILTIN_CHAT_MODELS);
  settings.activeEmbeddingModels = mergeActiveModels(
    settings.activeEmbeddingModels,
    BUILTIN_EMBEDDING_MODELS
  );
  return settings;
}
function getModelKeyFromModel(model) {
  return `${model.name}|${model.provider}`;
}
function mergeActiveModels(existingActiveModels, builtInModels) {
  const modelMap = /* @__PURE__ */ new Map();
  builtInModels.filter((model) => model.core).forEach((model) => {
    modelMap.set(getModelKeyFromModel(model), { ...model, core: true });
  });
  existingActiveModels.forEach((model) => {
    const key = getModelKeyFromModel(model);
    const existingModel = modelMap.get(key);
    if (existingModel) {
      modelMap.set(key, {
        ...model,
        isBuiltIn: existingModel.isBuiltIn || model.isBuiltIn
      });
    } else {
      modelMap.set(key, model);
    }
  });
  return Array.from(modelMap.values());
}

// src/logger.ts
function logInfo(...args) {
  if (getSettings().debug) {
    console.log(...args);
  }
}
function logError(...args) {
  if (getSettings().debug) {
    console.error(...args);
  }
}

// src/aiParams.ts
var userModelKeyAtom = atom(null);
var modelKeyAtom = atom(
  (get4) => {
    const userValue = get4(userModelKeyAtom);
    if (userValue !== null) {
      return userValue;
    }
    return get4(settingsAtom).defaultModelKey;
  },
  (get4, set, newValue) => {
    set(userModelKeyAtom, newValue);
  }
);
var userChainTypeAtom = atom(null);
var chainTypeAtom = atom(
  (get4) => {
    const userValue = get4(userChainTypeAtom);
    if (userValue !== null) {
      return userValue;
    }
    return get4(settingsAtom).defaultChainType;
  },
  (get4, set, newValue) => {
    set(userChainTypeAtom, newValue);
  }
);
function setModelKey(modelKey) {
  settingsStore.set(modelKeyAtom, modelKey);
}
function getModelKey() {
  return settingsStore.get(modelKeyAtom);
}
function subscribeToModelKeyChange(callback) {
  return settingsStore.sub(modelKeyAtom, callback);
}
function useModelKey() {
  return useAtom(modelKeyAtom, {
    store: settingsStore
  });
}
function getChainType() {
  return settingsStore.get(chainTypeAtom);
}
function setChainType(chainType) {
  settingsStore.set(chainTypeAtom, chainType);
}
function subscribeToChainTypeChange(callback) {
  return settingsStore.sub(chainTypeAtom, callback);
}
function useChainType() {
  return useAtom(chainTypeAtom, {
    store: settingsStore
  });
}

// src/components/modals/CopilotPlusExpiredModal.tsx
var import_react4 = __toESM(require_react());
var import_obsidian2 = require("obsidian");
var import_client3 = __toESM(require_client());

// src/components/ui/button.tsx
var React3 = __toESM(require_react());

// node_modules/@radix-ui/react-slot/dist/index.mjs
var React2 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React = __toESM(require_react(), 1);
function setRef(ref, value) {
  if (typeof ref === "function") {
    ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs(...refs) {
  return (node) => refs.forEach((ref) => setRef(ref, node));
}
function useComposedRefs(...refs) {
  return React.useCallback(composeRefs(...refs), refs);
}

// node_modules/@radix-ui/react-slot/dist/index.mjs
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var Slot = React2.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React2.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React2.Children.count(newElement) > 1)
          return React2.Children.only(null);
        return React2.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children: React2.isValidElement(newElement) ? React2.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children });
});
Slot.displayName = "Slot";
var SlotClone = React2.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React2.isValidElement(children)) {
    const childrenRef = getElementRef(children);
    return React2.cloneElement(children, {
      ...mergeProps(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React2.Children.count(children) > 1 ? React2.Children.only(null) : null;
});
SlotClone.displayName = "SlotClone";
var Slottable = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
};
function isSlottable(child) {
  return React2.isValidElement(child) && child.type === Slottable;
}
function mergeProps(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/clsx/dist/clsx.mjs
function r(e3) {
  var t3, f3, n4 = "";
  if ("string" == typeof e3 || "number" == typeof e3)
    n4 += e3;
  else if ("object" == typeof e3)
    if (Array.isArray(e3)) {
      var o3 = e3.length;
      for (t3 = 0; t3 < o3; t3++)
        e3[t3] && (f3 = r(e3[t3])) && (n4 && (n4 += " "), n4 += f3);
    } else
      for (f3 in e3)
        e3[f3] && (n4 && (n4 += " "), n4 += f3);
  return n4;
}
function clsx() {
  for (var e3, t3, f3 = 0, n4 = "", o3 = arguments.length; f3 < o3; f3++)
    (e3 = arguments[f3]) && (t3 = r(e3)) && (n4 && (n4 += " "), n4 += t3);
  return n4;
}

// node_modules/class-variance-authority/dist/index.mjs
var falsyToString = (value) => typeof value === "boolean" ? `${value}` : value === 0 ? "0" : value;
var cx = clsx;
var cva = (base, config) => (props) => {
  var _config_compoundVariants;
  if ((config === null || config === void 0 ? void 0 : config.variants) == null)
    return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
  const { variants, defaultVariants } = config;
  const getVariantClassNames = Object.keys(variants).map((variant) => {
    const variantProp = props === null || props === void 0 ? void 0 : props[variant];
    const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
    if (variantProp === null)
      return null;
    const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
    return variants[variant][variantKey];
  });
  const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => {
    let [key, value] = param;
    if (value === void 0) {
      return acc;
    }
    acc[key] = value;
    return acc;
  }, {});
  const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (_config_compoundVariants = config.compoundVariants) === null || _config_compoundVariants === void 0 ? void 0 : _config_compoundVariants.reduce((acc, param) => {
    let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param;
    return Object.entries(compoundVariantOptions).every((param2) => {
      let [key, value] = param2;
      return Array.isArray(value) ? value.includes({
        ...defaultVariants,
        ...propsWithoutUndefined
      }[key]) : {
        ...defaultVariants,
        ...propsWithoutUndefined
      }[key] === value;
    }) ? [
      ...acc,
      cvClass,
      cvClassName
    ] : acc;
  }, []);
  return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
};

// node_modules/tailwind-merge/dist/bundle-mjs.mjs
var CLASS_PART_SEPARATOR = "-";
var createClassGroupUtils = (config) => {
  const classMap = createClassMap(config);
  const {
    conflictingClassGroups,
    conflictingClassGroupModifiers
  } = config;
  const getClassGroupId = (className) => {
    const classParts = className.split(CLASS_PART_SEPARATOR);
    if (classParts[0] === "" && classParts.length !== 1) {
      classParts.shift();
    }
    return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className);
  };
  const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {
    const conflicts = conflictingClassGroups[classGroupId] || [];
    if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) {
      return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]];
    }
    return conflicts;
  };
  return {
    getClassGroupId,
    getConflictingClassGroupIds
  };
};
var getGroupRecursive = (classParts, classPartObject) => {
  if (classParts.length === 0) {
    return classPartObject.classGroupId;
  }
  const currentClassPart = classParts[0];
  const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);
  const classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : void 0;
  if (classGroupFromNextClassPart) {
    return classGroupFromNextClassPart;
  }
  if (classPartObject.validators.length === 0) {
    return void 0;
  }
  const classRest = classParts.join(CLASS_PART_SEPARATOR);
  return classPartObject.validators.find(({
    validator: validator2
  }) => validator2(classRest))?.classGroupId;
};
var arbitraryPropertyRegex = /^\[(.+)\]$/;
var getGroupIdForArbitraryProperty = (className) => {
  if (arbitraryPropertyRegex.test(className)) {
    const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1];
    const property = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(":"));
    if (property) {
      return "arbitrary.." + property;
    }
  }
};
var createClassMap = (config) => {
  const {
    theme,
    prefix
  } = config;
  const classMap = {
    nextPart: /* @__PURE__ */ new Map(),
    validators: []
  };
  const prefixedClassGroupEntries = getPrefixedClassGroupEntries(Object.entries(config.classGroups), prefix);
  prefixedClassGroupEntries.forEach(([classGroupId, classGroup]) => {
    processClassesRecursively(classGroup, classMap, classGroupId, theme);
  });
  return classMap;
};
var processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => {
  classGroup.forEach((classDefinition) => {
    if (typeof classDefinition === "string") {
      const classPartObjectToEdit = classDefinition === "" ? classPartObject : getPart(classPartObject, classDefinition);
      classPartObjectToEdit.classGroupId = classGroupId;
      return;
    }
    if (typeof classDefinition === "function") {
      if (isThemeGetter(classDefinition)) {
        processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);
        return;
      }
      classPartObject.validators.push({
        validator: classDefinition,
        classGroupId
      });
      return;
    }
    Object.entries(classDefinition).forEach(([key, classGroup2]) => {
      processClassesRecursively(classGroup2, getPart(classPartObject, key), classGroupId, theme);
    });
  });
};
var getPart = (classPartObject, path) => {
  let currentClassPartObject = classPartObject;
  path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => {
    if (!currentClassPartObject.nextPart.has(pathPart)) {
      currentClassPartObject.nextPart.set(pathPart, {
        nextPart: /* @__PURE__ */ new Map(),
        validators: []
      });
    }
    currentClassPartObject = currentClassPartObject.nextPart.get(pathPart);
  });
  return currentClassPartObject;
};
var isThemeGetter = (func) => func.isThemeGetter;
var getPrefixedClassGroupEntries = (classGroupEntries, prefix) => {
  if (!prefix) {
    return classGroupEntries;
  }
  return classGroupEntries.map(([classGroupId, classGroup]) => {
    const prefixedClassGroup = classGroup.map((classDefinition) => {
      if (typeof classDefinition === "string") {
        return prefix + classDefinition;
      }
      if (typeof classDefinition === "object") {
        return Object.fromEntries(Object.entries(classDefinition).map(([key, value]) => [prefix + key, value]));
      }
      return classDefinition;
    });
    return [classGroupId, prefixedClassGroup];
  });
};
var createLruCache = (maxCacheSize) => {
  if (maxCacheSize < 1) {
    return {
      get: () => void 0,
      set: () => {
      }
    };
  }
  let cacheSize = 0;
  let cache2 = /* @__PURE__ */ new Map();
  let previousCache = /* @__PURE__ */ new Map();
  const update2 = (key, value) => {
    cache2.set(key, value);
    cacheSize++;
    if (cacheSize > maxCacheSize) {
      cacheSize = 0;
      previousCache = cache2;
      cache2 = /* @__PURE__ */ new Map();
    }
  };
  return {
    get(key) {
      let value = cache2.get(key);
      if (value !== void 0) {
        return value;
      }
      if ((value = previousCache.get(key)) !== void 0) {
        update2(key, value);
        return value;
      }
    },
    set(key, value) {
      if (cache2.has(key)) {
        cache2.set(key, value);
      } else {
        update2(key, value);
      }
    }
  };
};
var IMPORTANT_MODIFIER = "!";
var createParseClassName = (config) => {
  const {
    separator,
    experimentalParseClassName
  } = config;
  const isSeparatorSingleCharacter = separator.length === 1;
  const firstSeparatorCharacter = separator[0];
  const separatorLength = separator.length;
  const parseClassName = (className) => {
    const modifiers = [];
    let bracketDepth = 0;
    let modifierStart = 0;
    let postfixModifierPosition;
    for (let index2 = 0; index2 < className.length; index2++) {
      let currentCharacter = className[index2];
      if (bracketDepth === 0) {
        if (currentCharacter === firstSeparatorCharacter && (isSeparatorSingleCharacter || className.slice(index2, index2 + separatorLength) === separator)) {
          modifiers.push(className.slice(modifierStart, index2));
          modifierStart = index2 + separatorLength;
          continue;
        }
        if (currentCharacter === "/") {
          postfixModifierPosition = index2;
          continue;
        }
      }
      if (currentCharacter === "[") {
        bracketDepth++;
      } else if (currentCharacter === "]") {
        bracketDepth--;
      }
    }
    const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.substring(modifierStart);
    const hasImportantModifier = baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER);
    const baseClassName = hasImportantModifier ? baseClassNameWithImportantModifier.substring(1) : baseClassNameWithImportantModifier;
    const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : void 0;
    return {
      modifiers,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    };
  };
  if (experimentalParseClassName) {
    return (className) => experimentalParseClassName({
      className,
      parseClassName
    });
  }
  return parseClassName;
};
var sortModifiers = (modifiers) => {
  if (modifiers.length <= 1) {
    return modifiers;
  }
  const sortedModifiers = [];
  let unsortedModifiers = [];
  modifiers.forEach((modifier) => {
    const isArbitraryVariant = modifier[0] === "[";
    if (isArbitraryVariant) {
      sortedModifiers.push(...unsortedModifiers.sort(), modifier);
      unsortedModifiers = [];
    } else {
      unsortedModifiers.push(modifier);
    }
  });
  sortedModifiers.push(...unsortedModifiers.sort());
  return sortedModifiers;
};
var createConfigUtils = (config) => ({
  cache: createLruCache(config.cacheSize),
  parseClassName: createParseClassName(config),
  ...createClassGroupUtils(config)
});
var SPLIT_CLASSES_REGEX = /\s+/;
var mergeClassList = (classList, configUtils) => {
  const {
    parseClassName,
    getClassGroupId,
    getConflictingClassGroupIds
  } = configUtils;
  const classGroupsInConflict = [];
  const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);
  let result = "";
  for (let index2 = classNames.length - 1; index2 >= 0; index2 -= 1) {
    const originalClassName = classNames[index2];
    const {
      modifiers,
      hasImportantModifier,
      baseClassName,
      maybePostfixModifierPosition
    } = parseClassName(originalClassName);
    let hasPostfixModifier = Boolean(maybePostfixModifierPosition);
    let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);
    if (!classGroupId) {
      if (!hasPostfixModifier) {
        result = originalClassName + (result.length > 0 ? " " + result : result);
        continue;
      }
      classGroupId = getClassGroupId(baseClassName);
      if (!classGroupId) {
        result = originalClassName + (result.length > 0 ? " " + result : result);
        continue;
      }
      hasPostfixModifier = false;
    }
    const variantModifier = sortModifiers(modifiers).join(":");
    const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;
    const classId = modifierId + classGroupId;
    if (classGroupsInConflict.includes(classId)) {
      continue;
    }
    classGroupsInConflict.push(classId);
    const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);
    for (let i3 = 0; i3 < conflictGroups.length; ++i3) {
      const group = conflictGroups[i3];
      classGroupsInConflict.push(modifierId + group);
    }
    result = originalClassName + (result.length > 0 ? " " + result : result);
  }
  return result;
};
function twJoin() {
  let index2 = 0;
  let argument;
  let resolvedValue;
  let string = "";
  while (index2 < arguments.length) {
    if (argument = arguments[index2++]) {
      if (resolvedValue = toValue(argument)) {
        string && (string += " ");
        string += resolvedValue;
      }
    }
  }
  return string;
}
var toValue = (mix) => {
  if (typeof mix === "string") {
    return mix;
  }
  let resolvedValue;
  let string = "";
  for (let k3 = 0; k3 < mix.length; k3++) {
    if (mix[k3]) {
      if (resolvedValue = toValue(mix[k3])) {
        string && (string += " ");
        string += resolvedValue;
      }
    }
  }
  return string;
};
function createTailwindMerge(createConfigFirst, ...createConfigRest) {
  let configUtils;
  let cacheGet;
  let cacheSet;
  let functionToCall = initTailwindMerge;
  function initTailwindMerge(classList) {
    const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());
    configUtils = createConfigUtils(config);
    cacheGet = configUtils.cache.get;
    cacheSet = configUtils.cache.set;
    functionToCall = tailwindMerge;
    return tailwindMerge(classList);
  }
  function tailwindMerge(classList) {
    const cachedResult = cacheGet(classList);
    if (cachedResult) {
      return cachedResult;
    }
    const result = mergeClassList(classList, configUtils);
    cacheSet(classList, result);
    return result;
  }
  return function callTailwindMerge() {
    return functionToCall(twJoin.apply(null, arguments));
  };
}
var fromTheme = (key) => {
  const themeGetter = (theme) => theme[key] || [];
  themeGetter.isThemeGetter = true;
  return themeGetter;
};
var arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i;
var fractionRegex = /^\d+\/\d+$/;
var stringLengths = /* @__PURE__ */ new Set(["px", "full", "screen"]);
var tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/;
var lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/;
var colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/;
var shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/;
var imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;
var isLength = (value) => isNumber(value) || stringLengths.has(value) || fractionRegex.test(value);
var isArbitraryLength = (value) => getIsArbitraryValue(value, "length", isLengthOnly);
var isNumber = (value) => Boolean(value) && !Number.isNaN(Number(value));
var isArbitraryNumber = (value) => getIsArbitraryValue(value, "number", isNumber);
var isInteger2 = (value) => Boolean(value) && Number.isInteger(Number(value));
var isPercent = (value) => value.endsWith("%") && isNumber(value.slice(0, -1));
var isArbitraryValue = (value) => arbitraryValueRegex.test(value);
var isTshirtSize = (value) => tshirtUnitRegex.test(value);
var sizeLabels = /* @__PURE__ */ new Set(["length", "size", "percentage"]);
var isArbitrarySize = (value) => getIsArbitraryValue(value, sizeLabels, isNever);
var isArbitraryPosition = (value) => getIsArbitraryValue(value, "position", isNever);
var imageLabels = /* @__PURE__ */ new Set(["image", "url"]);
var isArbitraryImage = (value) => getIsArbitraryValue(value, imageLabels, isImage);
var isArbitraryShadow = (value) => getIsArbitraryValue(value, "", isShadow);
var isAny = () => true;
var getIsArbitraryValue = (value, label, testValue) => {
  const result = arbitraryValueRegex.exec(value);
  if (result) {
    if (result[1]) {
      return typeof label === "string" ? result[1] === label : label.has(result[1]);
    }
    return testValue(result[2]);
  }
  return false;
};
var isLengthOnly = (value) => (
  // `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.
  // For example, `hsl(0 0% 0%)` would be classified as a length without this check.
  // I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.
  lengthUnitRegex.test(value) && !colorFunctionRegex.test(value)
);
var isNever = () => false;
var isShadow = (value) => shadowRegex.test(value);
var isImage = (value) => imageRegex.test(value);
var getDefaultConfig = () => {
  const colors = fromTheme("colors");
  const spacing = fromTheme("spacing");
  const blur = fromTheme("blur");
  const brightness = fromTheme("brightness");
  const borderColor = fromTheme("borderColor");
  const borderRadius = fromTheme("borderRadius");
  const borderSpacing = fromTheme("borderSpacing");
  const borderWidth = fromTheme("borderWidth");
  const contrast = fromTheme("contrast");
  const grayscale = fromTheme("grayscale");
  const hueRotate = fromTheme("hueRotate");
  const invert = fromTheme("invert");
  const gap = fromTheme("gap");
  const gradientColorStops = fromTheme("gradientColorStops");
  const gradientColorStopPositions = fromTheme("gradientColorStopPositions");
  const inset = fromTheme("inset");
  const margin = fromTheme("margin");
  const opacity = fromTheme("opacity");
  const padding = fromTheme("padding");
  const saturate = fromTheme("saturate");
  const scale = fromTheme("scale");
  const sepia = fromTheme("sepia");
  const skew = fromTheme("skew");
  const space = fromTheme("space");
  const translate = fromTheme("translate");
  const getOverscroll = () => ["auto", "contain", "none"];
  const getOverflow = () => ["auto", "hidden", "clip", "visible", "scroll"];
  const getSpacingWithAutoAndArbitrary = () => ["auto", isArbitraryValue, spacing];
  const getSpacingWithArbitrary = () => [isArbitraryValue, spacing];
  const getLengthWithEmptyAndArbitrary = () => ["", isLength, isArbitraryLength];
  const getNumberWithAutoAndArbitrary = () => ["auto", isNumber, isArbitraryValue];
  const getPositions = () => ["bottom", "center", "left", "left-bottom", "left-top", "right", "right-bottom", "right-top", "top"];
  const getLineStyles = () => ["solid", "dashed", "dotted", "double", "none"];
  const getBlendModes = () => ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"];
  const getAlign = () => ["start", "end", "center", "between", "around", "evenly", "stretch"];
  const getZeroAndEmpty = () => ["", "0", isArbitraryValue];
  const getBreaks = () => ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"];
  const getNumberAndArbitrary = () => [isNumber, isArbitraryValue];
  return {
    cacheSize: 500,
    separator: ":",
    theme: {
      colors: [isAny],
      spacing: [isLength, isArbitraryLength],
      blur: ["none", "", isTshirtSize, isArbitraryValue],
      brightness: getNumberAndArbitrary(),
      borderColor: [colors],
      borderRadius: ["none", "", "full", isTshirtSize, isArbitraryValue],
      borderSpacing: getSpacingWithArbitrary(),
      borderWidth: getLengthWithEmptyAndArbitrary(),
      contrast: getNumberAndArbitrary(),
      grayscale: getZeroAndEmpty(),
      hueRotate: getNumberAndArbitrary(),
      invert: getZeroAndEmpty(),
      gap: getSpacingWithArbitrary(),
      gradientColorStops: [colors],
      gradientColorStopPositions: [isPercent, isArbitraryLength],
      inset: getSpacingWithAutoAndArbitrary(),
      margin: getSpacingWithAutoAndArbitrary(),
      opacity: getNumberAndArbitrary(),
      padding: getSpacingWithArbitrary(),
      saturate: getNumberAndArbitrary(),
      scale: getNumberAndArbitrary(),
      sepia: getZeroAndEmpty(),
      skew: getNumberAndArbitrary(),
      space: getSpacingWithArbitrary(),
      translate: getSpacingWithArbitrary()
    },
    classGroups: {
      // Layout
      /**
       * Aspect Ratio
       * @see https://tailwindcss.com/docs/aspect-ratio
       */
      aspect: [{
        aspect: ["auto", "square", "video", isArbitraryValue]
      }],
      /**
       * Container
       * @see https://tailwindcss.com/docs/container
       */
      container: ["container"],
      /**
       * Columns
       * @see https://tailwindcss.com/docs/columns
       */
      columns: [{
        columns: [isTshirtSize]
      }],
      /**
       * Break After
       * @see https://tailwindcss.com/docs/break-after
       */
      "break-after": [{
        "break-after": getBreaks()
      }],
      /**
       * Break Before
       * @see https://tailwindcss.com/docs/break-before
       */
      "break-before": [{
        "break-before": getBreaks()
      }],
      /**
       * Break Inside
       * @see https://tailwindcss.com/docs/break-inside
       */
      "break-inside": [{
        "break-inside": ["auto", "avoid", "avoid-page", "avoid-column"]
      }],
      /**
       * Box Decoration Break
       * @see https://tailwindcss.com/docs/box-decoration-break
       */
      "box-decoration": [{
        "box-decoration": ["slice", "clone"]
      }],
      /**
       * Box Sizing
       * @see https://tailwindcss.com/docs/box-sizing
       */
      box: [{
        box: ["border", "content"]
      }],
      /**
       * Display
       * @see https://tailwindcss.com/docs/display
       */
      display: ["block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden"],
      /**
       * Floats
       * @see https://tailwindcss.com/docs/float
       */
      float: [{
        float: ["right", "left", "none", "start", "end"]
      }],
      /**
       * Clear
       * @see https://tailwindcss.com/docs/clear
       */
      clear: [{
        clear: ["left", "right", "both", "none", "start", "end"]
      }],
      /**
       * Isolation
       * @see https://tailwindcss.com/docs/isolation
       */
      isolation: ["isolate", "isolation-auto"],
      /**
       * Object Fit
       * @see https://tailwindcss.com/docs/object-fit
       */
      "object-fit": [{
        object: ["contain", "cover", "fill", "none", "scale-down"]
      }],
      /**
       * Object Position
       * @see https://tailwindcss.com/docs/object-position
       */
      "object-position": [{
        object: [...getPositions(), isArbitraryValue]
      }],
      /**
       * Overflow
       * @see https://tailwindcss.com/docs/overflow
       */
      overflow: [{
        overflow: getOverflow()
      }],
      /**
       * Overflow X
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-x": [{
        "overflow-x": getOverflow()
      }],
      /**
       * Overflow Y
       * @see https://tailwindcss.com/docs/overflow
       */
      "overflow-y": [{
        "overflow-y": getOverflow()
      }],
      /**
       * Overscroll Behavior
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      overscroll: [{
        overscroll: getOverscroll()
      }],
      /**
       * Overscroll Behavior X
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-x": [{
        "overscroll-x": getOverscroll()
      }],
      /**
       * Overscroll Behavior Y
       * @see https://tailwindcss.com/docs/overscroll-behavior
       */
      "overscroll-y": [{
        "overscroll-y": getOverscroll()
      }],
      /**
       * Position
       * @see https://tailwindcss.com/docs/position
       */
      position: ["static", "fixed", "absolute", "relative", "sticky"],
      /**
       * Top / Right / Bottom / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      inset: [{
        inset: [inset]
      }],
      /**
       * Right / Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-x": [{
        "inset-x": [inset]
      }],
      /**
       * Top / Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      "inset-y": [{
        "inset-y": [inset]
      }],
      /**
       * Start
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      start: [{
        start: [inset]
      }],
      /**
       * End
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      end: [{
        end: [inset]
      }],
      /**
       * Top
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      top: [{
        top: [inset]
      }],
      /**
       * Right
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      right: [{
        right: [inset]
      }],
      /**
       * Bottom
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      bottom: [{
        bottom: [inset]
      }],
      /**
       * Left
       * @see https://tailwindcss.com/docs/top-right-bottom-left
       */
      left: [{
        left: [inset]
      }],
      /**
       * Visibility
       * @see https://tailwindcss.com/docs/visibility
       */
      visibility: ["visible", "invisible", "collapse"],
      /**
       * Z-Index
       * @see https://tailwindcss.com/docs/z-index
       */
      z: [{
        z: ["auto", isInteger2, isArbitraryValue]
      }],
      // Flexbox and Grid
      /**
       * Flex Basis
       * @see https://tailwindcss.com/docs/flex-basis
       */
      basis: [{
        basis: getSpacingWithAutoAndArbitrary()
      }],
      /**
       * Flex Direction
       * @see https://tailwindcss.com/docs/flex-direction
       */
      "flex-direction": [{
        flex: ["row", "row-reverse", "col", "col-reverse"]
      }],
      /**
       * Flex Wrap
       * @see https://tailwindcss.com/docs/flex-wrap
       */
      "flex-wrap": [{
        flex: ["wrap", "wrap-reverse", "nowrap"]
      }],
      /**
       * Flex
       * @see https://tailwindcss.com/docs/flex
       */
      flex: [{
        flex: ["1", "auto", "initial", "none", isArbitraryValue]
      }],
      /**
       * Flex Grow
       * @see https://tailwindcss.com/docs/flex-grow
       */
      grow: [{
        grow: getZeroAndEmpty()
      }],
      /**
       * Flex Shrink
       * @see https://tailwindcss.com/docs/flex-shrink
       */
      shrink: [{
        shrink: getZeroAndEmpty()
      }],
      /**
       * Order
       * @see https://tailwindcss.com/docs/order
       */
      order: [{
        order: ["first", "last", "none", isInteger2, isArbitraryValue]
      }],
      /**
       * Grid Template Columns
       * @see https://tailwindcss.com/docs/grid-template-columns
       */
      "grid-cols": [{
        "grid-cols": [isAny]
      }],
      /**
       * Grid Column Start / End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start-end": [{
        col: ["auto", {
          span: ["full", isInteger2, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Column Start
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-start": [{
        "col-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Column End
       * @see https://tailwindcss.com/docs/grid-column
       */
      "col-end": [{
        "col-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Template Rows
       * @see https://tailwindcss.com/docs/grid-template-rows
       */
      "grid-rows": [{
        "grid-rows": [isAny]
      }],
      /**
       * Grid Row Start / End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start-end": [{
        row: ["auto", {
          span: [isInteger2, isArbitraryValue]
        }, isArbitraryValue]
      }],
      /**
       * Grid Row Start
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-start": [{
        "row-start": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Row End
       * @see https://tailwindcss.com/docs/grid-row
       */
      "row-end": [{
        "row-end": getNumberWithAutoAndArbitrary()
      }],
      /**
       * Grid Auto Flow
       * @see https://tailwindcss.com/docs/grid-auto-flow
       */
      "grid-flow": [{
        "grid-flow": ["row", "col", "dense", "row-dense", "col-dense"]
      }],
      /**
       * Grid Auto Columns
       * @see https://tailwindcss.com/docs/grid-auto-columns
       */
      "auto-cols": [{
        "auto-cols": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Grid Auto Rows
       * @see https://tailwindcss.com/docs/grid-auto-rows
       */
      "auto-rows": [{
        "auto-rows": ["auto", "min", "max", "fr", isArbitraryValue]
      }],
      /**
       * Gap
       * @see https://tailwindcss.com/docs/gap
       */
      gap: [{
        gap: [gap]
      }],
      /**
       * Gap X
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-x": [{
        "gap-x": [gap]
      }],
      /**
       * Gap Y
       * @see https://tailwindcss.com/docs/gap
       */
      "gap-y": [{
        "gap-y": [gap]
      }],
      /**
       * Justify Content
       * @see https://tailwindcss.com/docs/justify-content
       */
      "justify-content": [{
        justify: ["normal", ...getAlign()]
      }],
      /**
       * Justify Items
       * @see https://tailwindcss.com/docs/justify-items
       */
      "justify-items": [{
        "justify-items": ["start", "end", "center", "stretch"]
      }],
      /**
       * Justify Self
       * @see https://tailwindcss.com/docs/justify-self
       */
      "justify-self": [{
        "justify-self": ["auto", "start", "end", "center", "stretch"]
      }],
      /**
       * Align Content
       * @see https://tailwindcss.com/docs/align-content
       */
      "align-content": [{
        content: ["normal", ...getAlign(), "baseline"]
      }],
      /**
       * Align Items
       * @see https://tailwindcss.com/docs/align-items
       */
      "align-items": [{
        items: ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Align Self
       * @see https://tailwindcss.com/docs/align-self
       */
      "align-self": [{
        self: ["auto", "start", "end", "center", "stretch", "baseline"]
      }],
      /**
       * Place Content
       * @see https://tailwindcss.com/docs/place-content
       */
      "place-content": [{
        "place-content": [...getAlign(), "baseline"]
      }],
      /**
       * Place Items
       * @see https://tailwindcss.com/docs/place-items
       */
      "place-items": [{
        "place-items": ["start", "end", "center", "baseline", "stretch"]
      }],
      /**
       * Place Self
       * @see https://tailwindcss.com/docs/place-self
       */
      "place-self": [{
        "place-self": ["auto", "start", "end", "center", "stretch"]
      }],
      // Spacing
      /**
       * Padding
       * @see https://tailwindcss.com/docs/padding
       */
      p: [{
        p: [padding]
      }],
      /**
       * Padding X
       * @see https://tailwindcss.com/docs/padding
       */
      px: [{
        px: [padding]
      }],
      /**
       * Padding Y
       * @see https://tailwindcss.com/docs/padding
       */
      py: [{
        py: [padding]
      }],
      /**
       * Padding Start
       * @see https://tailwindcss.com/docs/padding
       */
      ps: [{
        ps: [padding]
      }],
      /**
       * Padding End
       * @see https://tailwindcss.com/docs/padding
       */
      pe: [{
        pe: [padding]
      }],
      /**
       * Padding Top
       * @see https://tailwindcss.com/docs/padding
       */
      pt: [{
        pt: [padding]
      }],
      /**
       * Padding Right
       * @see https://tailwindcss.com/docs/padding
       */
      pr: [{
        pr: [padding]
      }],
      /**
       * Padding Bottom
       * @see https://tailwindcss.com/docs/padding
       */
      pb: [{
        pb: [padding]
      }],
      /**
       * Padding Left
       * @see https://tailwindcss.com/docs/padding
       */
      pl: [{
        pl: [padding]
      }],
      /**
       * Margin
       * @see https://tailwindcss.com/docs/margin
       */
      m: [{
        m: [margin]
      }],
      /**
       * Margin X
       * @see https://tailwindcss.com/docs/margin
       */
      mx: [{
        mx: [margin]
      }],
      /**
       * Margin Y
       * @see https://tailwindcss.com/docs/margin
       */
      my: [{
        my: [margin]
      }],
      /**
       * Margin Start
       * @see https://tailwindcss.com/docs/margin
       */
      ms: [{
        ms: [margin]
      }],
      /**
       * Margin End
       * @see https://tailwindcss.com/docs/margin
       */
      me: [{
        me: [margin]
      }],
      /**
       * Margin Top
       * @see https://tailwindcss.com/docs/margin
       */
      mt: [{
        mt: [margin]
      }],
      /**
       * Margin Right
       * @see https://tailwindcss.com/docs/margin
       */
      mr: [{
        mr: [margin]
      }],
      /**
       * Margin Bottom
       * @see https://tailwindcss.com/docs/margin
       */
      mb: [{
        mb: [margin]
      }],
      /**
       * Margin Left
       * @see https://tailwindcss.com/docs/margin
       */
      ml: [{
        ml: [margin]
      }],
      /**
       * Space Between X
       * @see https://tailwindcss.com/docs/space
       */
      "space-x": [{
        "space-x": [space]
      }],
      /**
       * Space Between X Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-x-reverse": ["space-x-reverse"],
      /**
       * Space Between Y
       * @see https://tailwindcss.com/docs/space
       */
      "space-y": [{
        "space-y": [space]
      }],
      /**
       * Space Between Y Reverse
       * @see https://tailwindcss.com/docs/space
       */
      "space-y-reverse": ["space-y-reverse"],
      // Sizing
      /**
       * Width
       * @see https://tailwindcss.com/docs/width
       */
      w: [{
        w: ["auto", "min", "max", "fit", "svw", "lvw", "dvw", isArbitraryValue, spacing]
      }],
      /**
       * Min-Width
       * @see https://tailwindcss.com/docs/min-width
       */
      "min-w": [{
        "min-w": [isArbitraryValue, spacing, "min", "max", "fit"]
      }],
      /**
       * Max-Width
       * @see https://tailwindcss.com/docs/max-width
       */
      "max-w": [{
        "max-w": [isArbitraryValue, spacing, "none", "full", "min", "max", "fit", "prose", {
          screen: [isTshirtSize]
        }, isTshirtSize]
      }],
      /**
       * Height
       * @see https://tailwindcss.com/docs/height
       */
      h: [{
        h: [isArbitraryValue, spacing, "auto", "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Min-Height
       * @see https://tailwindcss.com/docs/min-height
       */
      "min-h": [{
        "min-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Max-Height
       * @see https://tailwindcss.com/docs/max-height
       */
      "max-h": [{
        "max-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"]
      }],
      /**
       * Size
       * @see https://tailwindcss.com/docs/size
       */
      size: [{
        size: [isArbitraryValue, spacing, "auto", "min", "max", "fit"]
      }],
      // Typography
      /**
       * Font Size
       * @see https://tailwindcss.com/docs/font-size
       */
      "font-size": [{
        text: ["base", isTshirtSize, isArbitraryLength]
      }],
      /**
       * Font Smoothing
       * @see https://tailwindcss.com/docs/font-smoothing
       */
      "font-smoothing": ["antialiased", "subpixel-antialiased"],
      /**
       * Font Style
       * @see https://tailwindcss.com/docs/font-style
       */
      "font-style": ["italic", "not-italic"],
      /**
       * Font Weight
       * @see https://tailwindcss.com/docs/font-weight
       */
      "font-weight": [{
        font: ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black", isArbitraryNumber]
      }],
      /**
       * Font Family
       * @see https://tailwindcss.com/docs/font-family
       */
      "font-family": [{
        font: [isAny]
      }],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-normal": ["normal-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-ordinal": ["ordinal"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-slashed-zero": ["slashed-zero"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-figure": ["lining-nums", "oldstyle-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-spacing": ["proportional-nums", "tabular-nums"],
      /**
       * Font Variant Numeric
       * @see https://tailwindcss.com/docs/font-variant-numeric
       */
      "fvn-fraction": ["diagonal-fractions", "stacked-fractions"],
      /**
       * Letter Spacing
       * @see https://tailwindcss.com/docs/letter-spacing
       */
      tracking: [{
        tracking: ["tighter", "tight", "normal", "wide", "wider", "widest", isArbitraryValue]
      }],
      /**
       * Line Clamp
       * @see https://tailwindcss.com/docs/line-clamp
       */
      "line-clamp": [{
        "line-clamp": ["none", isNumber, isArbitraryNumber]
      }],
      /**
       * Line Height
       * @see https://tailwindcss.com/docs/line-height
       */
      leading: [{
        leading: ["none", "tight", "snug", "normal", "relaxed", "loose", isLength, isArbitraryValue]
      }],
      /**
       * List Style Image
       * @see https://tailwindcss.com/docs/list-style-image
       */
      "list-image": [{
        "list-image": ["none", isArbitraryValue]
      }],
      /**
       * List Style Type
       * @see https://tailwindcss.com/docs/list-style-type
       */
      "list-style-type": [{
        list: ["none", "disc", "decimal", isArbitraryValue]
      }],
      /**
       * List Style Position
       * @see https://tailwindcss.com/docs/list-style-position
       */
      "list-style-position": [{
        list: ["inside", "outside"]
      }],
      /**
       * Placeholder Color
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/placeholder-color
       */
      "placeholder-color": [{
        placeholder: [colors]
      }],
      /**
       * Placeholder Opacity
       * @see https://tailwindcss.com/docs/placeholder-opacity
       */
      "placeholder-opacity": [{
        "placeholder-opacity": [opacity]
      }],
      /**
       * Text Alignment
       * @see https://tailwindcss.com/docs/text-align
       */
      "text-alignment": [{
        text: ["left", "center", "right", "justify", "start", "end"]
      }],
      /**
       * Text Color
       * @see https://tailwindcss.com/docs/text-color
       */
      "text-color": [{
        text: [colors]
      }],
      /**
       * Text Opacity
       * @see https://tailwindcss.com/docs/text-opacity
       */
      "text-opacity": [{
        "text-opacity": [opacity]
      }],
      /**
       * Text Decoration
       * @see https://tailwindcss.com/docs/text-decoration
       */
      "text-decoration": ["underline", "overline", "line-through", "no-underline"],
      /**
       * Text Decoration Style
       * @see https://tailwindcss.com/docs/text-decoration-style
       */
      "text-decoration-style": [{
        decoration: [...getLineStyles(), "wavy"]
      }],
      /**
       * Text Decoration Thickness
       * @see https://tailwindcss.com/docs/text-decoration-thickness
       */
      "text-decoration-thickness": [{
        decoration: ["auto", "from-font", isLength, isArbitraryLength]
      }],
      /**
       * Text Underline Offset
       * @see https://tailwindcss.com/docs/text-underline-offset
       */
      "underline-offset": [{
        "underline-offset": ["auto", isLength, isArbitraryValue]
      }],
      /**
       * Text Decoration Color
       * @see https://tailwindcss.com/docs/text-decoration-color
       */
      "text-decoration-color": [{
        decoration: [colors]
      }],
      /**
       * Text Transform
       * @see https://tailwindcss.com/docs/text-transform
       */
      "text-transform": ["uppercase", "lowercase", "capitalize", "normal-case"],
      /**
       * Text Overflow
       * @see https://tailwindcss.com/docs/text-overflow
       */
      "text-overflow": ["truncate", "text-ellipsis", "text-clip"],
      /**
       * Text Wrap
       * @see https://tailwindcss.com/docs/text-wrap
       */
      "text-wrap": [{
        text: ["wrap", "nowrap", "balance", "pretty"]
      }],
      /**
       * Text Indent
       * @see https://tailwindcss.com/docs/text-indent
       */
      indent: [{
        indent: getSpacingWithArbitrary()
      }],
      /**
       * Vertical Alignment
       * @see https://tailwindcss.com/docs/vertical-align
       */
      "vertical-align": [{
        align: ["baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", isArbitraryValue]
      }],
      /**
       * Whitespace
       * @see https://tailwindcss.com/docs/whitespace
       */
      whitespace: [{
        whitespace: ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"]
      }],
      /**
       * Word Break
       * @see https://tailwindcss.com/docs/word-break
       */
      break: [{
        break: ["normal", "words", "all", "keep"]
      }],
      /**
       * Hyphens
       * @see https://tailwindcss.com/docs/hyphens
       */
      hyphens: [{
        hyphens: ["none", "manual", "auto"]
      }],
      /**
       * Content
       * @see https://tailwindcss.com/docs/content
       */
      content: [{
        content: ["none", isArbitraryValue]
      }],
      // Backgrounds
      /**
       * Background Attachment
       * @see https://tailwindcss.com/docs/background-attachment
       */
      "bg-attachment": [{
        bg: ["fixed", "local", "scroll"]
      }],
      /**
       * Background Clip
       * @see https://tailwindcss.com/docs/background-clip
       */
      "bg-clip": [{
        "bg-clip": ["border", "padding", "content", "text"]
      }],
      /**
       * Background Opacity
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/background-opacity
       */
      "bg-opacity": [{
        "bg-opacity": [opacity]
      }],
      /**
       * Background Origin
       * @see https://tailwindcss.com/docs/background-origin
       */
      "bg-origin": [{
        "bg-origin": ["border", "padding", "content"]
      }],
      /**
       * Background Position
       * @see https://tailwindcss.com/docs/background-position
       */
      "bg-position": [{
        bg: [...getPositions(), isArbitraryPosition]
      }],
      /**
       * Background Repeat
       * @see https://tailwindcss.com/docs/background-repeat
       */
      "bg-repeat": [{
        bg: ["no-repeat", {
          repeat: ["", "x", "y", "round", "space"]
        }]
      }],
      /**
       * Background Size
       * @see https://tailwindcss.com/docs/background-size
       */
      "bg-size": [{
        bg: ["auto", "cover", "contain", isArbitrarySize]
      }],
      /**
       * Background Image
       * @see https://tailwindcss.com/docs/background-image
       */
      "bg-image": [{
        bg: ["none", {
          "gradient-to": ["t", "tr", "r", "br", "b", "bl", "l", "tl"]
        }, isArbitraryImage]
      }],
      /**
       * Background Color
       * @see https://tailwindcss.com/docs/background-color
       */
      "bg-color": [{
        bg: [colors]
      }],
      /**
       * Gradient Color Stops From Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from-pos": [{
        from: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops Via Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via-pos": [{
        via: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops To Position
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to-pos": [{
        to: [gradientColorStopPositions]
      }],
      /**
       * Gradient Color Stops From
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-from": [{
        from: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops Via
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-via": [{
        via: [gradientColorStops]
      }],
      /**
       * Gradient Color Stops To
       * @see https://tailwindcss.com/docs/gradient-color-stops
       */
      "gradient-to": [{
        to: [gradientColorStops]
      }],
      // Borders
      /**
       * Border Radius
       * @see https://tailwindcss.com/docs/border-radius
       */
      rounded: [{
        rounded: [borderRadius]
      }],
      /**
       * Border Radius Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-s": [{
        "rounded-s": [borderRadius]
      }],
      /**
       * Border Radius End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-e": [{
        "rounded-e": [borderRadius]
      }],
      /**
       * Border Radius Top
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-t": [{
        "rounded-t": [borderRadius]
      }],
      /**
       * Border Radius Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-r": [{
        "rounded-r": [borderRadius]
      }],
      /**
       * Border Radius Bottom
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-b": [{
        "rounded-b": [borderRadius]
      }],
      /**
       * Border Radius Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-l": [{
        "rounded-l": [borderRadius]
      }],
      /**
       * Border Radius Start Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ss": [{
        "rounded-ss": [borderRadius]
      }],
      /**
       * Border Radius Start End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-se": [{
        "rounded-se": [borderRadius]
      }],
      /**
       * Border Radius End End
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-ee": [{
        "rounded-ee": [borderRadius]
      }],
      /**
       * Border Radius End Start
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-es": [{
        "rounded-es": [borderRadius]
      }],
      /**
       * Border Radius Top Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tl": [{
        "rounded-tl": [borderRadius]
      }],
      /**
       * Border Radius Top Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-tr": [{
        "rounded-tr": [borderRadius]
      }],
      /**
       * Border Radius Bottom Right
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-br": [{
        "rounded-br": [borderRadius]
      }],
      /**
       * Border Radius Bottom Left
       * @see https://tailwindcss.com/docs/border-radius
       */
      "rounded-bl": [{
        "rounded-bl": [borderRadius]
      }],
      /**
       * Border Width
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w": [{
        border: [borderWidth]
      }],
      /**
       * Border Width X
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-x": [{
        "border-x": [borderWidth]
      }],
      /**
       * Border Width Y
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-y": [{
        "border-y": [borderWidth]
      }],
      /**
       * Border Width Start
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-s": [{
        "border-s": [borderWidth]
      }],
      /**
       * Border Width End
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-e": [{
        "border-e": [borderWidth]
      }],
      /**
       * Border Width Top
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-t": [{
        "border-t": [borderWidth]
      }],
      /**
       * Border Width Right
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-r": [{
        "border-r": [borderWidth]
      }],
      /**
       * Border Width Bottom
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-b": [{
        "border-b": [borderWidth]
      }],
      /**
       * Border Width Left
       * @see https://tailwindcss.com/docs/border-width
       */
      "border-w-l": [{
        "border-l": [borderWidth]
      }],
      /**
       * Border Opacity
       * @see https://tailwindcss.com/docs/border-opacity
       */
      "border-opacity": [{
        "border-opacity": [opacity]
      }],
      /**
       * Border Style
       * @see https://tailwindcss.com/docs/border-style
       */
      "border-style": [{
        border: [...getLineStyles(), "hidden"]
      }],
      /**
       * Divide Width X
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x": [{
        "divide-x": [borderWidth]
      }],
      /**
       * Divide Width X Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-x-reverse": ["divide-x-reverse"],
      /**
       * Divide Width Y
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y": [{
        "divide-y": [borderWidth]
      }],
      /**
       * Divide Width Y Reverse
       * @see https://tailwindcss.com/docs/divide-width
       */
      "divide-y-reverse": ["divide-y-reverse"],
      /**
       * Divide Opacity
       * @see https://tailwindcss.com/docs/divide-opacity
       */
      "divide-opacity": [{
        "divide-opacity": [opacity]
      }],
      /**
       * Divide Style
       * @see https://tailwindcss.com/docs/divide-style
       */
      "divide-style": [{
        divide: getLineStyles()
      }],
      /**
       * Border Color
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color": [{
        border: [borderColor]
      }],
      /**
       * Border Color X
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-x": [{
        "border-x": [borderColor]
      }],
      /**
       * Border Color Y
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-y": [{
        "border-y": [borderColor]
      }],
      /**
       * Border Color S
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-s": [{
        "border-s": [borderColor]
      }],
      /**
       * Border Color E
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-e": [{
        "border-e": [borderColor]
      }],
      /**
       * Border Color Top
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-t": [{
        "border-t": [borderColor]
      }],
      /**
       * Border Color Right
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-r": [{
        "border-r": [borderColor]
      }],
      /**
       * Border Color Bottom
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-b": [{
        "border-b": [borderColor]
      }],
      /**
       * Border Color Left
       * @see https://tailwindcss.com/docs/border-color
       */
      "border-color-l": [{
        "border-l": [borderColor]
      }],
      /**
       * Divide Color
       * @see https://tailwindcss.com/docs/divide-color
       */
      "divide-color": [{
        divide: [borderColor]
      }],
      /**
       * Outline Style
       * @see https://tailwindcss.com/docs/outline-style
       */
      "outline-style": [{
        outline: ["", ...getLineStyles()]
      }],
      /**
       * Outline Offset
       * @see https://tailwindcss.com/docs/outline-offset
       */
      "outline-offset": [{
        "outline-offset": [isLength, isArbitraryValue]
      }],
      /**
       * Outline Width
       * @see https://tailwindcss.com/docs/outline-width
       */
      "outline-w": [{
        outline: [isLength, isArbitraryLength]
      }],
      /**
       * Outline Color
       * @see https://tailwindcss.com/docs/outline-color
       */
      "outline-color": [{
        outline: [colors]
      }],
      /**
       * Ring Width
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w": [{
        ring: getLengthWithEmptyAndArbitrary()
      }],
      /**
       * Ring Width Inset
       * @see https://tailwindcss.com/docs/ring-width
       */
      "ring-w-inset": ["ring-inset"],
      /**
       * Ring Color
       * @see https://tailwindcss.com/docs/ring-color
       */
      "ring-color": [{
        ring: [colors]
      }],
      /**
       * Ring Opacity
       * @see https://tailwindcss.com/docs/ring-opacity
       */
      "ring-opacity": [{
        "ring-opacity": [opacity]
      }],
      /**
       * Ring Offset Width
       * @see https://tailwindcss.com/docs/ring-offset-width
       */
      "ring-offset-w": [{
        "ring-offset": [isLength, isArbitraryLength]
      }],
      /**
       * Ring Offset Color
       * @see https://tailwindcss.com/docs/ring-offset-color
       */
      "ring-offset-color": [{
        "ring-offset": [colors]
      }],
      // Effects
      /**
       * Box Shadow
       * @see https://tailwindcss.com/docs/box-shadow
       */
      shadow: [{
        shadow: ["", "inner", "none", isTshirtSize, isArbitraryShadow]
      }],
      /**
       * Box Shadow Color
       * @see https://tailwindcss.com/docs/box-shadow-color
       */
      "shadow-color": [{
        shadow: [isAny]
      }],
      /**
       * Opacity
       * @see https://tailwindcss.com/docs/opacity
       */
      opacity: [{
        opacity: [opacity]
      }],
      /**
       * Mix Blend Mode
       * @see https://tailwindcss.com/docs/mix-blend-mode
       */
      "mix-blend": [{
        "mix-blend": [...getBlendModes(), "plus-lighter", "plus-darker"]
      }],
      /**
       * Background Blend Mode
       * @see https://tailwindcss.com/docs/background-blend-mode
       */
      "bg-blend": [{
        "bg-blend": getBlendModes()
      }],
      // Filters
      /**
       * Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/filter
       */
      filter: [{
        filter: ["", "none"]
      }],
      /**
       * Blur
       * @see https://tailwindcss.com/docs/blur
       */
      blur: [{
        blur: [blur]
      }],
      /**
       * Brightness
       * @see https://tailwindcss.com/docs/brightness
       */
      brightness: [{
        brightness: [brightness]
      }],
      /**
       * Contrast
       * @see https://tailwindcss.com/docs/contrast
       */
      contrast: [{
        contrast: [contrast]
      }],
      /**
       * Drop Shadow
       * @see https://tailwindcss.com/docs/drop-shadow
       */
      "drop-shadow": [{
        "drop-shadow": ["", "none", isTshirtSize, isArbitraryValue]
      }],
      /**
       * Grayscale
       * @see https://tailwindcss.com/docs/grayscale
       */
      grayscale: [{
        grayscale: [grayscale]
      }],
      /**
       * Hue Rotate
       * @see https://tailwindcss.com/docs/hue-rotate
       */
      "hue-rotate": [{
        "hue-rotate": [hueRotate]
      }],
      /**
       * Invert
       * @see https://tailwindcss.com/docs/invert
       */
      invert: [{
        invert: [invert]
      }],
      /**
       * Saturate
       * @see https://tailwindcss.com/docs/saturate
       */
      saturate: [{
        saturate: [saturate]
      }],
      /**
       * Sepia
       * @see https://tailwindcss.com/docs/sepia
       */
      sepia: [{
        sepia: [sepia]
      }],
      /**
       * Backdrop Filter
       * @deprecated since Tailwind CSS v3.0.0
       * @see https://tailwindcss.com/docs/backdrop-filter
       */
      "backdrop-filter": [{
        "backdrop-filter": ["", "none"]
      }],
      /**
       * Backdrop Blur
       * @see https://tailwindcss.com/docs/backdrop-blur
       */
      "backdrop-blur": [{
        "backdrop-blur": [blur]
      }],
      /**
       * Backdrop Brightness
       * @see https://tailwindcss.com/docs/backdrop-brightness
       */
      "backdrop-brightness": [{
        "backdrop-brightness": [brightness]
      }],
      /**
       * Backdrop Contrast
       * @see https://tailwindcss.com/docs/backdrop-contrast
       */
      "backdrop-contrast": [{
        "backdrop-contrast": [contrast]
      }],
      /**
       * Backdrop Grayscale
       * @see https://tailwindcss.com/docs/backdrop-grayscale
       */
      "backdrop-grayscale": [{
        "backdrop-grayscale": [grayscale]
      }],
      /**
       * Backdrop Hue Rotate
       * @see https://tailwindcss.com/docs/backdrop-hue-rotate
       */
      "backdrop-hue-rotate": [{
        "backdrop-hue-rotate": [hueRotate]
      }],
      /**
       * Backdrop Invert
       * @see https://tailwindcss.com/docs/backdrop-invert
       */
      "backdrop-invert": [{
        "backdrop-invert": [invert]
      }],
      /**
       * Backdrop Opacity
       * @see https://tailwindcss.com/docs/backdrop-opacity
       */
      "backdrop-opacity": [{
        "backdrop-opacity": [opacity]
      }],
      /**
       * Backdrop Saturate
       * @see https://tailwindcss.com/docs/backdrop-saturate
       */
      "backdrop-saturate": [{
        "backdrop-saturate": [saturate]
      }],
      /**
       * Backdrop Sepia
       * @see https://tailwindcss.com/docs/backdrop-sepia
       */
      "backdrop-sepia": [{
        "backdrop-sepia": [sepia]
      }],
      // Tables
      /**
       * Border Collapse
       * @see https://tailwindcss.com/docs/border-collapse
       */
      "border-collapse": [{
        border: ["collapse", "separate"]
      }],
      /**
       * Border Spacing
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing": [{
        "border-spacing": [borderSpacing]
      }],
      /**
       * Border Spacing X
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-x": [{
        "border-spacing-x": [borderSpacing]
      }],
      /**
       * Border Spacing Y
       * @see https://tailwindcss.com/docs/border-spacing
       */
      "border-spacing-y": [{
        "border-spacing-y": [borderSpacing]
      }],
      /**
       * Table Layout
       * @see https://tailwindcss.com/docs/table-layout
       */
      "table-layout": [{
        table: ["auto", "fixed"]
      }],
      /**
       * Caption Side
       * @see https://tailwindcss.com/docs/caption-side
       */
      caption: [{
        caption: ["top", "bottom"]
      }],
      // Transitions and Animation
      /**
       * Tranisition Property
       * @see https://tailwindcss.com/docs/transition-property
       */
      transition: [{
        transition: ["none", "all", "", "colors", "opacity", "shadow", "transform", isArbitraryValue]
      }],
      /**
       * Transition Duration
       * @see https://tailwindcss.com/docs/transition-duration
       */
      duration: [{
        duration: getNumberAndArbitrary()
      }],
      /**
       * Transition Timing Function
       * @see https://tailwindcss.com/docs/transition-timing-function
       */
      ease: [{
        ease: ["linear", "in", "out", "in-out", isArbitraryValue]
      }],
      /**
       * Transition Delay
       * @see https://tailwindcss.com/docs/transition-delay
       */
      delay: [{
        delay: getNumberAndArbitrary()
      }],
      /**
       * Animation
       * @see https://tailwindcss.com/docs/animation
       */
      animate: [{
        animate: ["none", "spin", "ping", "pulse", "bounce", isArbitraryValue]
      }],
      // Transforms
      /**
       * Transform
       * @see https://tailwindcss.com/docs/transform
       */
      transform: [{
        transform: ["", "gpu", "none"]
      }],
      /**
       * Scale
       * @see https://tailwindcss.com/docs/scale
       */
      scale: [{
        scale: [scale]
      }],
      /**
       * Scale X
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-x": [{
        "scale-x": [scale]
      }],
      /**
       * Scale Y
       * @see https://tailwindcss.com/docs/scale
       */
      "scale-y": [{
        "scale-y": [scale]
      }],
      /**
       * Rotate
       * @see https://tailwindcss.com/docs/rotate
       */
      rotate: [{
        rotate: [isInteger2, isArbitraryValue]
      }],
      /**
       * Translate X
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-x": [{
        "translate-x": [translate]
      }],
      /**
       * Translate Y
       * @see https://tailwindcss.com/docs/translate
       */
      "translate-y": [{
        "translate-y": [translate]
      }],
      /**
       * Skew X
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-x": [{
        "skew-x": [skew]
      }],
      /**
       * Skew Y
       * @see https://tailwindcss.com/docs/skew
       */
      "skew-y": [{
        "skew-y": [skew]
      }],
      /**
       * Transform Origin
       * @see https://tailwindcss.com/docs/transform-origin
       */
      "transform-origin": [{
        origin: ["center", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", "left", "top-left", isArbitraryValue]
      }],
      // Interactivity
      /**
       * Accent Color
       * @see https://tailwindcss.com/docs/accent-color
       */
      accent: [{
        accent: ["auto", colors]
      }],
      /**
       * Appearance
       * @see https://tailwindcss.com/docs/appearance
       */
      appearance: [{
        appearance: ["none", "auto"]
      }],
      /**
       * Cursor
       * @see https://tailwindcss.com/docs/cursor
       */
      cursor: [{
        cursor: ["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none", "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing", "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out", isArbitraryValue]
      }],
      /**
       * Caret Color
       * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities
       */
      "caret-color": [{
        caret: [colors]
      }],
      /**
       * Pointer Events
       * @see https://tailwindcss.com/docs/pointer-events
       */
      "pointer-events": [{
        "pointer-events": ["none", "auto"]
      }],
      /**
       * Resize
       * @see https://tailwindcss.com/docs/resize
       */
      resize: [{
        resize: ["none", "y", "x", ""]
      }],
      /**
       * Scroll Behavior
       * @see https://tailwindcss.com/docs/scroll-behavior
       */
      "scroll-behavior": [{
        scroll: ["auto", "smooth"]
      }],
      /**
       * Scroll Margin
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-m": [{
        "scroll-m": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin X
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mx": [{
        "scroll-mx": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Y
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-my": [{
        "scroll-my": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Start
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ms": [{
        "scroll-ms": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin End
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-me": [{
        "scroll-me": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Top
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mt": [{
        "scroll-mt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Right
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mr": [{
        "scroll-mr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Bottom
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-mb": [{
        "scroll-mb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Margin Left
       * @see https://tailwindcss.com/docs/scroll-margin
       */
      "scroll-ml": [{
        "scroll-ml": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-p": [{
        "scroll-p": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding X
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-px": [{
        "scroll-px": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Y
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-py": [{
        "scroll-py": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Start
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-ps": [{
        "scroll-ps": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding End
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pe": [{
        "scroll-pe": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Top
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pt": [{
        "scroll-pt": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Right
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pr": [{
        "scroll-pr": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Bottom
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pb": [{
        "scroll-pb": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Padding Left
       * @see https://tailwindcss.com/docs/scroll-padding
       */
      "scroll-pl": [{
        "scroll-pl": getSpacingWithArbitrary()
      }],
      /**
       * Scroll Snap Align
       * @see https://tailwindcss.com/docs/scroll-snap-align
       */
      "snap-align": [{
        snap: ["start", "end", "center", "align-none"]
      }],
      /**
       * Scroll Snap Stop
       * @see https://tailwindcss.com/docs/scroll-snap-stop
       */
      "snap-stop": [{
        snap: ["normal", "always"]
      }],
      /**
       * Scroll Snap Type
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-type": [{
        snap: ["none", "x", "y", "both"]
      }],
      /**
       * Scroll Snap Type Strictness
       * @see https://tailwindcss.com/docs/scroll-snap-type
       */
      "snap-strictness": [{
        snap: ["mandatory", "proximity"]
      }],
      /**
       * Touch Action
       * @see https://tailwindcss.com/docs/touch-action
       */
      touch: [{
        touch: ["auto", "none", "manipulation"]
      }],
      /**
       * Touch Action X
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-x": [{
        "touch-pan": ["x", "left", "right"]
      }],
      /**
       * Touch Action Y
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-y": [{
        "touch-pan": ["y", "up", "down"]
      }],
      /**
       * Touch Action Pinch Zoom
       * @see https://tailwindcss.com/docs/touch-action
       */
      "touch-pz": ["touch-pinch-zoom"],
      /**
       * User Select
       * @see https://tailwindcss.com/docs/user-select
       */
      select: [{
        select: ["none", "text", "all", "auto"]
      }],
      /**
       * Will Change
       * @see https://tailwindcss.com/docs/will-change
       */
      "will-change": [{
        "will-change": ["auto", "scroll", "contents", "transform", isArbitraryValue]
      }],
      // SVG
      /**
       * Fill
       * @see https://tailwindcss.com/docs/fill
       */
      fill: [{
        fill: [colors, "none"]
      }],
      /**
       * Stroke Width
       * @see https://tailwindcss.com/docs/stroke-width
       */
      "stroke-w": [{
        stroke: [isLength, isArbitraryLength, isArbitraryNumber]
      }],
      /**
       * Stroke
       * @see https://tailwindcss.com/docs/stroke
       */
      stroke: [{
        stroke: [colors, "none"]
      }],
      // Accessibility
      /**
       * Screen Readers
       * @see https://tailwindcss.com/docs/screen-readers
       */
      sr: ["sr-only", "not-sr-only"],
      /**
       * Forced Color Adjust
       * @see https://tailwindcss.com/docs/forced-color-adjust
       */
      "forced-color-adjust": [{
        "forced-color-adjust": ["auto", "none"]
      }]
    },
    conflictingClassGroups: {
      overflow: ["overflow-x", "overflow-y"],
      overscroll: ["overscroll-x", "overscroll-y"],
      inset: ["inset-x", "inset-y", "start", "end", "top", "right", "bottom", "left"],
      "inset-x": ["right", "left"],
      "inset-y": ["top", "bottom"],
      flex: ["basis", "grow", "shrink"],
      gap: ["gap-x", "gap-y"],
      p: ["px", "py", "ps", "pe", "pt", "pr", "pb", "pl"],
      px: ["pr", "pl"],
      py: ["pt", "pb"],
      m: ["mx", "my", "ms", "me", "mt", "mr", "mb", "ml"],
      mx: ["mr", "ml"],
      my: ["mt", "mb"],
      size: ["w", "h"],
      "font-size": ["leading"],
      "fvn-normal": ["fvn-ordinal", "fvn-slashed-zero", "fvn-figure", "fvn-spacing", "fvn-fraction"],
      "fvn-ordinal": ["fvn-normal"],
      "fvn-slashed-zero": ["fvn-normal"],
      "fvn-figure": ["fvn-normal"],
      "fvn-spacing": ["fvn-normal"],
      "fvn-fraction": ["fvn-normal"],
      "line-clamp": ["display", "overflow"],
      rounded: ["rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"],
      "rounded-s": ["rounded-ss", "rounded-es"],
      "rounded-e": ["rounded-se", "rounded-ee"],
      "rounded-t": ["rounded-tl", "rounded-tr"],
      "rounded-r": ["rounded-tr", "rounded-br"],
      "rounded-b": ["rounded-br", "rounded-bl"],
      "rounded-l": ["rounded-tl", "rounded-bl"],
      "border-spacing": ["border-spacing-x", "border-spacing-y"],
      "border-w": ["border-w-s", "border-w-e", "border-w-t", "border-w-r", "border-w-b", "border-w-l"],
      "border-w-x": ["border-w-r", "border-w-l"],
      "border-w-y": ["border-w-t", "border-w-b"],
      "border-color": ["border-color-s", "border-color-e", "border-color-t", "border-color-r", "border-color-b", "border-color-l"],
      "border-color-x": ["border-color-r", "border-color-l"],
      "border-color-y": ["border-color-t", "border-color-b"],
      "scroll-m": ["scroll-mx", "scroll-my", "scroll-ms", "scroll-me", "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml"],
      "scroll-mx": ["scroll-mr", "scroll-ml"],
      "scroll-my": ["scroll-mt", "scroll-mb"],
      "scroll-p": ["scroll-px", "scroll-py", "scroll-ps", "scroll-pe", "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl"],
      "scroll-px": ["scroll-pr", "scroll-pl"],
      "scroll-py": ["scroll-pt", "scroll-pb"],
      touch: ["touch-x", "touch-y", "touch-pz"],
      "touch-x": ["touch"],
      "touch-y": ["touch"],
      "touch-pz": ["touch"]
    },
    conflictingClassGroupModifiers: {
      "font-size": ["leading"]
    }
  };
};
var mergeConfigs2 = (baseConfig, {
  cacheSize,
  prefix,
  separator,
  experimentalParseClassName,
  extend = {},
  override = {}
}) => {
  overrideProperty(baseConfig, "cacheSize", cacheSize);
  overrideProperty(baseConfig, "prefix", prefix);
  overrideProperty(baseConfig, "separator", separator);
  overrideProperty(baseConfig, "experimentalParseClassName", experimentalParseClassName);
  for (const configKey in override) {
    overrideConfigProperties(baseConfig[configKey], override[configKey]);
  }
  for (const key in extend) {
    mergeConfigProperties(baseConfig[key], extend[key]);
  }
  return baseConfig;
};
var overrideProperty = (baseObject, overrideKey, overrideValue) => {
  if (overrideValue !== void 0) {
    baseObject[overrideKey] = overrideValue;
  }
};
var overrideConfigProperties = (baseObject, overrideObject) => {
  if (overrideObject) {
    for (const key in overrideObject) {
      overrideProperty(baseObject, key, overrideObject[key]);
    }
  }
};
var mergeConfigProperties = (baseObject, mergeObject) => {
  if (mergeObject) {
    for (const key in mergeObject) {
      const mergeValue = mergeObject[key];
      if (mergeValue !== void 0) {
        baseObject[key] = (baseObject[key] || []).concat(mergeValue);
      }
    }
  }
};
var extendTailwindMerge = (configExtension, ...createConfig) => typeof configExtension === "function" ? createTailwindMerge(getDefaultConfig, configExtension, ...createConfig) : createTailwindMerge(() => mergeConfigs2(getDefaultConfig(), configExtension), ...createConfig);

// src/lib/utils.ts
var customTwMerge = extendTailwindMerge({
  extend: {
    classGroups: {
      "text-color": ["text-muted", "text-success", "text-warning", "text-error", "text-accent"],
      "font-size": [
        "text-smallest",
        "text-smaller",
        "text-small",
        "text-ui-smaller",
        "text-ui-small",
        "text-ui-medium",
        "text-ui-larger"
      ]
    }
  }
});
function cn(...inputs) {
  return customTwMerge(clsx(inputs));
}

// src/components/ui/button.tsx
var buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default: "bg-interactive-accent text-on-accent shadow hover:bg-interactive-accent/90",
        destructive: "bg-modifier-error text-normal shadow-sm hover:bg-modifier-error/90",
        outline: "border border-border bg-primary shadow-sm hover:bg-interactive-accent hover:text-on-accent",
        secondary: "bg-secondary text-normal shadow-sm hover:bg-secondary/80",
        ghost: "clickable-icon bg-transparent hover:bg-interactive-accent hover:text-on-accent",
        link: "text-accent underline-offset-4 hover:underline",
        ghost2: "text-faint clickable-icon bg-transparent hover:bg-opacity-100 hover:text-normal hover:bg-transparent outline-none focus-visible:outline-none focus-visible:text-on-accent focus-visible:ring-0"
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "size-7",
        fit: "px-1 text-xs gap-1"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
);
var Button = React3.forwardRef(
  ({ className, variant, size: size4, asChild = false, ...props }, ref) => {
    const Comp = asChild ? Slot : "button";
    return /* @__PURE__ */ React3.createElement(Comp, { className: cn(buttonVariants({ variant, size: size4, className })), ref, ...props });
  }
);
Button.displayName = "Button";

// node_modules/lucide-react/dist/esm/createLucideIcon.js
var import_react3 = __toESM(require_react());

// node_modules/lucide-react/dist/esm/shared/src/utils.js
var toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
var mergeClasses = (...classes) => classes.filter((className, index2, array) => {
  return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index2;
}).join(" ").trim();

// node_modules/lucide-react/dist/esm/Icon.js
var import_react2 = __toESM(require_react());

// node_modules/lucide-react/dist/esm/defaultAttributes.js
var defaultAttributes = {
  xmlns: "http://www.w3.org/2000/svg",
  width: 24,
  height: 24,
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 2,
  strokeLinecap: "round",
  strokeLinejoin: "round"
};

// node_modules/lucide-react/dist/esm/Icon.js
var Icon = (0, import_react2.forwardRef)(
  ({
    color: color2 = "currentColor",
    size: size4 = 24,
    strokeWidth = 2,
    absoluteStrokeWidth,
    className = "",
    children,
    iconNode,
    ...rest
  }, ref) => {
    return (0, import_react2.createElement)(
      "svg",
      {
        ref,
        ...defaultAttributes,
        width: size4,
        height: size4,
        stroke: color2,
        strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size4) : strokeWidth,
        className: mergeClasses("lucide", className),
        ...rest
      },
      [
        ...iconNode.map(([tag, attrs]) => (0, import_react2.createElement)(tag, attrs)),
        ...Array.isArray(children) ? children : [children]
      ]
    );
  }
);

// node_modules/lucide-react/dist/esm/createLucideIcon.js
var createLucideIcon = (iconName, iconNode) => {
  const Component2 = (0, import_react3.forwardRef)(
    ({ className, ...props }, ref) => (0, import_react3.createElement)(Icon, {
      ref,
      iconNode,
      className: mergeClasses(`lucide-${toKebabCase(iconName)}`, className),
      ...props
    })
  );
  Component2.displayName = `${iconName}`;
  return Component2;
};

// node_modules/lucide-react/dist/esm/icons/arrow-big-up.js
var ArrowBigUp = createLucideIcon("ArrowBigUp", [
  ["path", { d: "M9 18v-6H5l7-7 7 7h-4v6H9z", key: "1x06kx" }]
]);

// node_modules/lucide-react/dist/esm/icons/arrow-right.js
var ArrowRight = createLucideIcon("ArrowRight", [
  ["path", { d: "M5 12h14", key: "1ays0h" }],
  ["path", { d: "m12 5 7 7-7 7", key: "xquz4c" }]
]);

// node_modules/lucide-react/dist/esm/icons/bot.js
var Bot = createLucideIcon("Bot", [
  ["path", { d: "M12 8V4H8", key: "hb8ula" }],
  ["rect", { width: "16", height: "12", x: "4", y: "8", rx: "2", key: "enze0r" }],
  ["path", { d: "M2 14h2", key: "vft8re" }],
  ["path", { d: "M20 14h2", key: "4cs60a" }],
  ["path", { d: "M15 13v2", key: "1xurst" }],
  ["path", { d: "M9 13v2", key: "rq6x2g" }]
]);

// node_modules/lucide-react/dist/esm/icons/check.js
var Check = createLucideIcon("Check", [["path", { d: "M20 6 9 17l-5-5", key: "1gmf2c" }]]);

// node_modules/lucide-react/dist/esm/icons/chevron-down.js
var ChevronDown = createLucideIcon("ChevronDown", [
  ["path", { d: "m6 9 6 6 6-6", key: "qrunsl" }]
]);

// node_modules/lucide-react/dist/esm/icons/chevron-right.js
var ChevronRight = createLucideIcon("ChevronRight", [
  ["path", { d: "m9 18 6-6-6-6", key: "mthhwq" }]
]);

// node_modules/lucide-react/dist/esm/icons/chevron-up.js
var ChevronUp = createLucideIcon("ChevronUp", [["path", { d: "m18 15-6-6-6 6", key: "153udz" }]]);

// node_modules/lucide-react/dist/esm/icons/circle-help.js
var CircleHelp = createLucideIcon("CircleHelp", [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3", key: "1u773s" }],
  ["path", { d: "M12 17h.01", key: "p32p05" }]
]);

// node_modules/lucide-react/dist/esm/icons/circle-plus.js
var CirclePlus = createLucideIcon("CirclePlus", [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M8 12h8", key: "1wcyev" }],
  ["path", { d: "M12 8v8", key: "napkw2" }]
]);

// node_modules/lucide-react/dist/esm/icons/circle-stop.js
var CircleStop = createLucideIcon("CircleStop", [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["rect", { x: "9", y: "9", width: "6", height: "6", rx: "1", key: "1ssd4o" }]
]);

// node_modules/lucide-react/dist/esm/icons/circle.js
var Circle = createLucideIcon("Circle", [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }]
]);

// node_modules/lucide-react/dist/esm/icons/cog.js
var Cog = createLucideIcon("Cog", [
  ["path", { d: "M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z", key: "sobvz5" }],
  ["path", { d: "M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z", key: "11i496" }],
  ["path", { d: "M12 2v2", key: "tus03m" }],
  ["path", { d: "M12 22v-2", key: "1osdcq" }],
  ["path", { d: "m17 20.66-1-1.73", key: "eq3orb" }],
  ["path", { d: "M11 10.27 7 3.34", key: "16pf9h" }],
  ["path", { d: "m20.66 17-1.73-1", key: "sg0v6f" }],
  ["path", { d: "m3.34 7 1.73 1", key: "1ulond" }],
  ["path", { d: "M14 12h8", key: "4f43i9" }],
  ["path", { d: "M2 12h2", key: "1t8f8n" }],
  ["path", { d: "m20.66 7-1.73 1", key: "1ow05n" }],
  ["path", { d: "m3.34 17 1.73-1", key: "nuk764" }],
  ["path", { d: "m17 3.34-1 1.73", key: "2wel8s" }],
  ["path", { d: "m11 13.73-4 6.93", key: "794ttg" }]
]);

// node_modules/lucide-react/dist/esm/icons/command.js
var Command = createLucideIcon("Command", [
  [
    "path",
    { d: "M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3", key: "11bfej" }
  ]
]);

// node_modules/lucide-react/dist/esm/icons/copy.js
var Copy = createLucideIcon("Copy", [
  ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2", key: "17jyea" }],
  ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2", key: "zix9uf" }]
]);

// node_modules/lucide-react/dist/esm/icons/corner-down-left.js
var CornerDownLeft = createLucideIcon("CornerDownLeft", [
  ["polyline", { points: "9 10 4 15 9 20", key: "r3jprv" }],
  ["path", { d: "M20 4v7a4 4 0 0 1-4 4H4", key: "6o5b7l" }]
]);

// node_modules/lucide-react/dist/esm/icons/cpu.js
var Cpu = createLucideIcon("Cpu", [
  ["rect", { width: "16", height: "16", x: "4", y: "4", rx: "2", key: "14l7u7" }],
  ["rect", { width: "6", height: "6", x: "9", y: "9", rx: "1", key: "5aljv4" }],
  ["path", { d: "M15 2v2", key: "13l42r" }],
  ["path", { d: "M15 20v2", key: "15mkzm" }],
  ["path", { d: "M2 15h2", key: "1gxd5l" }],
  ["path", { d: "M2 9h2", key: "1bbxkp" }],
  ["path", { d: "M20 15h2", key: "19e6y8" }],
  ["path", { d: "M20 9h2", key: "19tzq7" }],
  ["path", { d: "M9 2v2", key: "165o2o" }],
  ["path", { d: "M9 20v2", key: "i2bqo8" }]
]);

// node_modules/lucide-react/dist/esm/icons/database.js
var Database = createLucideIcon("Database", [
  ["ellipse", { cx: "12", cy: "5", rx: "9", ry: "3", key: "msslwz" }],
  ["path", { d: "M3 5V19A9 3 0 0 0 21 19V5", key: "1wlel7" }],
  ["path", { d: "M3 12A9 3 0 0 0 21 12", key: "mv7ke4" }]
]);

// node_modules/lucide-react/dist/esm/icons/download.js
var Download = createLucideIcon("Download", [
  ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", key: "ih7n3h" }],
  ["polyline", { points: "7 10 12 15 17 10", key: "2ggqvy" }],
  ["line", { x1: "12", x2: "12", y1: "15", y2: "3", key: "1vk2je" }]
]);

// node_modules/lucide-react/dist/esm/icons/ellipsis.js
var Ellipsis = createLucideIcon("Ellipsis", [
  ["circle", { cx: "12", cy: "12", r: "1", key: "41hilf" }],
  ["circle", { cx: "19", cy: "12", r: "1", key: "1wjl8i" }],
  ["circle", { cx: "5", cy: "12", r: "1", key: "1pcz8c" }]
]);

// node_modules/lucide-react/dist/esm/icons/external-link.js
var ExternalLink = createLucideIcon("ExternalLink", [
  ["path", { d: "M15 3h6v6", key: "1q9fwt" }],
  ["path", { d: "M10 14 21 3", key: "gplh6r" }],
  ["path", { d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6", key: "a6xqqp" }]
]);

// node_modules/lucide-react/dist/esm/icons/eye-off.js
var EyeOff = createLucideIcon("EyeOff", [
  [
    "path",
    {
      d: "M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",
      key: "ct8e1f"
    }
  ],
  ["path", { d: "M14.084 14.158a3 3 0 0 1-4.242-4.242", key: "151rxh" }],
  [
    "path",
    {
      d: "M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",
      key: "13bj9a"
    }
  ],
  ["path", { d: "m2 2 20 20", key: "1ooewy" }]
]);

// node_modules/lucide-react/dist/esm/icons/eye.js
var Eye = createLucideIcon("Eye", [
  [
    "path",
    {
      d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",
      key: "1nclc0"
    }
  ],
  ["circle", { cx: "12", cy: "12", r: "3", key: "1v7zrd" }]
]);

// node_modules/lucide-react/dist/esm/icons/file-text.js
var FileText = createLucideIcon("FileText", [
  ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", key: "1rqfz7" }],
  ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4", key: "tnqrlb" }],
  ["path", { d: "M10 9H8", key: "b1mrlr" }],
  ["path", { d: "M16 13H8", key: "t4e002" }],
  ["path", { d: "M16 17H8", key: "z1uh3a" }]
]);

// node_modules/lucide-react/dist/esm/icons/image.js
var Image = createLucideIcon("Image", [
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2", key: "1m3agn" }],
  ["circle", { cx: "9", cy: "9", r: "2", key: "af1f0g" }],
  ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21", key: "1xmnt7" }]
]);

// node_modules/lucide-react/dist/esm/icons/info.js
var Info = createLucideIcon("Info", [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M12 16v-4", key: "1dtifu" }],
  ["path", { d: "M12 8h.01", key: "e9boi3" }]
]);

// node_modules/lucide-react/dist/esm/icons/key.js
var Key = createLucideIcon("Key", [
  ["path", { d: "m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4", key: "g0fldk" }],
  ["path", { d: "m21 2-9.6 9.6", key: "1j0ho8" }],
  ["circle", { cx: "7.5", cy: "15.5", r: "5.5", key: "yqb3hr" }]
]);

// node_modules/lucide-react/dist/esm/icons/library-big.js
var LibraryBig = createLucideIcon("LibraryBig", [
  ["rect", { width: "8", height: "18", x: "3", y: "3", rx: "1", key: "oynpb5" }],
  ["path", { d: "M7 3v18", key: "bbkbws" }],
  [
    "path",
    {
      d: "M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",
      key: "1qboyk"
    }
  ]
]);

// node_modules/lucide-react/dist/esm/icons/loader-circle.js
var LoaderCircle = createLucideIcon("LoaderCircle", [
  ["path", { d: "M21 12a9 9 0 1 1-6.219-8.56", key: "13zald" }]
]);

// node_modules/lucide-react/dist/esm/icons/message-circle-plus.js
var MessageCirclePlus = createLucideIcon("MessageCirclePlus", [
  ["path", { d: "M7.9 20A9 9 0 1 0 4 16.1L2 22Z", key: "vv11sd" }],
  ["path", { d: "M8 12h8", key: "1wcyev" }],
  ["path", { d: "M12 8v8", key: "napkw2" }]
]);

// node_modules/lucide-react/dist/esm/icons/pen-line.js
var PenLine = createLucideIcon("PenLine", [
  ["path", { d: "M12 20h9", key: "t2du7b" }],
  [
    "path",
    {
      d: "M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",
      key: "1ykcvy"
    }
  ]
]);

// node_modules/lucide-react/dist/esm/icons/pencil.js
var Pencil = createLucideIcon("Pencil", [
  [
    "path",
    {
      d: "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",
      key: "1a8usu"
    }
  ],
  ["path", { d: "m15 5 4 4", key: "1mk7zo" }]
]);

// node_modules/lucide-react/dist/esm/icons/plus.js
var Plus = createLucideIcon("Plus", [
  ["path", { d: "M5 12h14", key: "1ays0h" }],
  ["path", { d: "M12 5v14", key: "s699le" }]
]);

// node_modules/lucide-react/dist/esm/icons/refresh-ccw.js
var RefreshCcw = createLucideIcon("RefreshCcw", [
  ["path", { d: "M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8", key: "14sxne" }],
  ["path", { d: "M3 3v5h5", key: "1xhq8a" }],
  ["path", { d: "M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16", key: "1hlbsb" }],
  ["path", { d: "M16 16h5v5", key: "ccwih5" }]
]);

// node_modules/lucide-react/dist/esm/icons/refresh-cw.js
var RefreshCw = createLucideIcon("RefreshCw", [
  ["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8", key: "v9h5vc" }],
  ["path", { d: "M21 3v5h-5", key: "1q7to0" }],
  ["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16", key: "3uifl3" }],
  ["path", { d: "M8 16H3v5", key: "1cv678" }]
]);

// node_modules/lucide-react/dist/esm/icons/rotate-cw.js
var RotateCw = createLucideIcon("RotateCw", [
  ["path", { d: "M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8", key: "1p45f6" }],
  ["path", { d: "M21 3v5h-5", key: "1q7to0" }]
]);

// node_modules/lucide-react/dist/esm/icons/sparkles.js
var Sparkles = createLucideIcon("Sparkles", [
  [
    "path",
    {
      d: "M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",
      key: "4pj2yx"
    }
  ],
  ["path", { d: "M20 3v4", key: "1olli1" }],
  ["path", { d: "M22 5h-4", key: "1gvqau" }],
  ["path", { d: "M4 17v2", key: "vumght" }],
  ["path", { d: "M5 18H3", key: "zchphs" }]
]);

// node_modules/lucide-react/dist/esm/icons/square-arrow-out-up-right.js
var SquareArrowOutUpRight = createLucideIcon("SquareArrowOutUpRight", [
  ["path", { d: "M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6", key: "y09zxi" }],
  ["path", { d: "m21 3-9 9", key: "mpx6sq" }],
  ["path", { d: "M15 3h6v6", key: "1q9fwt" }]
]);

// node_modules/lucide-react/dist/esm/icons/square-pen.js
var SquarePen = createLucideIcon("SquarePen", [
  ["path", { d: "M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7", key: "1m0v6g" }],
  [
    "path",
    {
      d: "M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",
      key: "ohrbg2"
    }
  ]
]);

// node_modules/lucide-react/dist/esm/icons/text-cursor-input.js
var TextCursorInput = createLucideIcon("TextCursorInput", [
  ["path", { d: "M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1", key: "18xjzo" }],
  ["path", { d: "M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5", key: "fj48gi" }],
  ["path", { d: "M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1", key: "1n9rhb" }],
  ["path", { d: "M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7", key: "13ksps" }],
  ["path", { d: "M9 7v10", key: "1vc8ob" }]
]);

// node_modules/lucide-react/dist/esm/icons/trash-2.js
var Trash2 = createLucideIcon("Trash2", [
  ["path", { d: "M3 6h18", key: "d0wm0j" }],
  ["path", { d: "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6", key: "4alrt4" }],
  ["path", { d: "M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2", key: "v07s0e" }],
  ["line", { x1: "10", x2: "10", y1: "11", y2: "17", key: "1uufr5" }],
  ["line", { x1: "14", x2: "14", y1: "11", y2: "17", key: "xtxkd" }]
]);

// node_modules/lucide-react/dist/esm/icons/triangle-alert.js
var TriangleAlert = createLucideIcon("TriangleAlert", [
  [
    "path",
    {
      d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",
      key: "wmoenq"
    }
  ],
  ["path", { d: "M12 9v4", key: "juzpu7" }],
  ["path", { d: "M12 17h.01", key: "p32p05" }]
]);

// node_modules/lucide-react/dist/esm/icons/user.js
var User = createLucideIcon("User", [
  ["path", { d: "M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2", key: "975kel" }],
  ["circle", { cx: "12", cy: "7", r: "4", key: "17ys0d" }]
]);

// node_modules/lucide-react/dist/esm/icons/wrench.js
var Wrench = createLucideIcon("Wrench", [
  [
    "path",
    {
      d: "M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",
      key: "cbrjhi"
    }
  ]
]);

// node_modules/lucide-react/dist/esm/icons/x.js
var X = createLucideIcon("X", [
  ["path", { d: "M18 6 6 18", key: "1bl5f8" }],
  ["path", { d: "m6 6 12 12", key: "d8bk6v" }]
]);

// src/components/modals/CopilotPlusExpiredModal.tsx
function CopilotPlusExpiredModalContent({ onCancel }) {
  const settings = getSettings();
  const isUsingPlusModels = isPlusModel(settings.defaultModelKey) && isPlusModel(settings.embeddingModelKey);
  return /* @__PURE__ */ import_react4.default.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ import_react4.default.createElement("div", { className: "flex flex-col gap-2" }, /* @__PURE__ */ import_react4.default.createElement("div", null, "Your Copilot Plus license key is no longer valid. Please renew your subscription to continue using Copilot Plus."), isUsingPlusModels && /* @__PURE__ */ import_react4.default.createElement("div", { className: "text-sm text-warning" }, "The Copilot Plus exclusive models will stop working. You can switch to the default models in the Settings.")), /* @__PURE__ */ import_react4.default.createElement("div", { className: "flex gap-2 justify-end w-full" }, /* @__PURE__ */ import_react4.default.createElement(Button, { variant: "ghost", onClick: onCancel }, "Close"), /* @__PURE__ */ import_react4.default.createElement(
    Button,
    {
      variant: "default",
      onClick: () => {
        navigateToPlusPage(PLUS_UTM_MEDIUMS.EXPIRED_MODAL);
      }
    },
    "Renew Now ",
    /* @__PURE__ */ import_react4.default.createElement(ExternalLink, { className: "size-4" })
  )));
}
var CopilotPlusExpiredModal = class extends import_obsidian2.Modal {
  constructor(app2) {
    super(app2);
    this.setTitle("Thanks for being a Copilot Plus user \u{1F44B}");
  }
  onOpen() {
    const { contentEl } = this;
    this.root = (0, import_client3.createRoot)(contentEl);
    const handleCancel = () => {
      this.close();
    };
    this.root.render(/* @__PURE__ */ import_react4.default.createElement(CopilotPlusExpiredModalContent, { onCancel: handleCancel }));
  }
  onClose() {
    this.root.unmount();
  }
};

// src/error.ts
var CustomError = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
    Object.setPrototypeOf(this, CustomError.prototype);
  }
};

// src/utils.ts
var import_moment = __toESM(require_moment());
var import_obsidian3 = require("obsidian");
var ERROR_MESSAGES = {
  INVALID_LICENSE_KEY_USER: "Invalid Copilot Plus license key. Please check your license key in settings.",
  UNKNOWN_ERROR: "An unknown error occurred",
  REQUEST_FAILED: (status) => `Request failed, status ${status}`
};
function extractErrorDetail(error) {
  const errorJson = error?.json?.detail || error?.json || {};
  return {
    status: errorJson.status,
    message: errorJson.message || error?.message,
    reason: errorJson.reason
  };
}
function isLicenseKeyError(error) {
  const errorDetail = extractErrorDetail(error);
  return errorDetail.reason === "Invalid license key" || error?.message === "Invalid license key" || error?.message?.includes("status 403") || errorDetail.status === 403;
}
function getApiErrorMessage(error) {
  const errorDetail = extractErrorDetail(error);
  if (isLicenseKeyError(error)) {
    return ERROR_MESSAGES.INVALID_LICENSE_KEY_USER;
  }
  return errorDetail.message || (errorDetail.reason ? `Error: ${errorDetail.reason}` : ERROR_MESSAGES.UNKNOWN_ERROR);
}
async function getNoteFileFromTitle(vault, noteTitle) {
  const files = vault.getMarkdownFiles();
  for (const file of files) {
    const title = file.basename;
    if (title === noteTitle) {
      return file;
    }
  }
  return null;
}
var getNotesFromPath = (vault, path) => {
  const files = vault.getMarkdownFiles();
  if (path === "/") {
    return files;
  }
  const normalizedPath = path.toLowerCase().replace(/^\/|\/$/g, "");
  return files.filter((file) => {
    const normalizedFilePath = file.path.toLowerCase();
    const filePathParts = normalizedFilePath.split("/");
    const pathParts = normalizedPath.split("/");
    let filePathIndex = 0;
    for (const pathPart of pathParts) {
      while (filePathIndex < filePathParts.length) {
        if (filePathParts[filePathIndex] === pathPart) {
          break;
        }
        filePathIndex++;
      }
      if (filePathIndex >= filePathParts.length) {
        return false;
      }
    }
    return true;
  });
};
function stripHash(tag) {
  return tag.replace(/^#/, "").trim().toLowerCase();
}
function getTagsFromNote(file, frontmatterOnly = true) {
  const metadata = app.metadataCache.getFileCache(file);
  const frontmatterTags = metadata?.frontmatter?.tags;
  const allTags = /* @__PURE__ */ new Set();
  if (!frontmatterOnly) {
    const inlineTags = metadata?.tags?.map((tag) => tag.tag);
    if (inlineTags) {
      inlineTags.forEach((tag) => allTags.add(stripHash(tag)));
    }
  }
  if (frontmatterTags) {
    if (Array.isArray(frontmatterTags)) {
      frontmatterTags.forEach((tag) => allTags.add(stripHash(tag)));
    } else if (typeof frontmatterTags === "string") {
      allTags.add(stripHash(frontmatterTags));
    }
  }
  return Array.from(allTags);
}
function getNotesFromTags(vault, tags, noteFiles) {
  if (tags.length === 0) {
    return [];
  }
  tags = tags.map((tag) => stripHash(tag));
  const files = noteFiles && noteFiles.length > 0 ? noteFiles : getNotesFromPath(vault, "/");
  const filesWithTag = [];
  for (const file of files) {
    const noteTags = getTagsFromNote(file);
    if (tags.some((tag) => noteTags.includes(tag))) {
      filesWithTag.push(file);
    }
  }
  return filesWithTag;
}
function isPathInList(filePath, pathList) {
  if (!pathList)
    return false;
  const fileName = filePath.split("/").pop()?.toLowerCase();
  const normalizedFilePath = filePath.toLowerCase();
  return pathList.split(",").map(
    (path) => path.trim().replace(/^\[\[|\]\]$/g, "").replace(/^\//, "").toLowerCase()
    // Convert to lowercase for case-insensitive comparison
  ).some((normalizedPath) => {
    const isExactMatch = normalizedFilePath === normalizedPath || normalizedFilePath.startsWith(normalizedPath + "/") || normalizedFilePath.endsWith("/" + normalizedPath) || normalizedFilePath.includes("/" + normalizedPath + "/");
    const isFileNameMatch = fileName === normalizedPath + ".md";
    return isExactMatch || isFileNameMatch;
  });
}
var isLLMChain = (chain) => {
  return chain.last.bound.modelName || chain.last.bound.model;
};
var isRetrievalQAChain = (chain) => {
  return chain.last.bound.retriever !== void 0;
};
var isSupportedChain = (chain) => {
  return isLLMChain(chain) || isRetrievalQAChain(chain);
};
var formatDateTime = (now3, timezone = "local") => {
  const formattedDateTime = (0, import_moment.default)(now3);
  if (timezone === "utc") {
    formattedDateTime.utc();
  }
  return {
    fileName: formattedDateTime.format("YYYYMMDD_HHmmss"),
    display: formattedDateTime.format("YYYY/MM/DD HH:mm:ss"),
    epoch: formattedDateTime.valueOf()
  };
};
function stringToFormattedDateTime(timestamp) {
  const date2 = (0, import_moment.default)(timestamp, "YYYY/MM/DD HH:mm:ss");
  if (!date2.isValid()) {
    return formatDateTime(new Date());
  }
  return {
    fileName: date2.format("YYYYMMDD_HHmmss"),
    display: date2.format("YYYY/MM/DD HH:mm:ss"),
    epoch: date2.valueOf()
  };
}
async function getFileContent(file, vault) {
  if (file.extension != "md")
    return null;
  return await vault.cachedRead(file);
}
function getFileName(file) {
  return file.basename;
}
function areEmbeddingModelsSame(model1, model2) {
  if (!model1 || !model2)
    return false;
  if (model1.includes(NOMIC_EMBED_TEXT) && model2.includes(NOMIC_EMBED_TEXT)) {
    return true;
  }
  if (model1 === "small" && model2 === "cohereai" || model1 === "cohereai" && model2 === "small") {
    return true;
  }
  return model1 === model2;
}
function extractChatHistory(memoryVariables) {
  const chatHistory = [];
  const { history } = memoryVariables;
  for (let i3 = 0; i3 < history.length; i3 += 2) {
    const userMessage = history[i3]?.content || "";
    const aiMessage = history[i3 + 1]?.content || "";
    chatHistory.push([userMessage, aiMessage]);
  }
  return chatHistory;
}
function extractNoteTitles(query) {
  const regex2 = /\[\[(.*?)\]\]/g;
  const matches = query.match(regex2);
  const uniqueTitles = new Set(matches ? matches.map((match2) => match2.slice(2, -2)) : []);
  return Array.from(uniqueTitles);
}
function processVariableNameForNotePath(variableName) {
  variableName = variableName.trim();
  if (variableName.startsWith("[[") && variableName.endsWith("]]")) {
    return `${variableName.slice(2, -2).trim()}.md`;
  }
  return variableName;
}
function extractUniqueTitlesFromDocs(docs) {
  const titlesSet = /* @__PURE__ */ new Set();
  docs.forEach((doc) => {
    if (doc.metadata?.title) {
      titlesSet.add(doc.metadata?.title);
    }
  });
  return Array.from(titlesSet);
}
var YOUTUBE_URL_REGEX = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;
function isYoutubeUrl(url) {
  return YOUTUBE_URL_REGEX.test(url);
}
function extractYoutubeUrl(text) {
  const match2 = text.match(YOUTUBE_URL_REGEX);
  return match2 ? match2[0] : null;
}
var ImageProcessor = class {
  static async isImageUrl(url) {
    try {
      const urlObj = new URL(url);
      if (this.IMAGE_EXTENSIONS.some((ext) => urlObj.pathname.toLowerCase().endsWith(ext))) {
        return true;
      }
      try {
        const response = await safeFetch(url, {
          method: "HEAD",
          headers: {}
          // Explicitly set empty headers
        });
        const contentType = response.headers.get("content-type");
        if (contentType?.startsWith("image/")) {
          return true;
        }
      } catch (error) {
        console.debug("Error checking content-type:", error);
      }
      const searchParams = urlObj.searchParams;
      const imageIndicators = [
        // Image dimensions
        searchParams.has("w") || searchParams.has("width"),
        searchParams.has("h") || searchParams.has("height"),
        // Image processing
        searchParams.has("format"),
        searchParams.has("fit"),
        // Image quality
        searchParams.has("q") || searchParams.has("quality"),
        // Common CDN image path patterns
        urlObj.pathname.includes("/image/"),
        urlObj.pathname.includes("/images/"),
        urlObj.pathname.includes("/img/"),
        // Common image processing parameters
        searchParams.has("auto"),
        searchParams.has("crop")
      ];
      const imageIndicatorCount = imageIndicators.filter(Boolean).length;
      return imageIndicatorCount >= 2;
    } catch (error) {
      console.error("Error checking if URL is image:", error);
      return false;
    }
  }
  static async convertToBase64(imageUrl, vault) {
    const base64Url = await this.imageToBase64(imageUrl, vault);
    return {
      type: "image_url",
      image_url: {
        url: base64Url
      }
    };
  }
  static async imageToBase64(imageUrl, vault) {
    if (imageUrl.startsWith("data:")) {
      return imageUrl;
    }
    if (imageUrl.startsWith("app://")) {
      return await this.handleLocalImage(imageUrl, vault);
    }
    return await this.handleWebImage(imageUrl);
  }
  static async handleLocalImage(imageUrl, vault) {
    const localPath = decodeURIComponent(imageUrl.replace("app://", ""));
    const file = vault.getAbstractFileByPath(localPath);
    if (!file || !(file instanceof import_obsidian3.TFile)) {
      throw new Error(`Local image not found: ${localPath}`);
    }
    const arrayBuffer = await vault.readBinary(file);
    const buffer = Buffer.from(arrayBuffer);
    const base642 = buffer.toString("base64");
    const mimeType = `image/${file.extension}`;
    return `data:${mimeType};base64,${base642}`;
  }
  static async handleWebImage(imageUrl) {
    try {
      const response = await safeFetch(imageUrl, {
        method: "GET",
        headers: {}
      });
      if (!response.ok) {
        throw new Error(`Failed to fetch image: ${response.statusText}`);
      }
      const contentType = response.headers.get("content-type");
      if (!contentType?.startsWith("image/")) {
        throw new Error(`Invalid content type: ${contentType}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      const buffer = Buffer.from(arrayBuffer);
      const base642 = buffer.toString("base64");
      return `data:${contentType};base64,${base642}`;
    } catch (error) {
      console.error("Error converting image to base64:", error);
      throw error;
    }
  }
};
ImageProcessor.IMAGE_EXTENSIONS = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".webp",
  ".bmp",
  ".svg"
];
async function safeFetch(url, options = {}) {
  const headers = options.headers ? { ...options.headers } : {};
  delete headers["content-length"];
  if (typeof options.body === "string") {
    const newBody = JSON.parse(options.body ?? {});
    delete newBody["frequency_penalty"];
    options.body = JSON.stringify(newBody);
  }
  const method = options.method?.toLowerCase() || "post";
  const methodsWithBody = ["post", "put", "patch"];
  const response = await (0, import_obsidian3.requestUrl)({
    url,
    contentType: "application/json",
    headers,
    method,
    ...methodsWithBody.includes(method) && { body: options.body?.toString() },
    throw: false
    // Don't throw so we can get the response body
  });
  if (response.status >= 400) {
    let errorJson;
    try {
      errorJson = typeof response.json === "string" ? JSON.parse(response.json) : response.json;
    } catch {
      try {
        errorJson = typeof response.text === "string" ? JSON.parse(response.text) : response.text;
      } catch {
        errorJson = null;
      }
    }
    const error = new Error(ERROR_MESSAGES.REQUEST_FAILED(response.status));
    error.json = errorJson;
    if (errorJson?.detail?.reason === "Invalid license key" || errorJson?.reason === "Invalid license key") {
      error.message = "Invalid license key";
    } else if (errorJson?.detail?.message || errorJson?.message) {
      const message = errorJson?.detail?.message || errorJson?.message;
      const reason = errorJson?.detail?.reason || errorJson?.reason;
      error.message = reason ? `${message}: ${reason}` : message;
    } else if (errorJson?.detail) {
      error.message = JSON.stringify(errorJson.detail);
    }
    throw error;
  }
  return {
    ok: response.status >= 200 && response.status < 300,
    status: response.status,
    statusText: response.status.toString(),
    headers: new Headers(response.headers),
    url,
    type: "basic",
    redirected: false,
    bytes: () => Promise.resolve(new Uint8Array(0)),
    body: createReadableStreamFromString(response.text),
    bodyUsed: true,
    json: () => response.json,
    text: async () => response.text,
    arrayBuffer: async () => {
      if (response.arrayBuffer) {
        return response.arrayBuffer;
      }
      const base642 = response.text.replace(/^data:.*;base64,/, "");
      const binaryString = atob(base642);
      const bytes = new Uint8Array(binaryString.length);
      for (let i3 = 0; i3 < binaryString.length; i3++) {
        bytes[i3] = binaryString.charCodeAt(i3);
      }
      return bytes.buffer;
    },
    blob: () => {
      throw new Error("not implemented");
    },
    formData: () => {
      throw new Error("not implemented");
    },
    clone: () => {
      throw new Error("not implemented");
    }
  };
}
function createReadableStreamFromString(input) {
  return new ReadableStream({
    start(controller) {
      const encoder = new TextEncoder();
      const uint8Array = encoder.encode(input);
      controller.enqueue(uint8Array);
      controller.close();
    }
  });
}
function err2String(err, stack = false) {
  return err instanceof Error ? err.message + `
${err?.cause ? "more message: " + err.cause.message : ""}
${stack ? err.stack : ""}` : JSON.stringify(err);
}
function omit(obj, keys) {
  const result = { ...obj };
  keys.forEach((key) => {
    delete result[key];
  });
  return result;
}
function findCustomModel(modelKey, activeModels) {
  const [modelName, provider] = modelKey.split("|");
  const model = activeModels.find((m3) => m3.name === modelName && m3.provider === provider);
  if (!model) {
    throw new Error(`No model configuration found for: ${modelKey}`);
  }
  return model;
}
function getProviderInfo(provider) {
  const info = ProviderInfo[provider];
  return {
    ...info,
    label: info.label || provider
  };
}
function getProviderLabel(provider) {
  return ProviderInfo[provider]?.label || provider;
}
async function insertIntoEditor(message, replace = false) {
  let leaf = app.workspace.getMostRecentLeaf();
  if (!leaf) {
    new import_obsidian3.Notice("No active leaf found.");
    return;
  }
  if (!(leaf.view instanceof import_obsidian3.MarkdownView)) {
    leaf = app.workspace.getLeaf(false);
    await leaf.setViewState({ type: "markdown", state: leaf.view.getState() });
  }
  if (!(leaf.view instanceof import_obsidian3.MarkdownView)) {
    new import_obsidian3.Notice("Failed to open a markdown view.");
    return;
  }
  const editor = leaf.view.editor;
  const cursorFrom = editor.getCursor("from");
  const cursorTo = editor.getCursor("to");
  if (replace) {
    editor.replaceRange(message, cursorFrom, cursorTo);
  } else {
    editor.replaceRange(message, cursorTo);
  }
  new import_obsidian3.Notice("Message inserted into the active note.");
}
function debounce(func, wait) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}
function isNewerVersion(latest, current) {
  const latestParts = latest.split(".").map(Number);
  const currentParts = current.split(".").map(Number);
  for (let i3 = 0; i3 < 3; i3++) {
    if (latestParts[i3] > currentParts[i3])
      return true;
    if (latestParts[i3] < currentParts[i3])
      return false;
  }
  return false;
}
async function checkLatestVersion() {
  try {
    const response = await (0, import_obsidian3.requestUrl)({
      url: "https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",
      method: "GET"
    });
    const version2 = response.json.tag_name.replace("v", "");
    return { version: version2, error: null };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Failed to check for updates";
    return { version: null, error: errorMessage };
  }
}

// node_modules/@langchain/cohere/dist/chat_models.js
var import_cohere_ai = __toESM(require_cohere_ai(), 1);
init_esm();

// node_modules/@langchain/core/messages.js
init_messages2();

// node_modules/@langchain/cohere/dist/chat_models.js
init_base9();

// node_modules/@langchain/core/dist/utils/function_calling.js
init_esm();
init_base4();

// node_modules/@langchain/core/dist/utils/types/is_zod_schema.js
function isZodSchema(input) {
  return typeof input?.parse === "function";
}

// node_modules/@langchain/core/dist/utils/function_calling.js
function convertToOpenAIFunction(tool2, fields) {
  const fieldsCopy = typeof fields === "number" ? void 0 : fields;
  return {
    name: tool2.name,
    description: tool2.description,
    parameters: zodToJsonSchema(tool2.schema),
    // Do not include the `strict` field if it is `undefined`.
    ...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {}
  };
}
function convertToOpenAITool(tool2, fields) {
  const fieldsCopy = typeof fields === "number" ? void 0 : fields;
  let toolDef;
  if (isLangChainTool(tool2)) {
    toolDef = {
      type: "function",
      function: convertToOpenAIFunction(tool2)
    };
  } else {
    toolDef = tool2;
  }
  if (fieldsCopy?.strict !== void 0) {
    toolDef.function.strict = fieldsCopy.strict;
  }
  return toolDef;
}
function isStructuredTool(tool2) {
  return tool2 !== void 0 && Array.isArray(tool2.lc_namespace);
}
function isRunnableToolLike(tool2) {
  return tool2 !== void 0 && Runnable.isRunnable(tool2) && "lc_name" in tool2.constructor && typeof tool2.constructor.lc_name === "function" && tool2.constructor.lc_name() === "RunnableToolLike";
}
function isStructuredToolParams(tool2) {
  return !!tool2 && typeof tool2 === "object" && "name" in tool2 && "schema" in tool2 && // eslint-disable-next-line @typescript-eslint/no-explicit-any
  isZodSchema(tool2.schema);
}
function isLangChainTool(tool2) {
  return isStructuredToolParams(tool2) || isRunnableToolLike(tool2) || // eslint-disable-next-line @typescript-eslint/no-explicit-any
  isStructuredTool(tool2);
}

// node_modules/@langchain/core/dist/language_models/chat_models.js
init_esm();
init_messages2();
init_outputs();
init_base8();
init_manager();
init_base4();
init_stream();
init_passthrough();
init_base();
var BaseChatModel = class extends BaseLanguageModel {
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "chat_models", this._llmType()]
    });
    Object.defineProperty(this, "disableStreaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
  }
  _separateRunnableConfigFromCallOptionsCompat(options) {
    const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options);
    callOptions.signal = runnableConfig.signal;
    return [runnableConfig, callOptions];
  }
  /**
   * Invokes the chat model with a single input.
   * @param input The input for the language model.
   * @param options The call options.
   * @returns A Promise that resolves to a BaseMessageChunk.
   */
  async invoke(input, options) {
    const promptValue = BaseChatModel._convertInputToPromptValue(input);
    const result = await this.generatePrompt([promptValue], options, options?.callbacks);
    const chatGeneration = result.generations[0][0];
    return chatGeneration.message;
  }
  // eslint-disable-next-line require-yield
  async *_streamResponseChunks(_messages, _options, _runManager) {
    throw new Error("Not implemented.");
  }
  async *_streamIterator(input, options) {
    if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) {
      yield this.invoke(input, options);
    } else {
      const prompt = BaseChatModel._convertInputToPromptValue(input);
      const messages = prompt.toChatMessages();
      const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options);
      const inheritableMetadata = {
        ...runnableConfig.metadata,
        ...this.getLsParams(callOptions)
      };
      const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });
      const extra = {
        options: callOptions,
        invocation_params: this?.invocationParams(callOptions),
        batch_size: 1
      };
      const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName);
      let generationChunk;
      let llmOutput;
      try {
        for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) {
          if (chunk.message.id == null) {
            const runId = runManagers?.at(0)?.runId;
            if (runId != null)
              chunk.message._updateId(`run-${runId}`);
          }
          chunk.message.response_metadata = {
            ...chunk.generationInfo,
            ...chunk.message.response_metadata
          };
          yield chunk.message;
          if (!generationChunk) {
            generationChunk = chunk;
          } else {
            generationChunk = generationChunk.concat(chunk);
          }
          if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) {
            llmOutput = {
              tokenUsage: {
                promptTokens: chunk.message.usage_metadata.input_tokens,
                completionTokens: chunk.message.usage_metadata.output_tokens,
                totalTokens: chunk.message.usage_metadata.total_tokens
              }
            };
          }
        }
      } catch (err) {
        await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err)));
        throw err;
      }
      await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({
        // TODO: Remove cast after figuring out inheritance
        generations: [[generationChunk]],
        llmOutput
      })));
    }
  }
  getLsParams(options) {
    const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName();
    return {
      ls_model_type: "chat",
      ls_stop: options.stop,
      ls_provider: providerName
    };
  }
  /** @ignore */
  async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) {
    const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));
    let runManagers;
    if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) {
      runManagers = startedRunManagers;
    } else {
      const inheritableMetadata = {
        ...handledOptions.metadata,
        ...this.getLsParams(parsedOptions)
      };
      const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });
      const extra = {
        options: parsedOptions,
        invocation_params: this?.invocationParams(parsedOptions),
        batch_size: 1
      };
      runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName);
    }
    const generations = [];
    const llmOutputs = [];
    const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming);
    if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) {
      try {
        const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]);
        let aggregated;
        let llmOutput;
        for await (const chunk of stream) {
          if (chunk.message.id == null) {
            const runId = runManagers?.at(0)?.runId;
            if (runId != null)
              chunk.message._updateId(`run-${runId}`);
          }
          if (aggregated === void 0) {
            aggregated = chunk;
          } else {
            aggregated = concat(aggregated, chunk);
          }
          if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) {
            llmOutput = {
              tokenUsage: {
                promptTokens: chunk.message.usage_metadata.input_tokens,
                completionTokens: chunk.message.usage_metadata.output_tokens,
                totalTokens: chunk.message.usage_metadata.total_tokens
              }
            };
          }
        }
        if (aggregated === void 0) {
          throw new Error("Received empty response from chat model call.");
        }
        generations.push([aggregated]);
        await runManagers?.[0].handleLLMEnd({
          generations,
          llmOutput
        });
      } catch (e3) {
        await runManagers?.[0].handleLLMError(e3);
        throw e3;
      }
    } else {
      const results = await Promise.allSettled(baseMessages.map((messageList, i3) => this._generate(messageList, { ...parsedOptions, promptIndex: i3 }, runManagers?.[i3])));
      await Promise.all(results.map(async (pResult, i3) => {
        if (pResult.status === "fulfilled") {
          const result = pResult.value;
          for (const generation of result.generations) {
            if (generation.message.id == null) {
              const runId = runManagers?.at(0)?.runId;
              if (runId != null)
                generation.message._updateId(`run-${runId}`);
            }
            generation.message.response_metadata = {
              ...generation.generationInfo,
              ...generation.message.response_metadata
            };
          }
          if (result.generations.length === 1) {
            result.generations[0].message.response_metadata = {
              ...result.llmOutput,
              ...result.generations[0].message.response_metadata
            };
          }
          generations[i3] = result.generations;
          llmOutputs[i3] = result.llmOutput;
          return runManagers?.[i3]?.handleLLMEnd({
            generations: [result.generations],
            llmOutput: result.llmOutput
          });
        } else {
          await runManagers?.[i3]?.handleLLMError(pResult.reason);
          return Promise.reject(pResult.reason);
        }
      }));
    }
    const output = {
      generations,
      llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0
    };
    Object.defineProperty(output, RUN_KEY, {
      value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0,
      configurable: true
    });
    return output;
  }
  async _generateCached({ messages, cache: cache2, llmStringKey, parsedOptions, handledOptions }) {
    const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));
    const inheritableMetadata = {
      ...handledOptions.metadata,
      ...this.getLsParams(parsedOptions)
    };
    const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });
    const extra = {
      options: parsedOptions,
      invocation_params: this?.invocationParams(parsedOptions),
      batch_size: 1
    };
    const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName);
    const missingPromptIndices = [];
    const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index2) => {
      const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();
      const result = await cache2.lookup(prompt, llmStringKey);
      if (result == null) {
        missingPromptIndices.push(index2);
      }
      return result;
    }));
    const cachedResults = results.map((result, index2) => ({ result, runManager: runManagers?.[index2] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected");
    const generations = [];
    await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i3) => {
      if (promiseResult.status === "fulfilled") {
        const result = promiseResult.value;
        generations[i3] = result.map((result2) => {
          if ("message" in result2 && isBaseMessage(result2.message) && isAIMessage(result2.message)) {
            result2.message.usage_metadata = {
              input_tokens: 0,
              output_tokens: 0,
              total_tokens: 0
            };
          }
          result2.generationInfo = {
            ...result2.generationInfo,
            tokenUsage: {}
          };
          return result2;
        });
        if (result.length) {
          await runManager?.handleLLMNewToken(result[0].text);
        }
        return runManager?.handleLLMEnd({
          generations: [result]
        }, void 0, void 0, void 0, {
          cached: true
        });
      } else {
        await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, {
          cached: true
        });
        return Promise.reject(promiseResult.reason);
      }
    }));
    const output = {
      generations,
      missingPromptIndices,
      startedRunManagers: runManagers
    };
    Object.defineProperty(output, RUN_KEY, {
      value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0,
      configurable: true
    });
    return output;
  }
  /**
   * Generates chat based on the input messages.
   * @param messages An array of arrays of BaseMessage instances.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to an LLMResult.
   */
  async generate(messages, options, callbacks) {
    let parsedOptions;
    if (Array.isArray(options)) {
      parsedOptions = { stop: options };
    } else {
      parsedOptions = options;
    }
    const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage));
    const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions);
    runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;
    if (!this.cache) {
      return this._generateUncached(baseMessages, callOptions, runnableConfig);
    }
    const { cache: cache2 } = this;
    const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);
    const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({
      messages: baseMessages,
      cache: cache2,
      llmStringKey,
      parsedOptions: callOptions,
      handledOptions: runnableConfig
    });
    let llmOutput = {};
    if (missingPromptIndices.length > 0) {
      const results = await this._generateUncached(missingPromptIndices.map((i3) => baseMessages[i3]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i3) => startedRunManagers?.[i3]) : void 0);
      await Promise.all(results.generations.map(async (generation, index2) => {
        const promptIndex = missingPromptIndices[index2];
        generations[promptIndex] = generation;
        const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString();
        return cache2.update(prompt, llmStringKey, generation);
      }));
      llmOutput = results.llmOutput ?? {};
    }
    return { generations, llmOutput };
  }
  /**
   * Get the parameters used to invoke the model
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  invocationParams(_options) {
    return {};
  }
  _modelType() {
    return "base_chat_model";
  }
  /**
   * @deprecated
   * Return a json-like object representing this LLM.
   */
  serialize() {
    return {
      ...this.invocationParams(),
      _type: this._llmType(),
      _model: this._modelType()
    };
  }
  /**
   * Generates a prompt based on the input prompt values.
   * @param promptValues An array of BasePromptValue instances.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to an LLMResult.
   */
  async generatePrompt(promptValues, options, callbacks) {
    const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages());
    return this.generate(promptMessages, options, callbacks);
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
   *
   * Makes a single call to the chat model.
   * @param messages An array of BaseMessage instances.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to a BaseMessage.
   */
  async call(messages, options, callbacks) {
    const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks);
    const generations = result.generations;
    return generations[0][0].message;
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
   *
   * Makes a single call to the chat model with a prompt value.
   * @param promptValue The value of the prompt.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to a BaseMessage.
   */
  async callPrompt(promptValue, options, callbacks) {
    const promptMessages = promptValue.toChatMessages();
    return this.call(promptMessages, options, callbacks);
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
   *
   * Predicts the next message based on the input messages.
   * @param messages An array of BaseMessage instances.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to a BaseMessage.
   */
  async predictMessages(messages, options, callbacks) {
    return this.call(messages, options, callbacks);
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.2.0.
   *
   * Predicts the next message based on a text input.
   * @param text The text input.
   * @param options The call options or an array of stop sequences.
   * @param callbacks The callbacks for the language model.
   * @returns A Promise that resolves to a string.
   */
  async predict(text, options, callbacks) {
    const message = new HumanMessage(text);
    const result = await this.call([message], options, callbacks);
    if (typeof result.content !== "string") {
      throw new Error("Cannot use predict when output is not a string.");
    }
    return result.content;
  }
  withStructuredOutput(outputSchema, config) {
    if (typeof this.bindTools !== "function") {
      throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`);
    }
    if (config?.strict) {
      throw new Error(`"strict" mode is not supported for this model by default.`);
    }
    const schema = outputSchema;
    const name = config?.name;
    const description = schema.description ?? "A function available to call.";
    const method = config?.method;
    const includeRaw = config?.includeRaw;
    if (method === "jsonMode") {
      throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`);
    }
    let functionName = name ?? "extract";
    let tools;
    if (isZodSchema(schema)) {
      tools = [
        {
          type: "function",
          function: {
            name: functionName,
            description,
            parameters: zodToJsonSchema(schema)
          }
        }
      ];
    } else {
      if ("name" in schema) {
        functionName = schema.name;
      }
      tools = [
        {
          type: "function",
          function: {
            name: functionName,
            description,
            parameters: schema
          }
        }
      ];
    }
    const llm = this.bindTools(tools);
    const outputParser = RunnableLambda.from((input) => {
      if (!input.tool_calls || input.tool_calls.length === 0) {
        throw new Error("No tool calls found in the response.");
      }
      const toolCall = input.tool_calls.find((tc) => tc.name === functionName);
      if (!toolCall) {
        throw new Error(`No tool call found with name ${functionName}.`);
      }
      return toolCall.args;
    });
    if (!includeRaw) {
      return llm.pipe(outputParser).withConfig({
        runName: "StructuredOutput"
      });
    }
    const parserAssign = RunnablePassthrough.assign({
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parsed: (input, config2) => outputParser.invoke(input.raw, config2)
    });
    const parserNone = RunnablePassthrough.assign({
      parsed: () => null
    });
    const parsedWithFallback = parserAssign.withFallbacks({
      fallbacks: [parserNone]
    });
    return RunnableSequence.from([
      {
        raw: llm
      },
      parsedWithFallback
    ]).withConfig({
      runName: "StructuredOutputRunnable"
    });
  }
};

// node_modules/@langchain/cohere/dist/chat_models.js
init_outputs2();

// node_modules/@langchain/core/utils/env.js
init_env3();

// node_modules/@langchain/cohere/node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex4 = [];
for (i3 = 0; i3 < 256; ++i3) {
  byteToHex4.push((i3 + 256).toString(16).slice(1));
}
var i3;
function unsafeStringify4(arr2, offset5 = 0) {
  return (byteToHex4[arr2[offset5 + 0]] + byteToHex4[arr2[offset5 + 1]] + byteToHex4[arr2[offset5 + 2]] + byteToHex4[arr2[offset5 + 3]] + "-" + byteToHex4[arr2[offset5 + 4]] + byteToHex4[arr2[offset5 + 5]] + "-" + byteToHex4[arr2[offset5 + 6]] + byteToHex4[arr2[offset5 + 7]] + "-" + byteToHex4[arr2[offset5 + 8]] + byteToHex4[arr2[offset5 + 9]] + "-" + byteToHex4[arr2[offset5 + 10]] + byteToHex4[arr2[offset5 + 11]] + byteToHex4[arr2[offset5 + 12]] + byteToHex4[arr2[offset5 + 13]] + byteToHex4[arr2[offset5 + 14]] + byteToHex4[arr2[offset5 + 15]]).toLowerCase();
}

// node_modules/@langchain/cohere/node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues4;
var rnds84 = new Uint8Array(16);
function rng4() {
  if (!getRandomValues4) {
    getRandomValues4 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues4) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues4(rnds84);
}

// node_modules/@langchain/cohere/node_modules/uuid/dist/esm-browser/native.js
var randomUUID4 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default4 = {
  randomUUID: randomUUID4
};

// node_modules/@langchain/cohere/node_modules/uuid/dist/esm-browser/v4.js
function v44(options, buf, offset5) {
  if (native_default4.randomUUID && !buf && !options) {
    return native_default4.randomUUID();
  }
  options = options || {};
  var rnds = options.random || (options.rng || rng4)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset5 = offset5 || 0;
    for (var i3 = 0; i3 < 16; ++i3) {
      buf[offset5 + i3] = rnds[i3];
    }
    return buf;
  }
  return unsafeStringify4(rnds);
}
var v4_default4 = v44;

// node_modules/@langchain/cohere/dist/chat_models.js
function convertToDocuments(observations) {
  const documents = [];
  let observationsList = [];
  if (typeof observations === "string") {
    observationsList = [{ output: observations }];
  } else if (
    // eslint-disable-next-line no-instanceof/no-instanceof
    observations instanceof Map || typeof observations === "object" && observations !== null && !Array.isArray(observations)
  ) {
    observationsList = [observations];
  } else if (!Array.isArray(observations)) {
    observationsList = [{ output: observations }];
  }
  for (let doc of observationsList) {
    if (!(doc instanceof Map) && (typeof doc !== "object" || doc === null)) {
      doc = { output: doc };
    }
    documents.push(doc);
  }
  return documents;
}
function convertMessageToCohereMessage(message, toolResults) {
  const getRole = (role) => {
    switch (role) {
      case "system":
        return "SYSTEM";
      case "human":
        return "USER";
      case "ai":
        return "CHATBOT";
      case "tool":
        return "TOOL";
      default:
        throw new Error(`Unknown message type: '${role}'. Accepted types: 'human', 'ai', 'system', 'tool'`);
    }
  };
  const getContent = (content) => {
    if (typeof content === "string") {
      return content;
    }
    throw new Error(`ChatCohere does not support non text message content. Received: ${JSON.stringify(content, null, 2)}`);
  };
  const getToolCall = (message2) => {
    if (isAIMessage(message2) && message2.tool_calls) {
      return message2.tool_calls.map((toolCall) => ({
        name: toolCall.name,
        parameters: toolCall.args
      }));
    }
    return [];
  };
  if (message._getType().toLowerCase() === "ai") {
    return {
      role: getRole(message._getType()),
      message: getContent(message.content),
      toolCalls: getToolCall(message)
    };
  } else if (message._getType().toLowerCase() === "tool") {
    return {
      role: getRole(message._getType()),
      message: getContent(message.content),
      toolResults
    };
  } else if (message._getType().toLowerCase() === "human" || message._getType().toLowerCase() === "system") {
    return {
      role: getRole(message._getType()),
      message: getContent(message.content)
    };
  } else {
    throw new Error("Got unknown message type. Supported types are AIMessage, ToolMessage, HumanMessage, and SystemMessage");
  }
}
function isCohereTool(tool2) {
  return "name" in tool2 && "description" in tool2 && "parameterDefinitions" in tool2;
}
function isToolMessage2(message) {
  return message._getType() === "tool";
}
function _convertJsonSchemaToCohereTool(jsonSchema) {
  const parameterDefinitionsProperties = "properties" in jsonSchema ? jsonSchema.properties : {};
  let parameterDefinitionsRequired = "required" in jsonSchema ? jsonSchema.required : [];
  const parameterDefinitionsFinal = {};
  Object.keys(parameterDefinitionsProperties).forEach((propertyName) => {
    parameterDefinitionsFinal[propertyName] = parameterDefinitionsProperties[propertyName];
    if (parameterDefinitionsRequired === void 0) {
      parameterDefinitionsRequired = [];
    }
    parameterDefinitionsFinal[propertyName].required = parameterDefinitionsRequired.includes(propertyName);
  });
  return parameterDefinitionsFinal;
}
function _formatToolsToCohere(tools) {
  if (!tools) {
    return void 0;
  } else if (tools.every(isCohereTool)) {
    return tools;
  } else if (tools.every(isOpenAITool)) {
    return tools.map((tool2) => {
      return {
        name: tool2.function.name,
        description: tool2.function.description ?? "",
        parameterDefinitions: _convertJsonSchemaToCohereTool(tool2.function.parameters)
      };
    });
  } else if (tools.every(isLangChainTool)) {
    return tools.map((tool2) => {
      const parameterDefinitionsFromZod = zodToJsonSchema(tool2.schema);
      return {
        name: tool2.name,
        description: tool2.description ?? "",
        parameterDefinitions: _convertJsonSchemaToCohereTool(parameterDefinitionsFromZod)
      };
    });
  } else {
    throw new Error(`Can not pass in a mix of tool schema types to ChatCohere.`);
  }
}
var ChatCohere = class extends BaseChatModel {
  static lc_name() {
    return "ChatCohere";
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "command-r-plus"
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 0.3
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "streamUsage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    const token = fields?.apiKey ?? getEnvironmentVariable2("COHERE_API_KEY");
    if (!token) {
      throw new Error("No API key provided for ChatCohere.");
    }
    this.client = new import_cohere_ai.CohereClient({
      token
    });
    this.model = fields?.model ?? this.model;
    this.temperature = fields?.temperature ?? this.temperature;
    this.streaming = fields?.streaming ?? this.streaming;
    this.streamUsage = fields?.streamUsage ?? this.streamUsage;
  }
  getLsParams(options) {
    const params = this.invocationParams(options);
    return {
      ls_provider: "cohere",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: this.temperature ?? void 0,
      ls_max_tokens: typeof params.maxTokens === "number" ? params.maxTokens : void 0,
      ls_stop: Array.isArray(params.stopSequences) ? params.stopSequences : void 0
    };
  }
  _llmType() {
    return "cohere";
  }
  invocationParams(options) {
    if (options.tool_choice) {
      throw new Error("'tool_choice' call option is not supported by ChatCohere.");
    }
    const params = {
      model: this.model,
      preamble: options.preamble,
      conversationId: options.conversationId,
      promptTruncation: options.promptTruncation,
      connectors: options.connectors,
      searchQueriesOnly: options.searchQueriesOnly,
      documents: options.documents,
      temperature: options.temperature ?? this.temperature,
      forceSingleStep: options.forceSingleStep,
      tools: options.tools
    };
    return Object.fromEntries(Object.entries(params).filter(([, value]) => value !== void 0));
  }
  bindTools(tools, kwargs) {
    return this.bind({
      tools: _formatToolsToCohere(tools),
      ...kwargs
    });
  }
  /** @ignore */
  _getChatRequest(messages, options) {
    const params = this.invocationParams(options);
    const toolResults = this._messagesToCohereToolResultsCurrChatTurn(messages);
    const chatHistory = [];
    let messageStr = "";
    let tempToolResults = [];
    if (!params.forceSingleStep) {
      for (let i3 = 0; i3 < messages.length - 1; i3 += 1) {
        const message = messages[i3];
        if (message._getType().toLowerCase() === "tool") {
          tempToolResults = tempToolResults.concat(this._messageToCohereToolResults(messages, i3));
          if (i3 === messages.length - 1 || !(messages[i3 + 1]._getType().toLowerCase() === "tool")) {
            const cohere_message = convertMessageToCohereMessage(message, tempToolResults);
            chatHistory.push(cohere_message);
            tempToolResults = [];
          }
        } else {
          chatHistory.push(convertMessageToCohereMessage(message, []));
        }
      }
      messageStr = toolResults.length > 0 ? "" : messages[messages.length - 1].content.toString();
    } else {
      messageStr = "";
      for (let i3 = 0; i3 < messages.length - 1; i3 += 1) {
        const message = messages[i3];
        if (isAIMessage(message) && message.tool_calls) {
          continue;
        }
        if (message._getType().toLowerCase() === "tool") {
          tempToolResults = tempToolResults.concat(this._messageToCohereToolResults(messages, i3));
          if (i3 === messages.length - 1 || !(messages[i3 + 1]._getType().toLowerCase() === "tool")) {
            const cohereMessage = convertMessageToCohereMessage(message, tempToolResults);
            chatHistory.push(cohereMessage);
            tempToolResults = [];
          }
        } else {
          chatHistory.push(convertMessageToCohereMessage(message, []));
        }
      }
      for (let i3 = messages.length - 1; i3 >= 0; i3 -= 1) {
        const message = messages[i3];
        if (message._getType().toLowerCase() === "human" && message.content) {
          messageStr = message.content.toString();
          break;
        }
      }
    }
    const req = {
      message: messageStr,
      chatHistory,
      toolResults: toolResults.length > 0 ? toolResults : void 0,
      ...params
    };
    return req;
  }
  _getCurrChatTurnMessages(messages) {
    const currentChatTurnMessages = [];
    for (let i3 = messages.length - 1; i3 >= 0; i3 -= 1) {
      const message = messages[i3];
      currentChatTurnMessages.push(message);
      if (message._getType().toLowerCase() === "human") {
        break;
      }
    }
    return currentChatTurnMessages.reverse();
  }
  _messagesToCohereToolResultsCurrChatTurn(messages) {
    const toolResults = [];
    const currChatTurnMessages = this._getCurrChatTurnMessages(messages);
    for (const message of currChatTurnMessages) {
      if (isToolMessage2(message)) {
        const toolMessage = message;
        const previousAiMsgs = currChatTurnMessages.filter((msg) => isAIMessage(msg) && msg.tool_calls !== void 0);
        if (previousAiMsgs.length > 0) {
          const previousAiMsg = previousAiMsgs[previousAiMsgs.length - 1];
          if (previousAiMsg.tool_calls) {
            toolResults.push(...previousAiMsg.tool_calls.filter((lcToolCall) => lcToolCall.id === toolMessage.tool_call_id).map((lcToolCall) => ({
              call: {
                name: lcToolCall.name,
                parameters: lcToolCall.args
              },
              outputs: convertToDocuments(toolMessage.content)
            })));
          }
        }
      }
    }
    return toolResults;
  }
  _messageToCohereToolResults(messages, toolMessageIndex) {
    const toolResults = [];
    const toolMessage = messages[toolMessageIndex];
    if (!isToolMessage2(toolMessage)) {
      throw new Error("The message index does not correspond to an instance of ToolMessage");
    }
    const messagesUntilTool = messages.slice(0, toolMessageIndex);
    const previousAiMessage = messagesUntilTool.filter((message) => isAIMessage(message) && message.tool_calls).slice(-1)[0];
    if (previousAiMessage.tool_calls) {
      toolResults.push(...previousAiMessage.tool_calls.filter((lcToolCall) => lcToolCall.id === toolMessage.tool_call_id).map((lcToolCall) => ({
        call: {
          name: lcToolCall.name,
          parameters: lcToolCall.args
        },
        outputs: convertToDocuments(toolMessage.content)
      })));
    }
    return toolResults;
  }
  _formatCohereToolCalls(toolCalls = null) {
    if (!toolCalls) {
      return [];
    }
    const formattedToolCalls = [];
    for (const toolCall of toolCalls) {
      formattedToolCalls.push({
        id: v4_default4().substring(0, 32),
        function: {
          name: toolCall.name,
          arguments: toolCall.parameters
          // Convert arguments to string
        },
        type: "function"
      });
    }
    return formattedToolCalls;
  }
  _convertCohereToolCallToLangchain(toolCalls) {
    return toolCalls.map((toolCall) => ({
      name: toolCall.function.name,
      args: toolCall.function.arguments,
      id: toolCall.id,
      type: "tool_call"
    }));
  }
  /** @ignore */
  async _generate(messages, options, runManager) {
    const tokenUsage = {};
    const request = this._getChatRequest(messages, options);
    if (this.streaming) {
      const stream = this._streamResponseChunks(messages, options, runManager);
      const finalChunks = {};
      for await (const chunk of stream) {
        const index2 = chunk.generationInfo?.completion ?? 0;
        if (finalChunks[index2] === void 0) {
          finalChunks[index2] = chunk;
        } else {
          finalChunks[index2] = finalChunks[index2].concat(chunk);
        }
      }
      const generations2 = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_2, value]) => value);
      return { generations: generations2, llmOutput: { estimatedTokenUsage: tokenUsage } };
    }
    const response = await this.caller.callWithOptions({ signal: options.signal }, async () => {
      let response2;
      try {
        response2 = await this.client.chat(request);
      } catch (e3) {
        e3.status = e3.status ?? e3.statusCode;
        throw e3;
      }
      return response2;
    });
    if (response.meta?.tokens) {
      const { inputTokens, outputTokens } = response.meta.tokens;
      if (outputTokens) {
        tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + outputTokens;
      }
      if (inputTokens) {
        tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + inputTokens;
      }
      tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + (tokenUsage.promptTokens ?? 0) + (tokenUsage.completionTokens ?? 0);
    }
    const generationInfo = { ...response };
    delete generationInfo.text;
    if (response.toolCalls && response.toolCalls.length > 0) {
      generationInfo.toolCalls = this._formatCohereToolCalls(response.toolCalls);
    }
    let toolCalls = [];
    if ("toolCalls" in generationInfo) {
      toolCalls = this._convertCohereToolCallToLangchain(generationInfo.toolCalls);
    }
    const generations = [
      {
        text: response.text,
        message: new AIMessage({
          content: response.text,
          additional_kwargs: generationInfo,
          tool_calls: toolCalls,
          usage_metadata: {
            input_tokens: tokenUsage.promptTokens ?? 0,
            output_tokens: tokenUsage.completionTokens ?? 0,
            total_tokens: tokenUsage.totalTokens ?? 0
          }
        }),
        generationInfo
      }
    ];
    return {
      generations,
      llmOutput: { estimatedTokenUsage: tokenUsage }
    };
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const request = this._getChatRequest(messages, options);
    const stream = await this.caller.call(async () => {
      let stream2;
      try {
        stream2 = await this.client.chatStream(request);
      } catch (e3) {
        e3.status = e3.status ?? e3.statusCode;
        throw e3;
      }
      return stream2;
    });
    for await (const chunk of stream) {
      if (chunk.eventType === "text-generation") {
        yield new ChatGenerationChunk({
          text: chunk.text,
          message: new AIMessageChunk({
            content: chunk.text
          })
        });
        await runManager?.handleLLMNewToken(chunk.text);
      } else if (chunk.eventType !== "stream-end") {
        yield new ChatGenerationChunk({
          text: "",
          message: new AIMessageChunk({
            content: "",
            additional_kwargs: {
              ...chunk
            }
          }),
          generationInfo: {
            ...chunk
          }
        });
      } else if (chunk.eventType === "stream-end" && (this.streamUsage || options.streamUsage)) {
        const input_tokens = chunk.response.meta?.tokens?.inputTokens ?? 0;
        const output_tokens = chunk.response.meta?.tokens?.outputTokens ?? 0;
        const chunkGenerationInfo = {
          ...chunk.response
        };
        if (chunk.response.toolCalls && chunk.response.toolCalls.length > 0) {
          chunkGenerationInfo.toolCalls = this._formatCohereToolCalls(chunk.response.toolCalls);
        }
        let toolCallChunks = [];
        const toolCalls = chunkGenerationInfo.toolCalls ?? [];
        if (toolCalls.length > 0) {
          toolCallChunks = toolCalls.map((toolCall) => ({
            name: toolCall.function.name,
            args: toolCall.function.arguments,
            id: toolCall.id,
            index: toolCall.index,
            type: "tool_call_chunk"
          }));
        }
        yield new ChatGenerationChunk({
          text: "",
          message: new AIMessageChunk({
            content: "",
            additional_kwargs: {
              eventType: "stream-end"
            },
            tool_call_chunks: toolCallChunks,
            usage_metadata: {
              input_tokens,
              output_tokens,
              total_tokens: input_tokens + output_tokens
            }
          }),
          generationInfo: {
            eventType: "stream-end",
            ...chunkGenerationInfo
          }
        });
      }
    }
  }
  _combineLLMOutput(...llmOutputs) {
    return llmOutputs.reduce((acc, llmOutput) => {
      if (llmOutput && llmOutput.estimatedTokenUsage) {
        let completionTokens = acc.estimatedTokenUsage?.completionTokens ?? 0;
        let promptTokens = acc.estimatedTokenUsage?.promptTokens ?? 0;
        let totalTokens = acc.estimatedTokenUsage?.totalTokens ?? 0;
        completionTokens += llmOutput.estimatedTokenUsage.completionTokens ?? 0;
        promptTokens += llmOutput.estimatedTokenUsage.promptTokens ?? 0;
        totalTokens += llmOutput.estimatedTokenUsage.totalTokens ?? 0;
        acc.estimatedTokenUsage = {
          completionTokens,
          promptTokens,
          totalTokens
        };
      }
      return acc;
    }, {
      estimatedTokenUsage: {
        completionTokens: 0,
        promptTokens: 0,
        totalTokens: 0
      }
    });
  }
  get lc_secrets() {
    return {
      apiKey: "COHERE_API_KEY",
      api_key: "COHERE_API_KEY"
    };
  }
  get lc_aliases() {
    return {
      apiKey: "cohere_api_key",
      api_key: "cohere_api_key"
    };
  }
};

// node_modules/@langchain/cohere/dist/llms.js
var import_cohere_ai2 = __toESM(require_cohere_ai(), 1);

// node_modules/@langchain/core/dist/language_models/llms.js
init_messages2();
init_outputs();
init_manager();
init_base8();
init_stream();
init_base();

// node_modules/@langchain/cohere/dist/embeddings.js
var import_cohere_ai3 = __toESM(require_cohere_ai(), 1);

// node_modules/@langchain/core/dist/embeddings.js
init_async_caller2();
var Embeddings = class {
  constructor(params) {
    Object.defineProperty(this, "caller", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.caller = new AsyncCaller2(params ?? {});
  }
};

// node_modules/@langchain/core/dist/utils/chunk_array.js
var chunkArray = (arr2, chunkSize) => arr2.reduce((chunks, elem, index2) => {
  const chunkIndex = Math.floor(index2 / chunkSize);
  const chunk = chunks[chunkIndex] || [];
  chunks[chunkIndex] = chunk.concat([elem]);
  return chunks;
}, []);

// node_modules/@langchain/cohere/dist/embeddings.js
var CohereEmbeddings = class extends Embeddings {
  /**
   * Constructor for the CohereEmbeddings class.
   * @param fields - An optional object with properties to configure the instance.
   */
  constructor(fields) {
    const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
    super(fieldsWithDefaults);
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "batchSize", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 48
    });
    Object.defineProperty(this, "embeddingTypes", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["float"]
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    const apiKey = fieldsWithDefaults?.apiKey || getEnvironmentVariable2("COHERE_API_KEY");
    if (!apiKey) {
      throw new Error("Cohere API key not found");
    }
    this.client = new import_cohere_ai3.CohereClient({
      token: apiKey
    });
    this.model = fieldsWithDefaults?.model ?? this.model;
    if (!this.model) {
      throw new Error("Model not specified for CohereEmbeddings instance. Please provide a model name from the options here: https://docs.cohere.com/reference/embed");
    }
    this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
    this.embeddingTypes = fieldsWithDefaults?.embeddingTypes ?? this.embeddingTypes;
  }
  /**
   * Generates embeddings for an array of texts.
   * @param texts - An array of strings to generate embeddings for.
   * @returns A Promise that resolves to an array of embeddings.
   */
  async embedDocuments(texts) {
    const batches = chunkArray(texts, this.batchSize);
    const batchRequests = batches.map((batch) => this.embeddingWithRetry({
      model: this.model,
      texts: batch,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      inputType: "search_document",
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      embeddingTypes: this.embeddingTypes
    }));
    const batchResponses = await Promise.all(batchRequests);
    const embeddings = [];
    for (let i3 = 0; i3 < batchResponses.length; i3 += 1) {
      const batch = batches[i3];
      const { embeddings: batchResponse } = batchResponses[i3];
      for (let j3 = 0; j3 < batch.length; j3 += 1) {
        if ("float" in batchResponse && batchResponse.float) {
          embeddings.push(batchResponse.float[j3]);
        } else if (Array.isArray(batchResponse)) {
          embeddings.push(batchResponse[j3]);
        }
      }
    }
    return embeddings;
  }
  /**
   * Generates an embedding for a single text.
   * @param text - A string to generate an embedding for.
   * @returns A Promise that resolves to an array of numbers representing the embedding.
   */
  async embedQuery(text) {
    const { embeddings } = await this.embeddingWithRetry({
      model: this.model,
      texts: [text],
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      inputType: "search_query",
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      embeddingTypes: this.embeddingTypes
    });
    if ("float" in embeddings && embeddings.float) {
      return embeddings.float[0];
    } else if (Array.isArray(embeddings)) {
      return embeddings[0];
    } else {
      throw new Error(`Invalid response from Cohere API. Received: ${JSON.stringify(embeddings, null, 2)}`);
    }
  }
  async embed(request) {
    const { embeddings } = await this.embeddingWithRetry(request);
    if ("float" in embeddings && embeddings.float) {
      return embeddings.float[0];
    } else if (Array.isArray(embeddings)) {
      return embeddings[0];
    } else {
      throw new Error(`Invalid response from Cohere API. Received: ${JSON.stringify(embeddings, null, 2)}`);
    }
  }
  /**
   * Generates embeddings with retry capabilities.
   * @param request - An object containing the request parameters for generating embeddings.
   * @returns A Promise that resolves to the API response.
   */
  async embeddingWithRetry(request) {
    return this.caller.call(async () => {
      let response;
      try {
        response = await this.client.embed(request);
      } catch (e3) {
        e3.status = e3.status ?? e3.statusCode;
        throw e3;
      }
      return response;
    });
  }
  get lc_secrets() {
    return {
      apiKey: "COHERE_API_KEY",
      api_key: "COHERE_API_KEY"
    };
  }
  get lc_aliases() {
    return {
      apiKey: "cohere_api_key",
      api_key: "cohere_api_key"
    };
  }
};

// node_modules/@langchain/cohere/dist/rerank.js
var import_cohere_ai4 = __toESM(require_cohere_ai(), 1);

// node_modules/@google/generative-ai/dist/index.mjs
var SchemaType;
(function(SchemaType2) {
  SchemaType2["STRING"] = "string";
  SchemaType2["NUMBER"] = "number";
  SchemaType2["INTEGER"] = "integer";
  SchemaType2["BOOLEAN"] = "boolean";
  SchemaType2["ARRAY"] = "array";
  SchemaType2["OBJECT"] = "object";
})(SchemaType || (SchemaType = {}));
var ExecutableCodeLanguage;
(function(ExecutableCodeLanguage2) {
  ExecutableCodeLanguage2["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
  ExecutableCodeLanguage2["PYTHON"] = "python";
})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));
var Outcome;
(function(Outcome2) {
  Outcome2["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
  Outcome2["OUTCOME_OK"] = "outcome_ok";
  Outcome2["OUTCOME_FAILED"] = "outcome_failed";
  Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
})(Outcome || (Outcome = {}));
var POSSIBLE_ROLES = ["user", "model", "function", "system"];
var HarmCategory;
(function(HarmCategory2) {
  HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
  HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
  HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
  HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
  HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
})(HarmCategory || (HarmCategory = {}));
var HarmBlockThreshold;
(function(HarmBlockThreshold2) {
  HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
  HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE";
})(HarmBlockThreshold || (HarmBlockThreshold = {}));
var HarmProbability;
(function(HarmProbability2) {
  HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
  HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE";
  HarmProbability2["LOW"] = "LOW";
  HarmProbability2["MEDIUM"] = "MEDIUM";
  HarmProbability2["HIGH"] = "HIGH";
})(HarmProbability || (HarmProbability = {}));
var BlockReason;
(function(BlockReason2) {
  BlockReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
  BlockReason2["SAFETY"] = "SAFETY";
  BlockReason2["OTHER"] = "OTHER";
})(BlockReason || (BlockReason = {}));
var FinishReason;
(function(FinishReason2) {
  FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
  FinishReason2["STOP"] = "STOP";
  FinishReason2["MAX_TOKENS"] = "MAX_TOKENS";
  FinishReason2["SAFETY"] = "SAFETY";
  FinishReason2["RECITATION"] = "RECITATION";
  FinishReason2["LANGUAGE"] = "LANGUAGE";
  FinishReason2["OTHER"] = "OTHER";
})(FinishReason || (FinishReason = {}));
var TaskType;
(function(TaskType2) {
  TaskType2["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
  TaskType2["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
  TaskType2["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
  TaskType2["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
  TaskType2["CLASSIFICATION"] = "CLASSIFICATION";
  TaskType2["CLUSTERING"] = "CLUSTERING";
})(TaskType || (TaskType = {}));
var FunctionCallingMode;
(function(FunctionCallingMode2) {
  FunctionCallingMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  FunctionCallingMode2["AUTO"] = "AUTO";
  FunctionCallingMode2["ANY"] = "ANY";
  FunctionCallingMode2["NONE"] = "NONE";
})(FunctionCallingMode || (FunctionCallingMode = {}));
var DynamicRetrievalMode;
(function(DynamicRetrievalMode2) {
  DynamicRetrievalMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  DynamicRetrievalMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
var GoogleGenerativeAIError = class extends Error {
  constructor(message) {
    super(`[GoogleGenerativeAI Error]: ${message}`);
  }
};
var GoogleGenerativeAIResponseError = class extends GoogleGenerativeAIError {
  constructor(message, response) {
    super(message);
    this.response = response;
  }
};
var GoogleGenerativeAIFetchError = class extends GoogleGenerativeAIError {
  constructor(message, status, statusText, errorDetails) {
    super(message);
    this.status = status;
    this.statusText = statusText;
    this.errorDetails = errorDetails;
  }
};
var GoogleGenerativeAIRequestInputError = class extends GoogleGenerativeAIError {
};
var DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
var DEFAULT_API_VERSION = "v1beta";
var PACKAGE_VERSION = "0.21.0";
var PACKAGE_LOG_HEADER = "genai-js";
var Task;
(function(Task2) {
  Task2["GENERATE_CONTENT"] = "generateContent";
  Task2["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
  Task2["COUNT_TOKENS"] = "countTokens";
  Task2["EMBED_CONTENT"] = "embedContent";
  Task2["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
})(Task || (Task = {}));
var RequestUrl = class {
  constructor(model, task, apiKey, stream, requestOptions) {
    this.model = model;
    this.task = task;
    this.apiKey = apiKey;
    this.stream = stream;
    this.requestOptions = requestOptions;
  }
  toString() {
    var _a5, _b;
    const apiVersion = ((_a5 = this.requestOptions) === null || _a5 === void 0 ? void 0 : _a5.apiVersion) || DEFAULT_API_VERSION;
    const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
    let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;
    if (this.stream) {
      url += "?alt=sse";
    }
    return url;
  }
};
function getClientHeaders(requestOptions) {
  const clientHeaders = [];
  if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
    clientHeaders.push(requestOptions.apiClient);
  }
  clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
  return clientHeaders.join(" ");
}
async function getHeaders(url) {
  var _a5;
  const headers = new Headers();
  headers.append("Content-Type", "application/json");
  headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
  headers.append("x-goog-api-key", url.apiKey);
  let customHeaders = (_a5 = url.requestOptions) === null || _a5 === void 0 ? void 0 : _a5.customHeaders;
  if (customHeaders) {
    if (!(customHeaders instanceof Headers)) {
      try {
        customHeaders = new Headers(customHeaders);
      } catch (e3) {
        throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e3.message}`);
      }
    }
    for (const [headerName, headerValue] of customHeaders.entries()) {
      if (headerName === "x-goog-api-key") {
        throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
      } else if (headerName === "x-goog-api-client") {
        throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
      }
      headers.append(headerName, headerValue);
    }
  }
  return headers;
}
async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {
  const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
  return {
    url: url.toString(),
    fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body })
  };
}
async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, fetchFn = fetch) {
  const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);
  return makeRequest(url, fetchOptions, fetchFn);
}
async function makeRequest(url, fetchOptions, fetchFn = fetch) {
  let response;
  try {
    response = await fetchFn(url, fetchOptions);
  } catch (e3) {
    handleResponseError(e3, url);
  }
  if (!response.ok) {
    await handleResponseNotOk(response, url);
  }
  return response;
}
function handleResponseError(e3, url) {
  let err = e3;
  if (!(e3 instanceof GoogleGenerativeAIFetchError || e3 instanceof GoogleGenerativeAIRequestInputError)) {
    err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e3.message}`);
    err.stack = e3.stack;
  }
  throw err;
}
async function handleResponseNotOk(response, url) {
  let message = "";
  let errorDetails;
  try {
    const json = await response.json();
    message = json.error.message;
    if (json.error.details) {
      message += ` ${JSON.stringify(json.error.details)}`;
      errorDetails = json.error.details;
    }
  } catch (e3) {
  }
  throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
}
function buildFetchOptions(requestOptions) {
  const fetchOptions = {};
  if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== void 0 || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
    const controller = new AbortController();
    if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
      setTimeout(() => controller.abort(), requestOptions.timeout);
    }
    if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {
      requestOptions.signal.addEventListener("abort", () => {
        controller.abort();
      });
    }
    fetchOptions.signal = controller.signal;
  }
  return fetchOptions;
}
function addHelpers(response) {
  response.text = () => {
    if (response.candidates && response.candidates.length > 0) {
      if (response.candidates.length > 1) {
        console.warn(`This response had ${response.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`);
      }
      if (hadBadFinishReason(response.candidates[0])) {
        throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
      }
      return getText(response);
    } else if (response.promptFeedback) {
      throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
    }
    return "";
  };
  response.functionCall = () => {
    if (response.candidates && response.candidates.length > 0) {
      if (response.candidates.length > 1) {
        console.warn(`This response had ${response.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);
      }
      if (hadBadFinishReason(response.candidates[0])) {
        throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
      }
      console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`);
      return getFunctionCalls(response)[0];
    } else if (response.promptFeedback) {
      throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
    }
    return void 0;
  };
  response.functionCalls = () => {
    if (response.candidates && response.candidates.length > 0) {
      if (response.candidates.length > 1) {
        console.warn(`This response had ${response.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);
      }
      if (hadBadFinishReason(response.candidates[0])) {
        throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
      }
      return getFunctionCalls(response);
    } else if (response.promptFeedback) {
      throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
    }
    return void 0;
  };
  return response;
}
function getText(response) {
  var _a5, _b, _c, _d;
  const textStrings = [];
  if ((_b = (_a5 = response.candidates) === null || _a5 === void 0 ? void 0 : _a5[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
    for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
      if (part.text) {
        textStrings.push(part.text);
      }
      if (part.executableCode) {
        textStrings.push("\n```" + part.executableCode.language + "\n" + part.executableCode.code + "\n```\n");
      }
      if (part.codeExecutionResult) {
        textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n");
      }
    }
  }
  if (textStrings.length > 0) {
    return textStrings.join("");
  } else {
    return "";
  }
}
function getFunctionCalls(response) {
  var _a5, _b, _c, _d;
  const functionCalls = [];
  if ((_b = (_a5 = response.candidates) === null || _a5 === void 0 ? void 0 : _a5[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
    for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
      if (part.functionCall) {
        functionCalls.push(part.functionCall);
      }
    }
  }
  if (functionCalls.length > 0) {
    return functionCalls;
  } else {
    return void 0;
  }
}
var badFinishReasons = [
  FinishReason.RECITATION,
  FinishReason.SAFETY,
  FinishReason.LANGUAGE
];
function hadBadFinishReason(candidate) {
  return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason);
}
function formatBlockErrorMessage(response) {
  var _a5, _b, _c;
  let message = "";
  if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) {
    message += "Response was blocked";
    if ((_a5 = response.promptFeedback) === null || _a5 === void 0 ? void 0 : _a5.blockReason) {
      message += ` due to ${response.promptFeedback.blockReason}`;
    }
    if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
      message += `: ${response.promptFeedback.blockReasonMessage}`;
    }
  } else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
    const firstCandidate = response.candidates[0];
    if (hadBadFinishReason(firstCandidate)) {
      message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
      if (firstCandidate.finishMessage) {
        message += `: ${firstCandidate.finishMessage}`;
      }
    }
  }
  return message;
}
function __await5(v5) {
  return this instanceof __await5 ? (this.v = v5, this) : new __await5(v5);
}
function __asyncGenerator5(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var g4 = generator.apply(thisArg, _arguments || []), i3, q3 = [];
  return i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() {
    return this;
  }, i3;
  function verb(n4) {
    if (g4[n4])
      i3[n4] = function(v5) {
        return new Promise(function(a3, b3) {
          q3.push([n4, v5, a3, b3]) > 1 || resume(n4, v5);
        });
      };
  }
  function resume(n4, v5) {
    try {
      step(g4[n4](v5));
    } catch (e3) {
      settle(q3[0][3], e3);
    }
  }
  function step(r4) {
    r4.value instanceof __await5 ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f3, v5) {
    if (f3(v5), q3.shift(), q3.length)
      resume(q3[0][0], q3[0][1]);
  }
}
var responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
function processStream(response) {
  const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true }));
  const responseStream = getResponseStream(inputStream);
  const [stream1, stream2] = responseStream.tee();
  return {
    stream: generateResponseSequence(stream1),
    response: getResponsePromise(stream2)
  };
}
async function getResponsePromise(stream) {
  const allResponses = [];
  const reader = stream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      return addHelpers(aggregateResponses(allResponses));
    }
    allResponses.push(value);
  }
}
function generateResponseSequence(stream) {
  return __asyncGenerator5(this, arguments, function* generateResponseSequence_1() {
    const reader = stream.getReader();
    while (true) {
      const { value, done } = yield __await5(reader.read());
      if (done) {
        break;
      }
      yield yield __await5(addHelpers(value));
    }
  });
}
function getResponseStream(inputStream) {
  const reader = inputStream.getReader();
  const stream = new ReadableStream({
    start(controller) {
      let currentText = "";
      return pump();
      function pump() {
        return reader.read().then(({ value, done }) => {
          if (done) {
            if (currentText.trim()) {
              controller.error(new GoogleGenerativeAIError("Failed to parse stream"));
              return;
            }
            controller.close();
            return;
          }
          currentText += value;
          let match2 = currentText.match(responseLineRE);
          let parsedResponse;
          while (match2) {
            try {
              parsedResponse = JSON.parse(match2[1]);
            } catch (e3) {
              controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match2[1]}"`));
              return;
            }
            controller.enqueue(parsedResponse);
            currentText = currentText.substring(match2[0].length);
            match2 = currentText.match(responseLineRE);
          }
          return pump();
        });
      }
    }
  });
  return stream;
}
function aggregateResponses(responses) {
  const lastResponse = responses[responses.length - 1];
  const aggregatedResponse = {
    promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback
  };
  for (const response of responses) {
    if (response.candidates) {
      for (const candidate of response.candidates) {
        const i3 = candidate.index;
        if (!aggregatedResponse.candidates) {
          aggregatedResponse.candidates = [];
        }
        if (!aggregatedResponse.candidates[i3]) {
          aggregatedResponse.candidates[i3] = {
            index: candidate.index
          };
        }
        aggregatedResponse.candidates[i3].citationMetadata = candidate.citationMetadata;
        aggregatedResponse.candidates[i3].groundingMetadata = candidate.groundingMetadata;
        aggregatedResponse.candidates[i3].finishReason = candidate.finishReason;
        aggregatedResponse.candidates[i3].finishMessage = candidate.finishMessage;
        aggregatedResponse.candidates[i3].safetyRatings = candidate.safetyRatings;
        if (candidate.content && candidate.content.parts) {
          if (!aggregatedResponse.candidates[i3].content) {
            aggregatedResponse.candidates[i3].content = {
              role: candidate.content.role || "user",
              parts: []
            };
          }
          const newPart = {};
          for (const part of candidate.content.parts) {
            if (part.text) {
              newPart.text = part.text;
            }
            if (part.functionCall) {
              newPart.functionCall = part.functionCall;
            }
            if (part.executableCode) {
              newPart.executableCode = part.executableCode;
            }
            if (part.codeExecutionResult) {
              newPart.codeExecutionResult = part.codeExecutionResult;
            }
            if (Object.keys(newPart).length === 0) {
              newPart.text = "";
            }
            aggregatedResponse.candidates[i3].content.parts.push(newPart);
          }
        }
      }
    }
    if (response.usageMetadata) {
      aggregatedResponse.usageMetadata = response.usageMetadata;
    }
  }
  return aggregatedResponse;
}
async function generateContentStream(apiKey, model, params, requestOptions) {
  const response = await makeModelRequest(
    model,
    Task.STREAM_GENERATE_CONTENT,
    apiKey,
    /* stream */
    true,
    JSON.stringify(params),
    requestOptions
  );
  return processStream(response);
}
async function generateContent(apiKey, model, params, requestOptions) {
  const response = await makeModelRequest(
    model,
    Task.GENERATE_CONTENT,
    apiKey,
    /* stream */
    false,
    JSON.stringify(params),
    requestOptions
  );
  const responseJson = await response.json();
  const enhancedResponse = addHelpers(responseJson);
  return {
    response: enhancedResponse
  };
}
function formatSystemInstruction(input) {
  if (input == null) {
    return void 0;
  } else if (typeof input === "string") {
    return { role: "system", parts: [{ text: input }] };
  } else if (input.text) {
    return { role: "system", parts: [input] };
  } else if (input.parts) {
    if (!input.role) {
      return { role: "system", parts: input.parts };
    } else {
      return input;
    }
  }
}
function formatNewContent(request) {
  let newParts = [];
  if (typeof request === "string") {
    newParts = [{ text: request }];
  } else {
    for (const partOrString of request) {
      if (typeof partOrString === "string") {
        newParts.push({ text: partOrString });
      } else {
        newParts.push(partOrString);
      }
    }
  }
  return assignRoleToPartsAndValidateSendMessageRequest(newParts);
}
function assignRoleToPartsAndValidateSendMessageRequest(parts) {
  const userContent = { role: "user", parts: [] };
  const functionContent = { role: "function", parts: [] };
  let hasUserContent = false;
  let hasFunctionContent = false;
  for (const part of parts) {
    if ("functionResponse" in part) {
      functionContent.parts.push(part);
      hasFunctionContent = true;
    } else {
      userContent.parts.push(part);
      hasUserContent = true;
    }
  }
  if (hasUserContent && hasFunctionContent) {
    throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");
  }
  if (!hasUserContent && !hasFunctionContent) {
    throw new GoogleGenerativeAIError("No content is provided for sending chat message.");
  }
  if (hasUserContent) {
    return userContent;
  }
  return functionContent;
}
function formatCountTokensInput(params, modelParams) {
  var _a5;
  let formattedGenerateContentRequest = {
    model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,
    generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,
    safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,
    tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,
    toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,
    systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,
    cachedContent: (_a5 = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a5 === void 0 ? void 0 : _a5.name,
    contents: []
  };
  const containsGenerateContentRequest = params.generateContentRequest != null;
  if (params.contents) {
    if (containsGenerateContentRequest) {
      throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both.");
    }
    formattedGenerateContentRequest.contents = params.contents;
  } else if (containsGenerateContentRequest) {
    formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);
  } else {
    const content = formatNewContent(params);
    formattedGenerateContentRequest.contents = [content];
  }
  return { generateContentRequest: formattedGenerateContentRequest };
}
function formatGenerateContentInput(params) {
  let formattedRequest;
  if (params.contents) {
    formattedRequest = params;
  } else {
    const content = formatNewContent(params);
    formattedRequest = { contents: [content] };
  }
  if (params.systemInstruction) {
    formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
  }
  return formattedRequest;
}
function formatEmbedContentInput(params) {
  if (typeof params === "string" || Array.isArray(params)) {
    const content = formatNewContent(params);
    return { content };
  }
  return params;
}
var VALID_PART_FIELDS = [
  "text",
  "inlineData",
  "functionCall",
  "functionResponse",
  "executableCode",
  "codeExecutionResult"
];
var VALID_PARTS_PER_ROLE = {
  user: ["text", "inlineData"],
  function: ["functionResponse"],
  model: ["text", "functionCall", "executableCode", "codeExecutionResult"],
  // System instructions shouldn't be in history anyway.
  system: ["text"]
};
function validateChatHistory(history) {
  let prevContent = false;
  for (const currContent of history) {
    const { role, parts } = currContent;
    if (!prevContent && role !== "user") {
      throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);
    }
    if (!POSSIBLE_ROLES.includes(role)) {
      throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
    }
    if (!Array.isArray(parts)) {
      throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts");
    }
    if (parts.length === 0) {
      throw new GoogleGenerativeAIError("Each Content should have at least one part");
    }
    const countFields = {
      text: 0,
      inlineData: 0,
      functionCall: 0,
      functionResponse: 0,
      fileData: 0,
      executableCode: 0,
      codeExecutionResult: 0
    };
    for (const part of parts) {
      for (const key of VALID_PART_FIELDS) {
        if (key in part) {
          countFields[key] += 1;
        }
      }
    }
    const validParts = VALID_PARTS_PER_ROLE[role];
    for (const key of VALID_PART_FIELDS) {
      if (!validParts.includes(key) && countFields[key] > 0) {
        throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);
      }
    }
    prevContent = true;
  }
}
var SILENT_ERROR = "SILENT_ERROR";
var ChatSession = class {
  constructor(apiKey, model, params, _requestOptions = {}) {
    this.model = model;
    this.params = params;
    this._requestOptions = _requestOptions;
    this._history = [];
    this._sendPromise = Promise.resolve();
    this._apiKey = apiKey;
    if (params === null || params === void 0 ? void 0 : params.history) {
      validateChatHistory(params.history);
      this._history = params.history;
    }
  }
  /**
   * Gets the chat history so far. Blocked prompts are not added to history.
   * Blocked candidates are not added to history, nor are the prompts that
   * generated them.
   */
  async getHistory() {
    await this._sendPromise;
    return this._history;
  }
  /**
   * Sends a chat message and receives a non-streaming
   * {@link GenerateContentResult}.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async sendMessage(request, requestOptions = {}) {
    var _a5, _b, _c, _d, _e, _f;
    await this._sendPromise;
    const newContent = formatNewContent(request);
    const generateContentRequest = {
      safetySettings: (_a5 = this.params) === null || _a5 === void 0 ? void 0 : _a5.safetySettings,
      generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
      tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
      toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
      systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
      cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
      contents: [...this._history, newContent]
    };
    const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    let finalResult;
    this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result) => {
      var _a6;
      if (result.response.candidates && result.response.candidates.length > 0) {
        this._history.push(newContent);
        const responseContent = Object.assign({
          parts: [],
          // Response seems to come back without a role set.
          role: "model"
        }, (_a6 = result.response.candidates) === null || _a6 === void 0 ? void 0 : _a6[0].content);
        this._history.push(responseContent);
      } else {
        const blockErrorMessage = formatBlockErrorMessage(result.response);
        if (blockErrorMessage) {
          console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
        }
      }
      finalResult = result;
    });
    await this._sendPromise;
    return finalResult;
  }
  /**
   * Sends a chat message and receives the response as a
   * {@link GenerateContentStreamResult} containing an iterable stream
   * and a response promise.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async sendMessageStream(request, requestOptions = {}) {
    var _a5, _b, _c, _d, _e, _f;
    await this._sendPromise;
    const newContent = formatNewContent(request);
    const generateContentRequest = {
      safetySettings: (_a5 = this.params) === null || _a5 === void 0 ? void 0 : _a5.safetySettings,
      generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
      tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
      toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
      systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
      cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
      contents: [...this._history, newContent]
    };
    const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);
    this._sendPromise = this._sendPromise.then(() => streamPromise).catch((_ignored) => {
      throw new Error(SILENT_ERROR);
    }).then((streamResult) => streamResult.response).then((response) => {
      if (response.candidates && response.candidates.length > 0) {
        this._history.push(newContent);
        const responseContent = Object.assign({}, response.candidates[0].content);
        if (!responseContent.role) {
          responseContent.role = "model";
        }
        this._history.push(responseContent);
      } else {
        const blockErrorMessage = formatBlockErrorMessage(response);
        if (blockErrorMessage) {
          console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
        }
      }
    }).catch((e3) => {
      if (e3.message !== SILENT_ERROR) {
        console.error(e3);
      }
    });
    return streamPromise;
  }
};
async function countTokens(apiKey, model, params, singleRequestOptions) {
  const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);
  return response.json();
}
async function embedContent(apiKey, model, params, requestOptions) {
  const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
  return response.json();
}
async function batchEmbedContents(apiKey, model, params, requestOptions) {
  const requestsWithModel = params.requests.map((request) => {
    return Object.assign(Object.assign({}, request), { model });
  });
  const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);
  return response.json();
}
var GenerativeModel = class {
  constructor(apiKey, modelParams, _requestOptions = {}) {
    this.apiKey = apiKey;
    this._requestOptions = _requestOptions;
    if (modelParams.model.includes("/")) {
      this.model = modelParams.model;
    } else {
      this.model = `models/${modelParams.model}`;
    }
    this.generationConfig = modelParams.generationConfig || {};
    this.safetySettings = modelParams.safetySettings || [];
    this.tools = modelParams.tools;
    this.toolConfig = modelParams.toolConfig;
    this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
    this.cachedContent = modelParams.cachedContent;
  }
  /**
   * Makes a single non-streaming call to the model
   * and returns an object containing a single {@link GenerateContentResponse}.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async generateContent(request, requestOptions = {}) {
    var _a5;
    const formattedParams = formatGenerateContentInput(request);
    const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a5 = this.cachedContent) === null || _a5 === void 0 ? void 0 : _a5.name }, formattedParams), generativeModelRequestOptions);
  }
  /**
   * Makes a single streaming call to the model and returns an object
   * containing an iterable stream that iterates over all chunks in the
   * streaming response as well as a promise that returns the final
   * aggregated response.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async generateContentStream(request, requestOptions = {}) {
    var _a5;
    const formattedParams = formatGenerateContentInput(request);
    const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a5 = this.cachedContent) === null || _a5 === void 0 ? void 0 : _a5.name }, formattedParams), generativeModelRequestOptions);
  }
  /**
   * Gets a new {@link ChatSession} instance which can be used for
   * multi-turn chats.
   */
  startChat(startChatParams) {
    var _a5;
    return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a5 = this.cachedContent) === null || _a5 === void 0 ? void 0 : _a5.name }, startChatParams), this._requestOptions);
  }
  /**
   * Counts the tokens in the provided request.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async countTokens(request, requestOptions = {}) {
    const formattedParams = formatCountTokensInput(request, {
      model: this.model,
      generationConfig: this.generationConfig,
      safetySettings: this.safetySettings,
      tools: this.tools,
      toolConfig: this.toolConfig,
      systemInstruction: this.systemInstruction,
      cachedContent: this.cachedContent
    });
    const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
  }
  /**
   * Embeds the provided content.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async embedContent(request, requestOptions = {}) {
    const formattedParams = formatEmbedContentInput(request);
    const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
  }
  /**
   * Embeds an array of {@link EmbedContentRequest}s.
   *
   * Fields set in the optional {@link SingleRequestOptions} parameter will
   * take precedence over the {@link RequestOptions} values provided to
   * {@link GoogleGenerativeAI.getGenerativeModel }.
   */
  async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {
    const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
    return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);
  }
};
var GoogleGenerativeAI = class {
  constructor(apiKey) {
    this.apiKey = apiKey;
  }
  /**
   * Gets a {@link GenerativeModel} instance for the provided model name.
   */
  getGenerativeModel(modelParams, requestOptions) {
    if (!modelParams.model) {
      throw new GoogleGenerativeAIError(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);
    }
    return new GenerativeModel(this.apiKey, modelParams, requestOptions);
  }
  /**
   * Creates a {@link GenerativeModel} instance from provided content cache.
   */
  getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {
    if (!cachedContent.name) {
      throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field.");
    }
    if (!cachedContent.model) {
      throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
    }
    const disallowedDuplicates = ["model", "systemInstruction"];
    for (const key of disallowedDuplicates) {
      if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {
        if (key === "model") {
          const modelParamsComp = modelParams.model.startsWith("models/") ? modelParams.model.replace("models/", "") : modelParams.model;
          const cachedContentComp = cachedContent.model.startsWith("models/") ? cachedContent.model.replace("models/", "") : cachedContent.model;
          if (modelParamsComp === cachedContentComp) {
            continue;
          }
        }
        throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);
      }
    }
    const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent });
    return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);
  }
};

// node_modules/@langchain/google-genai/dist/chat_models.js
init_runnables2();

// node_modules/@langchain/google-genai/dist/utils/zod_to_genai_parameters.js
init_esm();
function removeAdditionalProperties(obj) {
  if (typeof obj === "object" && obj !== null) {
    const newObj = { ...obj };
    if ("additionalProperties" in newObj) {
      delete newObj.additionalProperties;
    }
    if ("$schema" in newObj) {
      delete newObj.$schema;
    }
    for (const key in newObj) {
      if (key in newObj) {
        if (Array.isArray(newObj[key])) {
          newObj[key] = newObj[key].map(removeAdditionalProperties);
        } else if (typeof newObj[key] === "object" && newObj[key] !== null) {
          newObj[key] = removeAdditionalProperties(newObj[key]);
        }
      }
    }
    return newObj;
  }
  return obj;
}
function zodToGenerativeAIParameters(zodObj) {
  const jsonSchema = removeAdditionalProperties(zodToJsonSchema(zodObj));
  const { $schema, ...rest } = jsonSchema;
  return rest;
}
function jsonSchemaToGeminiParameters(schema) {
  const jsonSchema = removeAdditionalProperties(schema);
  const { $schema, ...rest } = jsonSchema;
  return rest;
}

// node_modules/@langchain/google-genai/dist/utils/common.js
init_outputs2();
init_base9();
function getMessageAuthor(message) {
  const type = message._getType();
  if (ChatMessage.isInstance(message)) {
    return message.role;
  }
  if (type === "tool") {
    return type;
  }
  return message.name ?? type;
}
function convertAuthorToRole(author) {
  switch (author) {
    case "ai":
    case "model":
      return "model";
    case "system":
      return "system";
    case "human":
      return "user";
    case "tool":
    case "function":
      return "function";
    default:
      throw new Error(`Unknown / unsupported author: ${author}`);
  }
}
function messageContentMedia(content) {
  if ("mimeType" in content && "data" in content) {
    return {
      inlineData: {
        mimeType: content.mimeType,
        data: content.data
      }
    };
  }
  throw new Error("Invalid media content");
}
function convertMessageContentToParts(message, isMultimodalModel) {
  if (typeof message.content === "string" && message.content !== "") {
    return [{ text: message.content }];
  }
  let functionCalls = [];
  let functionResponses = [];
  let messageParts = [];
  if ("tool_calls" in message && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
    functionCalls = message.tool_calls.map((tc) => ({
      functionCall: {
        name: tc.name,
        args: tc.args
      }
    }));
  } else if (message.getType() === "tool" && message.name && message.content) {
    functionResponses = [
      {
        functionResponse: {
          name: message.name,
          response: message.content
        }
      }
    ];
  } else if (Array.isArray(message.content)) {
    messageParts = message.content.map((c4) => {
      if (c4.type === "text") {
        return {
          text: c4.text
        };
      } else if (c4.type === "executableCode") {
        return {
          executableCode: c4.executableCode
        };
      } else if (c4.type === "codeExecutionResult") {
        return {
          codeExecutionResult: c4.codeExecutionResult
        };
      }
      if (c4.type === "image_url") {
        if (!isMultimodalModel) {
          throw new Error(`This model does not support images`);
        }
        let source;
        if (typeof c4.image_url === "string") {
          source = c4.image_url;
        } else if (typeof c4.image_url === "object" && "url" in c4.image_url) {
          source = c4.image_url.url;
        } else {
          throw new Error("Please provide image as base64 encoded data URL");
        }
        const [dm, data] = source.split(",");
        if (!dm.startsWith("data:")) {
          throw new Error("Please provide image as base64 encoded data URL");
        }
        const [mimeType, encoding] = dm.replace(/^data:/, "").split(";");
        if (encoding !== "base64") {
          throw new Error("Please provide image as base64 encoded data URL");
        }
        return {
          inlineData: {
            data,
            mimeType
          }
        };
      } else if (c4.type === "media") {
        return messageContentMedia(c4);
      } else if (c4.type === "tool_use") {
        return {
          functionCall: {
            name: c4.name,
            args: c4.input
          }
        };
      }
      throw new Error(`Unknown content type ${c4.type}`);
    });
  }
  return [...messageParts, ...functionCalls, ...functionResponses];
}
function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false) {
  return messages.reduce((acc, message, index2) => {
    if (!isBaseMessage(message)) {
      throw new Error("Unsupported message input");
    }
    const author = getMessageAuthor(message);
    if (author === "system" && index2 !== 0) {
      throw new Error("System message should be the first one");
    }
    const role = convertAuthorToRole(author);
    const prevContent = acc.content[acc.content.length];
    if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) {
      throw new Error("Google Generative AI requires alternate messages between authors");
    }
    const parts = convertMessageContentToParts(message, isMultimodalModel);
    if (acc.mergeWithPreviousContent) {
      const prevContent2 = acc.content[acc.content.length - 1];
      if (!prevContent2) {
        throw new Error("There was a problem parsing your system message. Please try a prompt without one.");
      }
      prevContent2.parts.push(...parts);
      return {
        mergeWithPreviousContent: false,
        content: acc.content
      };
    }
    let actualRole = role;
    if (actualRole === "function" || actualRole === "system" && !convertSystemMessageToHumanContent) {
      actualRole = "user";
    }
    const content = {
      role: actualRole,
      parts
    };
    return {
      mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent,
      content: [...acc.content, content]
    };
  }, { content: [], mergeWithPreviousContent: false }).content;
}
function mapGenerateContentResultToChatResult(response, extra) {
  if (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) {
    return {
      generations: [],
      llmOutput: {
        filters: response.promptFeedback
      }
    };
  }
  const functionCalls = response.functionCalls();
  const [candidate] = response.candidates;
  const { content: candidateContent, ...generationInfo } = candidate;
  let content;
  if (candidateContent?.parts.length === 1 && candidateContent.parts[0].text) {
    content = candidateContent.parts[0].text;
  } else {
    content = candidateContent.parts.map((p3) => {
      if ("text" in p3) {
        return {
          type: "text",
          text: p3.text
        };
      } else if ("executableCode" in p3) {
        return {
          type: "executableCode",
          executableCode: p3.executableCode
        };
      } else if ("codeExecutionResult" in p3) {
        return {
          type: "codeExecutionResult",
          codeExecutionResult: p3.codeExecutionResult
        };
      }
      return p3;
    });
  }
  let text = "";
  if (typeof content === "string") {
    text = content;
  } else if ("text" in content[0]) {
    text = content[0].text;
  }
  const generation = {
    text,
    message: new AIMessage({
      content,
      tool_calls: functionCalls?.map((fc) => ({
        ...fc,
        type: "tool_call"
      })),
      additional_kwargs: {
        ...generationInfo
      },
      usage_metadata: extra?.usageMetadata
    }),
    generationInfo
  };
  return {
    generations: [generation]
  };
}
function convertResponseContentToChatGenerationChunk(response, extra) {
  if (!response.candidates || response.candidates.length === 0) {
    return null;
  }
  const functionCalls = response.functionCalls();
  const [candidate] = response.candidates;
  const { content: candidateContent, ...generationInfo } = candidate;
  let content;
  if (candidateContent?.parts && candidateContent.parts.every((p3) => "text" in p3)) {
    content = candidateContent.parts.map((p3) => p3.text).join("");
  } else if (candidateContent.parts) {
    content = candidateContent.parts.map((p3) => {
      if ("text" in p3) {
        return {
          type: "text",
          text: p3.text
        };
      } else if ("executableCode" in p3) {
        return {
          type: "executableCode",
          executableCode: p3.executableCode
        };
      } else if ("codeExecutionResult" in p3) {
        return {
          type: "codeExecutionResult",
          codeExecutionResult: p3.codeExecutionResult
        };
      }
      return p3;
    });
  }
  let text = "";
  if (content && typeof content === "string") {
    text = content;
  } else if (content && typeof content === "object" && "text" in content[0]) {
    text = content[0].text;
  }
  const toolCallChunks = [];
  if (functionCalls) {
    toolCallChunks.push(...functionCalls.map((fc) => ({
      ...fc,
      args: JSON.stringify(fc.args),
      index: extra.index,
      type: "tool_call_chunk"
    })));
  }
  return new ChatGenerationChunk({
    text,
    message: new AIMessageChunk({
      content: content || "",
      name: !candidateContent ? void 0 : candidateContent.role,
      tool_call_chunks: toolCallChunks,
      // Each chunk can have unique "generationInfo", and merging strategy is unclear,
      // so leave blank for now.
      additional_kwargs: {},
      usage_metadata: extra.usageMetadata
    }),
    generationInfo
  });
}
function convertToGenerativeAITools(tools) {
  if (tools.every((tool2) => "functionDeclarations" in tool2 && Array.isArray(tool2.functionDeclarations))) {
    return tools;
  }
  return [
    {
      functionDeclarations: tools.map((tool2) => {
        if (isLangChainTool(tool2)) {
          const jsonSchema = zodToGenerativeAIParameters(tool2.schema);
          return {
            name: tool2.name,
            description: tool2.description,
            parameters: jsonSchema
          };
        }
        if (isOpenAITool(tool2)) {
          return {
            name: tool2.function.name,
            description: tool2.function.description ?? `A function available to call.`,
            parameters: jsonSchemaToGeminiParameters(tool2.function.parameters)
          };
        }
        return tool2;
      })
    }
  ];
}

// node_modules/@langchain/google-genai/dist/output_parsers.js
init_output_parsers2();
var GoogleGenerativeAIToolsOutputParser = class extends BaseLLMOutputParser {
  static lc_name() {
    return "GoogleGenerativeAIToolsOutputParser";
  }
  constructor(params) {
    super(params);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "google_genai", "output_parsers"]
    });
    Object.defineProperty(this, "returnId", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "keyName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "returnSingle", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "zodSchema", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.keyName = params.keyName;
    this.returnSingle = params.returnSingle ?? this.returnSingle;
    this.zodSchema = params.zodSchema;
  }
  async _validateResult(result) {
    if (this.zodSchema === void 0) {
      return result;
    }
    const zodParsedResult = await this.zodSchema.safeParseAsync(result);
    if (zodParsedResult.success) {
      return zodParsedResult.data;
    } else {
      throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2));
    }
  }
  async parseResult(generations) {
    const tools = generations.flatMap((generation) => {
      const { message } = generation;
      if (!("tool_calls" in message) || !Array.isArray(message.tool_calls)) {
        return [];
      }
      return message.tool_calls;
    });
    if (tools[0] === void 0) {
      throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");
    }
    const [tool2] = tools;
    const validatedResult = await this._validateResult(tool2.args);
    return validatedResult;
  }
};

// node_modules/@langchain/google-genai/dist/utils/tools.js
init_base9();
function convertToolsToGenAI(tools, extra) {
  const genAITools = processTools(tools);
  const toolConfig = createToolConfig(genAITools, extra);
  return { tools: genAITools, toolConfig };
}
function processTools(tools) {
  let functionDeclarationTools = [];
  const genAITools = [];
  tools.forEach((tool2) => {
    if (isLangChainTool(tool2)) {
      const [convertedTool] = convertToGenerativeAITools([
        tool2
      ]);
      if (convertedTool.functionDeclarations) {
        functionDeclarationTools.push(...convertedTool.functionDeclarations);
      }
    } else if (isOpenAITool(tool2)) {
      const { functionDeclarations } = convertOpenAIToolToGenAI(tool2);
      if (functionDeclarations) {
        functionDeclarationTools.push(...functionDeclarations);
      } else {
        throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool");
      }
    } else {
      genAITools.push(tool2);
    }
  });
  const genAIFunctionDeclaration = genAITools.find((t3) => "functionDeclarations" in t3);
  if (genAIFunctionDeclaration) {
    return genAITools.map((tool2) => {
      if (functionDeclarationTools?.length > 0 && "functionDeclarations" in tool2) {
        const newTool = {
          functionDeclarations: [
            ...tool2.functionDeclarations || [],
            ...functionDeclarationTools
          ]
        };
        functionDeclarationTools = [];
        return newTool;
      }
      return tool2;
    });
  }
  return [
    ...genAITools,
    ...functionDeclarationTools.length > 0 ? [
      {
        functionDeclarations: functionDeclarationTools
      }
    ] : []
  ];
}
function convertOpenAIToolToGenAI(tool2) {
  return {
    functionDeclarations: [
      {
        name: tool2.function.name,
        description: tool2.function.description,
        parameters: removeAdditionalProperties(tool2.function.parameters)
      }
    ]
  };
}
function createToolConfig(genAITools, extra) {
  if (!genAITools.length || !extra)
    return void 0;
  const { toolChoice, allowedFunctionNames } = extra;
  const modeMap = {
    any: FunctionCallingMode.ANY,
    auto: FunctionCallingMode.AUTO,
    none: FunctionCallingMode.NONE
  };
  if (toolChoice && ["any", "auto", "none"].includes(toolChoice)) {
    return {
      functionCallingConfig: {
        mode: modeMap[toolChoice] ?? "MODE_UNSPECIFIED",
        allowedFunctionNames
      }
    };
  }
  if (typeof toolChoice === "string" || allowedFunctionNames) {
    return {
      functionCallingConfig: {
        mode: FunctionCallingMode.ANY,
        allowedFunctionNames: [
          ...allowedFunctionNames ?? [],
          ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []
        ]
      }
    };
  }
  return void 0;
}

// node_modules/@langchain/google-genai/dist/chat_models.js
var ChatGoogleGenerativeAI = class extends BaseChatModel {
  static lc_name() {
    return "ChatGoogleGenerativeAI";
  }
  get lc_secrets() {
    return {
      apiKey: "GOOGLE_API_KEY"
    };
  }
  get lc_aliases() {
    return {
      apiKey: "google_api_key"
    };
  }
  get _isMultimodalModel() {
    return this.model.includes("vision") || this.model.startsWith("gemini-1.5") || this.model.startsWith("gemini-2");
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "chat_models", "google_genai"]
    });
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "gemini-pro"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "gemini-pro"
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "maxOutputTokens", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "topP", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "topK", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stopSequences", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: []
    });
    Object.defineProperty(this, "safetySettings", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "streamUsage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "convertSystemMessageToHumanContent", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.modelName = fields?.model?.replace(/^models\//, "") ?? fields?.modelName?.replace(/^models\//, "") ?? this.model;
    this.model = this.modelName;
    this.maxOutputTokens = fields?.maxOutputTokens ?? this.maxOutputTokens;
    if (this.maxOutputTokens && this.maxOutputTokens < 0) {
      throw new Error("`maxOutputTokens` must be a positive integer");
    }
    this.temperature = fields?.temperature ?? this.temperature;
    if (this.temperature && (this.temperature < 0 || this.temperature > 1)) {
      throw new Error("`temperature` must be in the range of [0.0,1.0]");
    }
    this.topP = fields?.topP ?? this.topP;
    if (this.topP && this.topP < 0) {
      throw new Error("`topP` must be a positive integer");
    }
    if (this.topP && this.topP > 1) {
      throw new Error("`topP` must be below 1.");
    }
    this.topK = fields?.topK ?? this.topK;
    if (this.topK && this.topK < 0) {
      throw new Error("`topK` must be a positive integer");
    }
    this.stopSequences = fields?.stopSequences ?? this.stopSequences;
    this.apiKey = fields?.apiKey ?? getEnvironmentVariable2("GOOGLE_API_KEY");
    if (!this.apiKey) {
      throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");
    }
    this.safetySettings = fields?.safetySettings ?? this.safetySettings;
    if (this.safetySettings && this.safetySettings.length > 0) {
      const safetySettingsSet = new Set(this.safetySettings.map((s4) => s4.category));
      if (safetySettingsSet.size !== this.safetySettings.length) {
        throw new Error("The categories in `safetySettings` array must be unique");
      }
    }
    this.streaming = fields?.streaming ?? this.streaming;
    this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({
      model: this.model,
      safetySettings: this.safetySettings,
      generationConfig: {
        candidateCount: 1,
        stopSequences: this.stopSequences,
        maxOutputTokens: this.maxOutputTokens,
        temperature: this.temperature,
        topP: this.topP,
        topK: this.topK,
        ...fields?.json ? { responseMimeType: "application/json" } : {}
      }
    }, {
      apiVersion: fields?.apiVersion,
      baseUrl: fields?.baseUrl
    });
    this.streamUsage = fields?.streamUsage ?? this.streamUsage;
  }
  useCachedContent(cachedContent, modelParams, requestOptions) {
    if (!this.apiKey)
      return;
    this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions);
  }
  get useSystemInstruction() {
    return typeof this.convertSystemMessageToHumanContent === "boolean" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction;
  }
  get computeUseSystemInstruction() {
    if (this.modelName === "gemini-1.0-pro-001") {
      return false;
    } else if (this.modelName.startsWith("gemini-pro-vision")) {
      return false;
    } else if (this.modelName.startsWith("gemini-1.0-pro-vision")) {
      return false;
    } else if (this.modelName === "gemini-pro") {
      return false;
    }
    return true;
  }
  getLsParams(options) {
    return {
      ls_provider: "google_genai",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: this.client.generationConfig.temperature,
      ls_max_tokens: this.client.generationConfig.maxOutputTokens,
      ls_stop: options.stop
    };
  }
  _combineLLMOutput() {
    return [];
  }
  _llmType() {
    return "googlegenerativeai";
  }
  bindTools(tools, kwargs) {
    return this.bind({ tools: convertToolsToGenAI(tools)?.tools, ...kwargs });
  }
  invocationParams(options) {
    const toolsAndConfig = options?.tools?.length ? convertToolsToGenAI(options.tools, {
      toolChoice: options.tool_choice,
      allowedFunctionNames: options.allowedFunctionNames
    }) : void 0;
    return {
      ...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {},
      ...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {}
    };
  }
  async _generate(messages, options, runManager) {
    const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
    let actualPrompt = prompt;
    if (prompt[0].role === "system") {
      const [systemInstruction] = prompt;
      this.client.systemInstruction = systemInstruction;
      actualPrompt = prompt.slice(1);
    }
    const parameters = this.invocationParams(options);
    if (this.streaming) {
      const tokenUsage = {};
      const stream = this._streamResponseChunks(messages, options, runManager);
      const finalChunks = {};
      for await (const chunk of stream) {
        const index2 = chunk.generationInfo?.completion ?? 0;
        if (finalChunks[index2] === void 0) {
          finalChunks[index2] = chunk;
        } else {
          finalChunks[index2] = finalChunks[index2].concat(chunk);
        }
      }
      const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_2, value]) => value);
      return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
    }
    const res = await this.completionWithRetry({
      ...parameters,
      contents: actualPrompt
    });
    let usageMetadata;
    if ("usageMetadata" in res.response) {
      const genAIUsageMetadata = res.response.usageMetadata;
      usageMetadata = {
        input_tokens: genAIUsageMetadata.promptTokenCount ?? 0,
        output_tokens: genAIUsageMetadata.candidatesTokenCount ?? 0,
        total_tokens: genAIUsageMetadata.totalTokenCount ?? 0
      };
    }
    const generationResult = mapGenerateContentResultToChatResult(res.response, {
      usageMetadata
    });
    await runManager?.handleLLMNewToken(generationResult.generations[0].text ?? "");
    return generationResult;
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction);
    let actualPrompt = prompt;
    if (prompt[0].role === "system") {
      const [systemInstruction] = prompt;
      this.client.systemInstruction = systemInstruction;
      actualPrompt = prompt.slice(1);
    }
    const parameters = this.invocationParams(options);
    const request = {
      ...parameters,
      contents: actualPrompt
    };
    const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {
      const { stream: stream2 } = await this.client.generateContentStream(request);
      return stream2;
    });
    let usageMetadata;
    let index2 = 0;
    for await (const response of stream) {
      if ("usageMetadata" in response && this.streamUsage !== false && options.streamUsage !== false) {
        const genAIUsageMetadata = response.usageMetadata;
        if (!usageMetadata) {
          usageMetadata = {
            input_tokens: genAIUsageMetadata.promptTokenCount,
            output_tokens: genAIUsageMetadata.candidatesTokenCount,
            total_tokens: genAIUsageMetadata.totalTokenCount
          };
        } else {
          const outputTokenDiff = genAIUsageMetadata.candidatesTokenCount - usageMetadata.output_tokens;
          usageMetadata = {
            input_tokens: 0,
            output_tokens: outputTokenDiff,
            total_tokens: outputTokenDiff
          };
        }
      }
      const chunk = convertResponseContentToChatGenerationChunk(response, {
        usageMetadata,
        index: index2
      });
      index2 += 1;
      if (!chunk) {
        continue;
      }
      yield chunk;
      await runManager?.handleLLMNewToken(chunk.text ?? "");
    }
  }
  async completionWithRetry(request, options) {
    return this.caller.callWithOptions({ signal: options?.signal }, async () => {
      try {
        return await this.client.generateContent(request);
      } catch (e3) {
        if (e3.message?.includes("400 Bad Request")) {
          e3.status = 400;
        }
        throw e3;
      }
    });
  }
  withStructuredOutput(outputSchema, config) {
    const schema = outputSchema;
    const name = config?.name;
    const method = config?.method;
    const includeRaw = config?.includeRaw;
    if (method === "jsonMode") {
      throw new Error(`ChatGoogleGenerativeAI only supports "functionCalling" as a method.`);
    }
    let functionName = name ?? "extract";
    let outputParser;
    let tools;
    if (isZodSchema(schema)) {
      const jsonSchema = zodToGenerativeAIParameters(schema);
      tools = [
        {
          functionDeclarations: [
            {
              name: functionName,
              description: jsonSchema.description ?? "A function available to call.",
              parameters: jsonSchema
            }
          ]
        }
      ];
      outputParser = new GoogleGenerativeAIToolsOutputParser({
        returnSingle: true,
        keyName: functionName,
        zodSchema: schema
      });
    } else {
      let geminiFunctionDefinition;
      if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
        geminiFunctionDefinition = schema;
        functionName = schema.name;
      } else {
        geminiFunctionDefinition = {
          name: functionName,
          description: schema.description ?? "",
          parameters: schema
        };
      }
      tools = [
        {
          functionDeclarations: [geminiFunctionDefinition]
        }
      ];
      outputParser = new GoogleGenerativeAIToolsOutputParser({
        returnSingle: true,
        keyName: functionName
      });
    }
    const llm = this.bind({
      tools,
      tool_choice: functionName
    });
    if (!includeRaw) {
      return llm.pipe(outputParser).withConfig({
        runName: "ChatGoogleGenerativeAIStructuredOutput"
      });
    }
    const parserAssign = RunnablePassthrough.assign({
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parsed: (input, config2) => outputParser.invoke(input.raw, config2)
    });
    const parserNone = RunnablePassthrough.assign({
      parsed: () => null
    });
    const parsedWithFallback = parserAssign.withFallbacks({
      fallbacks: [parserNone]
    });
    return RunnableSequence.from([
      {
        raw: llm
      },
      parsedWithFallback
    ]).withConfig({
      runName: "StructuredOutputRunnable"
    });
  }
};

// node_modules/@langchain/google-genai/dist/embeddings.js
var GoogleGenerativeAIEmbeddings = class extends Embeddings {
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "embedding-001"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "embedding-001"
    });
    Object.defineProperty(this, "taskType", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "title", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stripNewLines", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "maxBatchSize", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 100
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.modelName = fields?.model?.replace(/^models\//, "") ?? fields?.modelName?.replace(/^models\//, "") ?? this.modelName;
    this.model = this.modelName;
    this.taskType = fields?.taskType ?? this.taskType;
    this.title = fields?.title ?? this.title;
    if (this.title && this.taskType !== "RETRIEVAL_DOCUMENT") {
      throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT");
    }
    this.apiKey = fields?.apiKey ?? getEnvironmentVariable2("GOOGLE_API_KEY");
    if (!this.apiKey) {
      throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor");
    }
    this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({
      model: this.model
    });
  }
  _convertToContent(text) {
    const cleanedText = this.stripNewLines ? text.replace(/\n/g, " ") : text;
    return {
      content: { role: "user", parts: [{ text: cleanedText }] },
      taskType: this.taskType,
      title: this.title
    };
  }
  async _embedQueryContent(text) {
    const req = this._convertToContent(text);
    const res = await this.client.embedContent(req);
    return res.embedding.values ?? [];
  }
  async _embedDocumentsContent(documents) {
    const batchEmbedChunks = chunkArray(documents, this.maxBatchSize);
    const batchEmbedRequests = batchEmbedChunks.map((chunk) => ({
      requests: chunk.map((doc) => this._convertToContent(doc))
    }));
    const responses = await Promise.allSettled(batchEmbedRequests.map((req) => this.client.batchEmbedContents(req)));
    const embeddings = responses.flatMap((res, idx) => {
      if (res.status === "fulfilled") {
        return res.value.embeddings.map((e3) => e3.values || []);
      } else {
        return Array(batchEmbedChunks[idx].length).fill([]);
      }
    });
    return embeddings;
  }
  /**
   * Method that takes a document as input and returns a promise that
   * resolves to an embedding for the document. It calls the _embedText
   * method with the document as the input.
   * @param document Document for which to generate an embedding.
   * @returns Promise that resolves to an embedding for the input document.
   */
  embedQuery(document2) {
    return this.caller.call(this._embedQueryContent.bind(this), document2);
  }
  /**
   * Method that takes an array of documents as input and returns a promise
   * that resolves to a 2D array of embeddings for each document. It calls
   * the _embedText method for each document in the array.
   * @param documents Array of documents for which to generate embeddings.
   * @returns Promise that resolves to a 2D array of embeddings for each input document.
   */
  embedDocuments(documents) {
    return this.caller.call(this._embedDocumentsContent.bind(this), documents);
  }
};

// node_modules/whatwg-fetch/fetch.js
var g3 = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef
typeof window !== "undefined" && window || {};
var support = {
  searchParams: "URLSearchParams" in g3,
  iterable: "Symbol" in g3 && "iterator" in Symbol,
  blob: "FileReader" in g3 && "Blob" in g3 && function() {
    try {
      new Blob();
      return true;
    } catch (e3) {
      return false;
    }
  }(),
  formData: "FormData" in g3,
  arrayBuffer: "ArrayBuffer" in g3
};
function isDataView(obj) {
  return obj && DataView.prototype.isPrototypeOf(obj);
}
if (support.arrayBuffer) {
  viewClasses = [
    "[object Int8Array]",
    "[object Uint8Array]",
    "[object Uint8ClampedArray]",
    "[object Int16Array]",
    "[object Uint16Array]",
    "[object Int32Array]",
    "[object Uint32Array]",
    "[object Float32Array]",
    "[object Float64Array]"
  ];
  isArrayBufferView = ArrayBuffer.isView || function(obj) {
    return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
  };
}
var viewClasses;
var isArrayBufferView;
function normalizeName(name) {
  if (typeof name !== "string") {
    name = String(name);
  }
  if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") {
    throw new TypeError('Invalid character in header field name: "' + name + '"');
  }
  return name.toLowerCase();
}
function normalizeValue(value) {
  if (typeof value !== "string") {
    value = String(value);
  }
  return value;
}
function iteratorFor(items) {
  var iterator = {
    next: function() {
      var value = items.shift();
      return { done: value === void 0, value };
    }
  };
  if (support.iterable) {
    iterator[Symbol.iterator] = function() {
      return iterator;
    };
  }
  return iterator;
}
function Headers2(headers) {
  this.map = {};
  if (headers instanceof Headers2) {
    headers.forEach(function(value, name) {
      this.append(name, value);
    }, this);
  } else if (Array.isArray(headers)) {
    headers.forEach(function(header) {
      if (header.length != 2) {
        throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length);
      }
      this.append(header[0], header[1]);
    }, this);
  } else if (headers) {
    Object.getOwnPropertyNames(headers).forEach(function(name) {
      this.append(name, headers[name]);
    }, this);
  }
}
Headers2.prototype.append = function(name, value) {
  name = normalizeName(name);
  value = normalizeValue(value);
  var oldValue = this.map[name];
  this.map[name] = oldValue ? oldValue + ", " + value : value;
};
Headers2.prototype["delete"] = function(name) {
  delete this.map[normalizeName(name)];
};
Headers2.prototype.get = function(name) {
  name = normalizeName(name);
  return this.has(name) ? this.map[name] : null;
};
Headers2.prototype.has = function(name) {
  return this.map.hasOwnProperty(normalizeName(name));
};
Headers2.prototype.set = function(name, value) {
  this.map[normalizeName(name)] = normalizeValue(value);
};
Headers2.prototype.forEach = function(callback, thisArg) {
  for (var name in this.map) {
    if (this.map.hasOwnProperty(name)) {
      callback.call(thisArg, this.map[name], name, this);
    }
  }
};
Headers2.prototype.keys = function() {
  var items = [];
  this.forEach(function(value, name) {
    items.push(name);
  });
  return iteratorFor(items);
};
Headers2.prototype.values = function() {
  var items = [];
  this.forEach(function(value) {
    items.push(value);
  });
  return iteratorFor(items);
};
Headers2.prototype.entries = function() {
  var items = [];
  this.forEach(function(value, name) {
    items.push([name, value]);
  });
  return iteratorFor(items);
};
if (support.iterable) {
  Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries;
}
function consumed(body) {
  if (body._noBody)
    return;
  if (body.bodyUsed) {
    return Promise.reject(new TypeError("Already read"));
  }
  body.bodyUsed = true;
}
function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result);
    };
    reader.onerror = function() {
      reject(reader.error);
    };
  });
}
function readBlobAsArrayBuffer(blob) {
  var reader = new FileReader();
  var promise = fileReaderReady(reader);
  reader.readAsArrayBuffer(blob);
  return promise;
}
function readBlobAsText(blob) {
  var reader = new FileReader();
  var promise = fileReaderReady(reader);
  var match2 = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
  var encoding = match2 ? match2[1] : "utf-8";
  reader.readAsText(blob, encoding);
  return promise;
}
function readArrayBufferAsText(buf) {
  var view = new Uint8Array(buf);
  var chars = new Array(view.length);
  for (var i3 = 0; i3 < view.length; i3++) {
    chars[i3] = String.fromCharCode(view[i3]);
  }
  return chars.join("");
}
function bufferClone(buf) {
  if (buf.slice) {
    return buf.slice(0);
  } else {
    var view = new Uint8Array(buf.byteLength);
    view.set(new Uint8Array(buf));
    return view.buffer;
  }
}
function Body() {
  this.bodyUsed = false;
  this._initBody = function(body) {
    this.bodyUsed = this.bodyUsed;
    this._bodyInit = body;
    if (!body) {
      this._noBody = true;
      this._bodyText = "";
    } else if (typeof body === "string") {
      this._bodyText = body;
    } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
      this._bodyBlob = body;
    } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
      this._bodyFormData = body;
    } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
      this._bodyText = body.toString();
    } else if (support.arrayBuffer && support.blob && isDataView(body)) {
      this._bodyArrayBuffer = bufferClone(body.buffer);
      this._bodyInit = new Blob([this._bodyArrayBuffer]);
    } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
      this._bodyArrayBuffer = bufferClone(body);
    } else {
      this._bodyText = body = Object.prototype.toString.call(body);
    }
    if (!this.headers.get("content-type")) {
      if (typeof body === "string") {
        this.headers.set("content-type", "text/plain;charset=UTF-8");
      } else if (this._bodyBlob && this._bodyBlob.type) {
        this.headers.set("content-type", this._bodyBlob.type);
      } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
        this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
      }
    }
  };
  if (support.blob) {
    this.blob = function() {
      var rejected = consumed(this);
      if (rejected) {
        return rejected;
      }
      if (this._bodyBlob) {
        return Promise.resolve(this._bodyBlob);
      } else if (this._bodyArrayBuffer) {
        return Promise.resolve(new Blob([this._bodyArrayBuffer]));
      } else if (this._bodyFormData) {
        throw new Error("could not read FormData body as blob");
      } else {
        return Promise.resolve(new Blob([this._bodyText]));
      }
    };
  }
  this.arrayBuffer = function() {
    if (this._bodyArrayBuffer) {
      var isConsumed = consumed(this);
      if (isConsumed) {
        return isConsumed;
      } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
        return Promise.resolve(
          this._bodyArrayBuffer.buffer.slice(
            this._bodyArrayBuffer.byteOffset,
            this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
          )
        );
      } else {
        return Promise.resolve(this._bodyArrayBuffer);
      }
    } else if (support.blob) {
      return this.blob().then(readBlobAsArrayBuffer);
    } else {
      throw new Error("could not read as ArrayBuffer");
    }
  };
  this.text = function() {
    var rejected = consumed(this);
    if (rejected) {
      return rejected;
    }
    if (this._bodyBlob) {
      return readBlobAsText(this._bodyBlob);
    } else if (this._bodyArrayBuffer) {
      return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
    } else if (this._bodyFormData) {
      throw new Error("could not read FormData body as text");
    } else {
      return Promise.resolve(this._bodyText);
    }
  };
  if (support.formData) {
    this.formData = function() {
      return this.text().then(decode);
    };
  }
  this.json = function() {
    return this.text().then(JSON.parse);
  };
  return this;
}
var methods = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
function normalizeMethod(method) {
  var upcased = method.toUpperCase();
  return methods.indexOf(upcased) > -1 ? upcased : method;
}
function Request2(input, options) {
  if (!(this instanceof Request2)) {
    throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
  }
  options = options || {};
  var body = options.body;
  if (input instanceof Request2) {
    if (input.bodyUsed) {
      throw new TypeError("Already read");
    }
    this.url = input.url;
    this.credentials = input.credentials;
    if (!options.headers) {
      this.headers = new Headers2(input.headers);
    }
    this.method = input.method;
    this.mode = input.mode;
    this.signal = input.signal;
    if (!body && input._bodyInit != null) {
      body = input._bodyInit;
      input.bodyUsed = true;
    }
  } else {
    this.url = String(input);
  }
  this.credentials = options.credentials || this.credentials || "same-origin";
  if (options.headers || !this.headers) {
    this.headers = new Headers2(options.headers);
  }
  this.method = normalizeMethod(options.method || this.method || "GET");
  this.mode = options.mode || this.mode || null;
  this.signal = options.signal || this.signal || function() {
    if ("AbortController" in g3) {
      var ctrl = new AbortController();
      return ctrl.signal;
    }
  }();
  this.referrer = null;
  if ((this.method === "GET" || this.method === "HEAD") && body) {
    throw new TypeError("Body not allowed for GET or HEAD requests");
  }
  this._initBody(body);
  if (this.method === "GET" || this.method === "HEAD") {
    if (options.cache === "no-store" || options.cache === "no-cache") {
      var reParamSearch = /([?&])_=[^&]*/;
      if (reParamSearch.test(this.url)) {
        this.url = this.url.replace(reParamSearch, "$1_=" + new Date().getTime());
      } else {
        var reQueryString = /\?/;
        this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + new Date().getTime();
      }
    }
  }
}
Request2.prototype.clone = function() {
  return new Request2(this, { body: this._bodyInit });
};
function decode(body) {
  var form = new FormData();
  body.trim().split("&").forEach(function(bytes) {
    if (bytes) {
      var split = bytes.split("=");
      var name = split.shift().replace(/\+/g, " ");
      var value = split.join("=").replace(/\+/g, " ");
      form.append(decodeURIComponent(name), decodeURIComponent(value));
    }
  });
  return form;
}
function parseHeaders(rawHeaders) {
  var headers = new Headers2();
  var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " ");
  preProcessedHeaders.split("\r").map(function(header) {
    return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header;
  }).forEach(function(line) {
    var parts = line.split(":");
    var key = parts.shift().trim();
    if (key) {
      var value = parts.join(":").trim();
      try {
        headers.append(key, value);
      } catch (error) {
        console.warn("Response " + error.message);
      }
    }
  });
  return headers;
}
Body.call(Request2.prototype);
function Response2(bodyInit, options) {
  if (!(this instanceof Response2)) {
    throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
  }
  if (!options) {
    options = {};
  }
  this.type = "default";
  this.status = options.status === void 0 ? 200 : options.status;
  if (this.status < 200 || this.status > 599) {
    throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
  }
  this.ok = this.status >= 200 && this.status < 300;
  this.statusText = options.statusText === void 0 ? "" : "" + options.statusText;
  this.headers = new Headers2(options.headers);
  this.url = options.url || "";
  this._initBody(bodyInit);
}
Body.call(Response2.prototype);
Response2.prototype.clone = function() {
  return new Response2(this._bodyInit, {
    status: this.status,
    statusText: this.statusText,
    headers: new Headers2(this.headers),
    url: this.url
  });
};
Response2.error = function() {
  var response = new Response2(null, { status: 200, statusText: "" });
  response.ok = false;
  response.status = 0;
  response.type = "error";
  return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response2.redirect = function(url, status) {
  if (redirectStatuses.indexOf(status) === -1) {
    throw new RangeError("Invalid status code");
  }
  return new Response2(null, { status, headers: { location: url } });
};
var DOMException2 = g3.DOMException;
try {
  new DOMException2();
} catch (err) {
  DOMException2 = function(message, name) {
    this.message = message;
    this.name = name;
    var error = Error(message);
    this.stack = error.stack;
  };
  DOMException2.prototype = Object.create(Error.prototype);
  DOMException2.prototype.constructor = DOMException2;
}
function fetch2(input, init) {
  return new Promise(function(resolve, reject) {
    var request = new Request2(input, init);
    if (request.signal && request.signal.aborted) {
      return reject(new DOMException2("Aborted", "AbortError"));
    }
    var xhr = new XMLHttpRequest();
    function abortXhr() {
      xhr.abort();
    }
    xhr.onload = function() {
      var options = {
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders() || "")
      };
      if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) {
        options.status = 200;
      } else {
        options.status = xhr.status;
      }
      options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL");
      var body = "response" in xhr ? xhr.response : xhr.responseText;
      setTimeout(function() {
        resolve(new Response2(body, options));
      }, 0);
    };
    xhr.onerror = function() {
      setTimeout(function() {
        reject(new TypeError("Network request failed"));
      }, 0);
    };
    xhr.ontimeout = function() {
      setTimeout(function() {
        reject(new TypeError("Network request timed out"));
      }, 0);
    };
    xhr.onabort = function() {
      setTimeout(function() {
        reject(new DOMException2("Aborted", "AbortError"));
      }, 0);
    };
    function fixUrl(url) {
      try {
        return url === "" && g3.location.href ? g3.location.href : url;
      } catch (e3) {
        return url;
      }
    }
    xhr.open(request.method, fixUrl(request.url), true);
    if (request.credentials === "include") {
      xhr.withCredentials = true;
    } else if (request.credentials === "omit") {
      xhr.withCredentials = false;
    }
    if ("responseType" in xhr) {
      if (support.blob) {
        xhr.responseType = "blob";
      } else if (support.arrayBuffer) {
        xhr.responseType = "arraybuffer";
      }
    }
    if (init && typeof init.headers === "object" && !(init.headers instanceof Headers2 || g3.Headers && init.headers instanceof g3.Headers)) {
      var names = [];
      Object.getOwnPropertyNames(init.headers).forEach(function(name) {
        names.push(normalizeName(name));
        xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
      });
      request.headers.forEach(function(value, name) {
        if (names.indexOf(name) === -1) {
          xhr.setRequestHeader(name, value);
        }
      });
    } else {
      request.headers.forEach(function(value, name) {
        xhr.setRequestHeader(name, value);
      });
    }
    if (request.signal) {
      request.signal.addEventListener("abort", abortXhr);
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          request.signal.removeEventListener("abort", abortXhr);
        }
      };
    }
    xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit);
  });
}
fetch2.polyfill = true;
if (!g3.fetch) {
  g3.fetch = fetch2;
  g3.Headers = Headers2;
  g3.Request = Request2;
  g3.Response = Response2;
}

// node_modules/ollama/dist/shared/ollama.133b951a.mjs
var version = "0.5.9";
var __defProp$1 = Object.defineProperty;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField$1 = (obj, key, value) => {
  __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var ResponseError = class extends Error {
  constructor(error, status_code) {
    super(error);
    this.error = error;
    this.status_code = status_code;
    this.name = "ResponseError";
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ResponseError);
    }
  }
};
var AbortableAsyncIterator = class {
  constructor(abortController, itr, doneCallback) {
    __publicField$1(this, "abortController");
    __publicField$1(this, "itr");
    __publicField$1(this, "doneCallback");
    this.abortController = abortController;
    this.itr = itr;
    this.doneCallback = doneCallback;
  }
  abort() {
    this.abortController.abort();
  }
  async *[Symbol.asyncIterator]() {
    for await (const message of this.itr) {
      if ("error" in message) {
        throw new Error(message.error);
      }
      yield message;
      if (message.done || message.status === "success") {
        this.doneCallback();
        return;
      }
    }
    throw new Error("Did not receive done or success response in stream.");
  }
};
var checkOk = async (response) => {
  if (response.ok) {
    return;
  }
  let message = `Error ${response.status}: ${response.statusText}`;
  let errorData = null;
  if (response.headers.get("content-type")?.includes("application/json")) {
    try {
      errorData = await response.json();
      message = errorData.error || message;
    } catch (error) {
      console.log("Failed to parse error response as JSON");
    }
  } else {
    try {
      console.log("Getting text from response");
      const textResponse = await response.text();
      message = textResponse || message;
    } catch (error) {
      console.log("Failed to get text from error response");
    }
  }
  throw new ResponseError(message, response.status);
};
function getPlatform() {
  if (typeof window !== "undefined" && window.navigator) {
    return `${window.navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`;
  } else if (typeof process !== "undefined") {
    return `${process.arch} ${process.platform} Node.js/${process.version}`;
  }
  return "";
}
var fetchWithHeaders = async (fetch6, url, options = {}) => {
  const defaultHeaders = {
    "Content-Type": "application/json",
    Accept: "application/json",
    "User-Agent": `ollama-js/${version} (${getPlatform()})`
  };
  if (!options.headers) {
    options.headers = {};
  }
  options.headers = {
    ...defaultHeaders,
    ...options.headers
  };
  return fetch6(url, options);
};
var get2 = async (fetch6, host) => {
  const response = await fetchWithHeaders(fetch6, host);
  await checkOk(response);
  return response;
};
var post = async (fetch6, host, data, options) => {
  const isRecord = (input) => {
    return input !== null && typeof input === "object" && !Array.isArray(input);
  };
  const formattedData = isRecord(data) ? JSON.stringify(data) : data;
  const response = await fetchWithHeaders(fetch6, host, {
    method: "POST",
    body: formattedData,
    signal: options?.signal,
    headers: options?.headers
  });
  await checkOk(response);
  return response;
};
var del = async (fetch6, host, data) => {
  const response = await fetchWithHeaders(fetch6, host, {
    method: "DELETE",
    body: JSON.stringify(data)
  });
  await checkOk(response);
  return response;
};
var parseJSON = async function* (itr) {
  const decoder = new TextDecoder("utf-8");
  let buffer = "";
  const reader = itr.getReader();
  while (true) {
    const { done, value: chunk } = await reader.read();
    if (done) {
      break;
    }
    buffer += decoder.decode(chunk);
    const parts = buffer.split("\n");
    buffer = parts.pop() ?? "";
    for (const part of parts) {
      try {
        yield JSON.parse(part);
      } catch (error) {
        console.warn("invalid json: ", part);
      }
    }
  }
  for (const part of buffer.split("\n").filter((p3) => p3 !== "")) {
    try {
      yield JSON.parse(part);
    } catch (error) {
      console.warn("invalid json: ", part);
    }
  }
};
var formatHost = (host) => {
  if (!host) {
    return "http://127.0.0.1:11434";
  }
  let isExplicitProtocol = host.includes("://");
  if (host.startsWith(":")) {
    host = `http://127.0.0.1${host}`;
    isExplicitProtocol = true;
  }
  if (!isExplicitProtocol) {
    host = `http://${host}`;
  }
  const url = new URL(host);
  let port = url.port;
  if (!port) {
    if (!isExplicitProtocol) {
      port = "11434";
    } else {
      port = url.protocol === "https:" ? "443" : "80";
    }
  }
  let formattedHost = `${url.protocol}//${url.hostname}:${port}${url.pathname}`;
  if (formattedHost.endsWith("/")) {
    formattedHost = formattedHost.slice(0, -1);
  }
  return formattedHost;
};
var __defProp3 = Object.defineProperty;
var __defNormalProp3 = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField3 = (obj, key, value) => {
  __defNormalProp3(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var Ollama$1 = class Ollama {
  constructor(config) {
    __publicField3(this, "config");
    __publicField3(this, "fetch");
    __publicField3(this, "ongoingStreamedRequests", []);
    this.config = {
      host: ""
    };
    if (!config?.proxy) {
      this.config.host = formatHost(config?.host ?? "http://127.0.0.1:11434");
    }
    this.fetch = fetch;
    if (config?.fetch != null) {
      this.fetch = config.fetch;
    }
  }
  // Abort any ongoing streamed requests to Ollama
  abort() {
    for (const request of this.ongoingStreamedRequests) {
      request.abort();
    }
    this.ongoingStreamedRequests.length = 0;
  }
  /**
   * Processes a request to the Ollama server. If the request is streamable, it will return a
   * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response
   * object.
   * @param endpoint {string} - The endpoint to send the request to.
   * @param request {object} - The request object to send to the endpoint.
   * @protected {T | AbortableAsyncIterator<T>} - The response object or a AbortableAsyncIterator that yields
   * response messages.
   * @throws {Error} - If the response body is missing or if the response is an error.
   * @returns {Promise<T | AbortableAsyncIterator<T>>} - The response object or a AbortableAsyncIterator that yields the streamed response.
   */
  async processStreamableRequest(endpoint, request) {
    request.stream = request.stream ?? false;
    const host = `${this.config.host}/api/${endpoint}`;
    if (request.stream) {
      const abortController = new AbortController();
      const response2 = await post(this.fetch, host, request, {
        signal: abortController.signal,
        headers: this.config.headers
      });
      if (!response2.body) {
        throw new Error("Missing body");
      }
      const itr = parseJSON(response2.body);
      const abortableAsyncIterator = new AbortableAsyncIterator(
        abortController,
        itr,
        () => {
          const i3 = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);
          if (i3 > -1) {
            this.ongoingStreamedRequests.splice(i3, 1);
          }
        }
      );
      this.ongoingStreamedRequests.push(abortableAsyncIterator);
      return abortableAsyncIterator;
    }
    const response = await post(this.fetch, host, request, {
      headers: this.config.headers
    });
    return await response.json();
  }
  /**
  * Encodes an image to base64 if it is a Uint8Array.
  * @param image {Uint8Array | string} - The image to encode.
  * @returns {Promise<string>} - The base64 encoded image.
  */
  async encodeImage(image) {
    if (typeof image !== "string") {
      const uint8Array = new Uint8Array(image);
      let byteString = "";
      const len = uint8Array.byteLength;
      for (let i3 = 0; i3 < len; i3++) {
        byteString += String.fromCharCode(uint8Array[i3]);
      }
      return btoa(byteString);
    }
    return image;
  }
  /**
   * Generates a response from a text prompt.
   * @param request {GenerateRequest} - The request object.
   * @returns {Promise<GenerateResponse | AbortableAsyncIterator<GenerateResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async generate(request) {
    if (request.images) {
      request.images = await Promise.all(request.images.map(this.encodeImage.bind(this)));
    }
    return this.processStreamableRequest("generate", request);
  }
  /**
   * Chats with the model. The request object can contain messages with images that are either
   * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the
   * request.
   * @param request {ChatRequest} - The request object.
   * @returns {Promise<ChatResponse | AbortableAsyncIterator<ChatResponse>>} - The response object or an
   * AbortableAsyncIterator that yields response messages.
   */
  async chat(request) {
    if (request.messages) {
      for (const message of request.messages) {
        if (message.images) {
          message.images = await Promise.all(
            message.images.map(this.encodeImage.bind(this))
          );
        }
      }
    }
    return this.processStreamableRequest("chat", request);
  }
  /**
   * Creates a new model from a stream of data.
   * @param request {CreateRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or a stream of progress responses.
   */
  async create(request) {
    return this.processStreamableRequest("create", {
      name: request.model,
      stream: request.stream,
      modelfile: request.modelfile,
      quantize: request.quantize
    });
  }
  /**
   * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the
   * response should be streamed.
   * @param request {PullRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async pull(request) {
    return this.processStreamableRequest("pull", {
      name: request.model,
      stream: request.stream,
      insecure: request.insecure
    });
  }
  /**
   * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the
   * response should be streamed.
   * @param request {PushRequest} - The request object.
   * @returns {Promise<ProgressResponse | AbortableAsyncIterator<ProgressResponse>>} - The response object or
   * an AbortableAsyncIterator that yields response messages.
   */
  async push(request) {
    return this.processStreamableRequest("push", {
      name: request.model,
      stream: request.stream,
      insecure: request.insecure
    });
  }
  /**
   * Deletes a model from the server. The request object should contain the name of the model to
   * delete.
   * @param request {DeleteRequest} - The request object.
   * @returns {Promise<StatusResponse>} - The response object.
   */
  async delete(request) {
    await del(this.fetch, `${this.config.host}/api/delete`, {
      name: request.model
    });
    return { status: "success" };
  }
  /**
   * Copies a model from one name to another. The request object should contain the name of the
   * model to copy and the new name.
   * @param request {CopyRequest} - The request object.
   * @returns {Promise<StatusResponse>} - The response object.
   */
  async copy(request) {
    await post(this.fetch, `${this.config.host}/api/copy`, { ...request });
    return { status: "success" };
  }
  /**
   * Lists the models on the server.
   * @returns {Promise<ListResponse>} - The response object.
   * @throws {Error} - If the response body is missing.
   */
  async list() {
    const response = await get2(this.fetch, `${this.config.host}/api/tags`);
    return await response.json();
  }
  /**
   * Shows the metadata of a model. The request object should contain the name of the model.
   * @param request {ShowRequest} - The request object.
   * @returns {Promise<ShowResponse>} - The response object.
   */
  async show(request) {
    const response = await post(this.fetch, `${this.config.host}/api/show`, {
      ...request
    });
    return await response.json();
  }
  /**
   * Embeds text input into vectors.
   * @param request {EmbedRequest} - The request object.
   * @returns {Promise<EmbedResponse>} - The response object.
   */
  async embed(request) {
    const response = await post(this.fetch, `${this.config.host}/api/embed`, {
      ...request
    });
    return await response.json();
  }
  /**
   * Embeds a text prompt into a vector.
   * @param request {EmbeddingsRequest} - The request object.
   * @returns {Promise<EmbeddingsResponse>} - The response object.
   */
  async embeddings(request) {
    const response = await post(this.fetch, `${this.config.host}/api/embeddings`, {
      ...request
    });
    return await response.json();
  }
  /**
   * Lists the running models on the server
   * @returns {Promise<ListResponse>} - The response object.
   * @throws {Error} - If the response body is missing.
   */
  async ps() {
    const response = await get2(this.fetch, `${this.config.host}/api/ps`);
    return await response.json();
  }
};
var browser = new Ollama$1();

// node_modules/@langchain/ollama/dist/chat_models.js
init_outputs2();

// node_modules/@langchain/core/utils/stream.js
init_stream();

// node_modules/@langchain/ollama/node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex5 = [];
for (i3 = 0; i3 < 256; ++i3) {
  byteToHex5.push((i3 + 256).toString(16).slice(1));
}
var i3;
function unsafeStringify5(arr2, offset5 = 0) {
  return (byteToHex5[arr2[offset5 + 0]] + byteToHex5[arr2[offset5 + 1]] + byteToHex5[arr2[offset5 + 2]] + byteToHex5[arr2[offset5 + 3]] + "-" + byteToHex5[arr2[offset5 + 4]] + byteToHex5[arr2[offset5 + 5]] + "-" + byteToHex5[arr2[offset5 + 6]] + byteToHex5[arr2[offset5 + 7]] + "-" + byteToHex5[arr2[offset5 + 8]] + byteToHex5[arr2[offset5 + 9]] + "-" + byteToHex5[arr2[offset5 + 10]] + byteToHex5[arr2[offset5 + 11]] + byteToHex5[arr2[offset5 + 12]] + byteToHex5[arr2[offset5 + 13]] + byteToHex5[arr2[offset5 + 14]] + byteToHex5[arr2[offset5 + 15]]).toLowerCase();
}

// node_modules/@langchain/ollama/node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues5;
var rnds85 = new Uint8Array(16);
function rng5() {
  if (!getRandomValues5) {
    getRandomValues5 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
    if (!getRandomValues5) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues5(rnds85);
}

// node_modules/@langchain/ollama/node_modules/uuid/dist/esm-browser/native.js
var randomUUID5 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default5 = {
  randomUUID: randomUUID5
};

// node_modules/@langchain/ollama/node_modules/uuid/dist/esm-browser/v4.js
function v45(options, buf, offset5) {
  if (native_default5.randomUUID && !buf && !options) {
    return native_default5.randomUUID();
  }
  options = options || {};
  var rnds = options.random || (options.rng || rng5)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset5 = offset5 || 0;
    for (var i3 = 0; i3 < 16; ++i3) {
      buf[offset5 + i3] = rnds[i3];
    }
    return buf;
  }
  return unsafeStringify5(rnds);
}
var v4_default5 = v45;

// node_modules/@langchain/ollama/dist/utils.js
function convertOllamaMessagesToLangChain(messages, extra) {
  return new AIMessageChunk({
    content: messages.content ?? "",
    tool_call_chunks: messages.tool_calls?.map((tc) => ({
      name: tc.function.name,
      args: JSON.stringify(tc.function.arguments),
      type: "tool_call_chunk",
      index: 0,
      id: v4_default5()
    })),
    response_metadata: extra?.responseMetadata,
    usage_metadata: extra?.usageMetadata
  });
}
function extractBase64FromDataUrl(dataUrl) {
  const match2 = dataUrl.match(/^data:.*?;base64,(.*)$/);
  return match2 ? match2[1] : "";
}
function convertAMessagesToOllama(messages) {
  if (typeof messages.content === "string") {
    return [
      {
        role: "assistant",
        content: messages.content
      }
    ];
  }
  const textFields = messages.content.filter((c4) => c4.type === "text" && typeof c4.text === "string");
  const textMessages = textFields.map((c4) => ({
    role: "assistant",
    content: c4.text
  }));
  let toolCallMsgs;
  if (messages.content.find((c4) => c4.type === "tool_use") && messages.tool_calls?.length) {
    const toolCalls = messages.tool_calls?.map((tc) => ({
      id: tc.id,
      type: "function",
      function: {
        name: tc.name,
        arguments: tc.args
      }
    }));
    if (toolCalls) {
      toolCallMsgs = {
        role: "assistant",
        tool_calls: toolCalls,
        content: ""
      };
    }
  } else if (messages.content.find((c4) => c4.type === "tool_use") && !messages.tool_calls?.length) {
    throw new Error("'tool_use' content type is not supported without tool calls.");
  }
  return [...textMessages, ...toolCallMsgs ? [toolCallMsgs] : []];
}
function convertHumanGenericMessagesToOllama(message) {
  if (typeof message.content === "string") {
    return [
      {
        role: "user",
        content: message.content
      }
    ];
  }
  return message.content.map((c4) => {
    if (c4.type === "text") {
      return {
        role: "user",
        content: c4.text
      };
    } else if (c4.type === "image_url") {
      if (typeof c4.image_url === "string") {
        return {
          role: "user",
          content: "",
          images: [extractBase64FromDataUrl(c4.image_url)]
        };
      } else if (c4.image_url.url && typeof c4.image_url.url === "string") {
        return {
          role: "user",
          content: "",
          images: [extractBase64FromDataUrl(c4.image_url.url)]
        };
      }
    }
    throw new Error(`Unsupported content type: ${c4.type}`);
  });
}
function convertSystemMessageToOllama(message) {
  if (typeof message.content === "string") {
    return [
      {
        role: "system",
        content: message.content
      }
    ];
  } else if (message.content.every((c4) => c4.type === "text" && typeof c4.text === "string")) {
    return message.content.map((c4) => ({
      role: "system",
      content: c4.text
    }));
  } else {
    throw new Error(`Unsupported content type(s): ${message.content.map((c4) => c4.type).join(", ")}`);
  }
}
function convertToolMessageToOllama(message) {
  if (typeof message.content !== "string") {
    throw new Error("Non string tool message content is not supported");
  }
  return [
    {
      role: "tool",
      content: message.content
    }
  ];
}
function convertToOllamaMessages(messages) {
  return messages.flatMap((msg) => {
    if (["human", "generic"].includes(msg._getType())) {
      return convertHumanGenericMessagesToOllama(msg);
    } else if (msg._getType() === "ai") {
      return convertAMessagesToOllama(msg);
    } else if (msg._getType() === "system") {
      return convertSystemMessageToOllama(msg);
    } else if (msg._getType() === "tool") {
      return convertToolMessageToOllama(msg);
    } else {
      throw new Error(`Unsupported message type: ${msg._getType()}`);
    }
  });
}

// node_modules/@langchain/ollama/dist/chat_models.js
var ChatOllama = class extends BaseChatModel {
  // Used for tracing, replace with the same name as your class
  static lc_name() {
    return "ChatOllama";
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "llama3"
    });
    Object.defineProperty(this, "numa", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numCtx", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numBatch", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numGpu", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "mainGpu", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "lowVram", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "f16Kv", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "logitsAll", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "vocabOnly", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "useMmap", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "useMlock", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "embeddingOnly", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numThread", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numKeep", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "seed", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "numPredict", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "topK", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "topP", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "tfsZ", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "typicalP", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "repeatLastN", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "repeatPenalty", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "presencePenalty", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "frequencyPenalty", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "mirostat", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "mirostatTau", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "mirostatEta", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "penalizeNewline", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "format", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "keepAlive", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "5m"
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "checkOrPullModel", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "baseUrl", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "http://127.0.0.1:11434"
    });
    this.client = new Ollama$1({
      host: fields?.baseUrl,
      headers: fields?.headers
    });
    this.baseUrl = fields?.baseUrl ?? this.baseUrl;
    this.model = fields?.model ?? this.model;
    this.numa = fields?.numa;
    this.numCtx = fields?.numCtx;
    this.numBatch = fields?.numBatch;
    this.numGpu = fields?.numGpu;
    this.mainGpu = fields?.mainGpu;
    this.lowVram = fields?.lowVram;
    this.f16Kv = fields?.f16Kv;
    this.logitsAll = fields?.logitsAll;
    this.vocabOnly = fields?.vocabOnly;
    this.useMmap = fields?.useMmap;
    this.useMlock = fields?.useMlock;
    this.embeddingOnly = fields?.embeddingOnly;
    this.numThread = fields?.numThread;
    this.numKeep = fields?.numKeep;
    this.seed = fields?.seed;
    this.numPredict = fields?.numPredict;
    this.topK = fields?.topK;
    this.topP = fields?.topP;
    this.tfsZ = fields?.tfsZ;
    this.typicalP = fields?.typicalP;
    this.repeatLastN = fields?.repeatLastN;
    this.temperature = fields?.temperature;
    this.repeatPenalty = fields?.repeatPenalty;
    this.presencePenalty = fields?.presencePenalty;
    this.frequencyPenalty = fields?.frequencyPenalty;
    this.mirostat = fields?.mirostat;
    this.mirostatTau = fields?.mirostatTau;
    this.mirostatEta = fields?.mirostatEta;
    this.penalizeNewline = fields?.penalizeNewline;
    this.streaming = fields?.streaming;
    this.format = fields?.format;
    this.keepAlive = fields?.keepAlive ?? this.keepAlive;
    this.checkOrPullModel = fields?.checkOrPullModel ?? this.checkOrPullModel;
  }
  // Replace
  _llmType() {
    return "ollama";
  }
  /**
   * Download a model onto the local machine.
   *
   * @param {string} model The name of the model to download.
   * @param {PullModelOptions | undefined} options Options for pulling the model.
   * @returns {Promise<void>}
   */
  async pull(model, options) {
    const { stream, insecure, logProgress } = {
      stream: true,
      ...options
    };
    if (stream) {
      for await (const chunk of await this.client.pull({
        model,
        insecure,
        stream
      })) {
        if (logProgress) {
          console.log(chunk);
        }
      }
    } else {
      const response = await this.client.pull({ model, insecure });
      if (logProgress) {
        console.log(response);
      }
    }
  }
  bindTools(tools, kwargs) {
    return this.bind({
      tools: tools.map((tool2) => convertToOpenAITool(tool2)),
      ...kwargs
    });
  }
  getLsParams(options) {
    const params = this.invocationParams(options);
    return {
      ls_provider: "ollama",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: params.options?.temperature ?? void 0,
      ls_max_tokens: params.options?.num_predict ?? void 0,
      ls_stop: options.stop
    };
  }
  invocationParams(options) {
    if (options?.tool_choice) {
      throw new Error("Tool choice is not supported for ChatOllama.");
    }
    return {
      model: this.model,
      format: this.format,
      keep_alive: this.keepAlive,
      options: {
        numa: this.numa,
        num_ctx: this.numCtx,
        num_batch: this.numBatch,
        num_gpu: this.numGpu,
        main_gpu: this.mainGpu,
        low_vram: this.lowVram,
        f16_kv: this.f16Kv,
        logits_all: this.logitsAll,
        vocab_only: this.vocabOnly,
        use_mmap: this.useMmap,
        use_mlock: this.useMlock,
        embedding_only: this.embeddingOnly,
        num_thread: this.numThread,
        num_keep: this.numKeep,
        seed: this.seed,
        num_predict: this.numPredict,
        top_k: this.topK,
        top_p: this.topP,
        tfs_z: this.tfsZ,
        typical_p: this.typicalP,
        repeat_last_n: this.repeatLastN,
        temperature: this.temperature,
        repeat_penalty: this.repeatPenalty,
        presence_penalty: this.presencePenalty,
        frequency_penalty: this.frequencyPenalty,
        mirostat: this.mirostat,
        mirostat_tau: this.mirostatTau,
        mirostat_eta: this.mirostatEta,
        penalize_newline: this.penalizeNewline,
        stop: options?.stop
      },
      tools: options?.tools?.length ? options.tools.map((tool2) => convertToOpenAITool(tool2)) : void 0
    };
  }
  /**
   * Check if a model exists on the local machine.
   *
   * @param {string} model The name of the model to check.
   * @returns {Promise<boolean>} Whether or not the model exists.
   */
  async checkModelExistsOnMachine(model) {
    const { models } = await this.client.list();
    return !!models.find((m3) => m3.name === model || m3.name === `${model}:latest`);
  }
  async _generate(messages, options, runManager) {
    if (this.checkOrPullModel) {
      if (!await this.checkModelExistsOnMachine(this.model)) {
        await this.pull(this.model, {
          logProgress: true
        });
      }
    }
    let finalChunk;
    for await (const chunk of this._streamResponseChunks(messages, options, runManager)) {
      if (!finalChunk) {
        finalChunk = chunk.message;
      } else {
        finalChunk = concat(finalChunk, chunk.message);
      }
    }
    const nonChunkMessage = new AIMessage({
      id: finalChunk?.id,
      content: finalChunk?.content ?? "",
      tool_calls: finalChunk?.tool_calls,
      response_metadata: finalChunk?.response_metadata,
      usage_metadata: finalChunk?.usage_metadata
    });
    return {
      generations: [
        {
          text: typeof nonChunkMessage.content === "string" ? nonChunkMessage.content : "",
          message: nonChunkMessage
        }
      ]
    };
  }
  /**
   * Implement to support streaming.
   * Should yield chunks iteratively.
   */
  async *_streamResponseChunks(messages, options, runManager) {
    if (this.checkOrPullModel) {
      if (!await this.checkModelExistsOnMachine(this.model)) {
        await this.pull(this.model, {
          logProgress: true
        });
      }
    }
    const params = this.invocationParams(options);
    const ollamaMessages = convertToOllamaMessages(messages);
    const usageMetadata = {
      input_tokens: 0,
      output_tokens: 0,
      total_tokens: 0
    };
    if (params.tools && params.tools.length > 0) {
      const toolResult = await this.client.chat({
        ...params,
        messages: ollamaMessages,
        stream: false
        // Ollama currently does not support streaming with tools
      });
      const { message: responseMessage, ...rest } = toolResult;
      usageMetadata.input_tokens += rest.prompt_eval_count ?? 0;
      usageMetadata.output_tokens += rest.eval_count ?? 0;
      usageMetadata.total_tokens = usageMetadata.input_tokens + usageMetadata.output_tokens;
      yield new ChatGenerationChunk({
        text: responseMessage.content,
        message: convertOllamaMessagesToLangChain(responseMessage, {
          responseMetadata: rest,
          usageMetadata
        })
      });
      return runManager?.handleLLMNewToken(responseMessage.content);
    }
    const stream = await this.client.chat({
      ...params,
      messages: ollamaMessages,
      stream: true
    });
    let lastMetadata;
    for await (const chunk of stream) {
      if (options.signal?.aborted) {
        this.client.abort();
      }
      const { message: responseMessage, ...rest } = chunk;
      usageMetadata.input_tokens += rest.prompt_eval_count ?? 0;
      usageMetadata.output_tokens += rest.eval_count ?? 0;
      usageMetadata.total_tokens = usageMetadata.input_tokens + usageMetadata.output_tokens;
      lastMetadata = rest;
      yield new ChatGenerationChunk({
        text: responseMessage.content ?? "",
        message: convertOllamaMessagesToLangChain(responseMessage)
      });
      await runManager?.handleLLMNewToken(responseMessage.content ?? "");
    }
    yield new ChatGenerationChunk({
      text: "",
      message: new AIMessageChunk({
        content: "",
        response_metadata: lastMetadata,
        usage_metadata: usageMetadata
      })
    });
  }
};

// node_modules/@langchain/ollama/dist/embeddings.js
var OllamaEmbeddings = class extends Embeddings {
  constructor(fields) {
    super({ maxConcurrency: 1, ...fields });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "mxbai-embed-large"
    });
    Object.defineProperty(this, "baseUrl", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "http://localhost:11434"
    });
    Object.defineProperty(this, "keepAlive", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "5m"
    });
    Object.defineProperty(this, "requestOptions", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "truncate", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    this.client = new Ollama$1({
      host: fields?.baseUrl,
      headers: fields?.headers
    });
    this.baseUrl = fields?.baseUrl ?? this.baseUrl;
    this.model = fields?.model ?? this.model;
    this.keepAlive = fields?.keepAlive ?? this.keepAlive;
    this.truncate = fields?.truncate ?? this.truncate;
    this.requestOptions = fields?.requestOptions ? this._convertOptions(fields?.requestOptions) : void 0;
  }
  /** convert camelCased Ollama request options like "useMMap" to
   * the snake_cased equivalent which the ollama API actually uses.
   * Used only for consistency with the llms/Ollama and chatModels/Ollama classes
   */
  _convertOptions(requestOptions) {
    const snakeCasedOptions = {};
    const mapping = {
      embeddingOnly: "embedding_only",
      frequencyPenalty: "frequency_penalty",
      keepAlive: "keep_alive",
      logitsAll: "logits_all",
      lowVram: "low_vram",
      mainGpu: "main_gpu",
      mirostat: "mirostat",
      mirostatEta: "mirostat_eta",
      mirostatTau: "mirostat_tau",
      numBatch: "num_batch",
      numCtx: "num_ctx",
      numGpu: "num_gpu",
      numKeep: "num_keep",
      numPredict: "num_predict",
      numThread: "num_thread",
      penalizeNewline: "penalize_newline",
      presencePenalty: "presence_penalty",
      repeatLastN: "repeat_last_n",
      repeatPenalty: "repeat_penalty",
      temperature: "temperature",
      stop: "stop",
      tfsZ: "tfs_z",
      topK: "top_k",
      topP: "top_p",
      typicalP: "typical_p",
      useMlock: "use_mlock",
      useMmap: "use_mmap",
      vocabOnly: "vocab_only",
      f16Kv: "f16_kv",
      numa: "numa",
      seed: "seed"
    };
    for (const [key, value] of Object.entries(requestOptions)) {
      const snakeCasedOption = mapping[key];
      if (snakeCasedOption) {
        snakeCasedOptions[snakeCasedOption] = value;
      }
    }
    return snakeCasedOptions;
  }
  async embedDocuments(texts) {
    return this.embeddingWithRetry(texts);
  }
  async embedQuery(text) {
    return (await this.embeddingWithRetry([text]))[0];
  }
  async embeddingWithRetry(texts) {
    const res = await this.caller.call(() => this.client.embed({
      model: this.model,
      input: texts,
      keep_alive: this.keepAlive,
      options: this.requestOptions,
      truncate: this.truncate
    }));
    return res.embeddings;
  }
};

// node_modules/@langchain/ollama/dist/llms.js
init_outputs2();

// node_modules/openai/internal/qs/formats.mjs
var default_format = "RFC3986";
var formatters = {
  RFC1738: (v5) => String(v5).replace(/%20/g, "+"),
  RFC3986: (v5) => String(v5)
};
var RFC1738 = "RFC1738";

// node_modules/openai/internal/qs/utils.mjs
var is_array = Array.isArray;
var hex_table = (() => {
  const array = [];
  for (let i3 = 0; i3 < 256; ++i3) {
    array.push("%" + ((i3 < 16 ? "0" : "") + i3.toString(16)).toUpperCase());
  }
  return array;
})();
var limit = 1024;
var encode = (str2, _defaultEncoder, charset, _kind, format) => {
  if (str2.length === 0) {
    return str2;
  }
  let string = str2;
  if (typeof str2 === "symbol") {
    string = Symbol.prototype.toString.call(str2);
  } else if (typeof str2 !== "string") {
    string = String(str2);
  }
  if (charset === "iso-8859-1") {
    return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
      return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
    });
  }
  let out = "";
  for (let j3 = 0; j3 < string.length; j3 += limit) {
    const segment = string.length >= limit ? string.slice(j3, j3 + limit) : string;
    const arr2 = [];
    for (let i3 = 0; i3 < segment.length; ++i3) {
      let c4 = segment.charCodeAt(i3);
      if (c4 === 45 || // -
      c4 === 46 || // .
      c4 === 95 || // _
      c4 === 126 || // ~
      c4 >= 48 && c4 <= 57 || // 0-9
      c4 >= 65 && c4 <= 90 || // a-z
      c4 >= 97 && c4 <= 122 || // A-Z
      format === RFC1738 && (c4 === 40 || c4 === 41)) {
        arr2[arr2.length] = segment.charAt(i3);
        continue;
      }
      if (c4 < 128) {
        arr2[arr2.length] = hex_table[c4];
        continue;
      }
      if (c4 < 2048) {
        arr2[arr2.length] = hex_table[192 | c4 >> 6] + hex_table[128 | c4 & 63];
        continue;
      }
      if (c4 < 55296 || c4 >= 57344) {
        arr2[arr2.length] = hex_table[224 | c4 >> 12] + hex_table[128 | c4 >> 6 & 63] + hex_table[128 | c4 & 63];
        continue;
      }
      i3 += 1;
      c4 = 65536 + ((c4 & 1023) << 10 | segment.charCodeAt(i3) & 1023);
      arr2[arr2.length] = hex_table[240 | c4 >> 18] + hex_table[128 | c4 >> 12 & 63] + hex_table[128 | c4 >> 6 & 63] + hex_table[128 | c4 & 63];
    }
    out += arr2.join("");
  }
  return out;
};
function is_buffer(obj) {
  if (!obj || typeof obj !== "object") {
    return false;
  }
  return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
}
function maybe_map(val2, fn) {
  if (is_array(val2)) {
    const mapped = [];
    for (let i3 = 0; i3 < val2.length; i3 += 1) {
      mapped.push(fn(val2[i3]));
    }
    return mapped;
  }
  return fn(val2);
}

// node_modules/openai/internal/qs/stringify.mjs
var has = Object.prototype.hasOwnProperty;
var array_prefix_generators = {
  brackets(prefix) {
    return String(prefix) + "[]";
  },
  comma: "comma",
  indices(prefix, key) {
    return String(prefix) + "[" + key + "]";
  },
  repeat(prefix) {
    return String(prefix);
  }
};
var is_array2 = Array.isArray;
var push2 = Array.prototype.push;
var push_to_array = function(arr2, value_or_array) {
  push2.apply(arr2, is_array2(value_or_array) ? value_or_array : [value_or_array]);
};
var to_ISO = Date.prototype.toISOString;
var defaults = {
  addQueryPrefix: false,
  allowDots: false,
  allowEmptyArrays: false,
  arrayFormat: "indices",
  charset: "utf-8",
  charsetSentinel: false,
  delimiter: "&",
  encode: true,
  encodeDotInKeys: false,
  encoder: encode,
  encodeValuesOnly: false,
  format: default_format,
  formatter: formatters[default_format],
  /** @deprecated */
  indices: false,
  serializeDate(date2) {
    return to_ISO.call(date2);
  },
  skipNulls: false,
  strictNullHandling: false
};
function is_non_nullish_primitive(v5) {
  return typeof v5 === "string" || typeof v5 === "number" || typeof v5 === "boolean" || typeof v5 === "symbol" || typeof v5 === "bigint";
}
var sentinel = {};
function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
  let obj = object;
  let tmp_sc = sideChannel;
  let step = 0;
  let find_flag = false;
  while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
    const pos = tmp_sc.get(object);
    step += 1;
    if (typeof pos !== "undefined") {
      if (pos === step) {
        throw new RangeError("Cyclic object value");
      } else {
        find_flag = true;
      }
    }
    if (typeof tmp_sc.get(sentinel) === "undefined") {
      step = 0;
    }
  }
  if (typeof filter2 === "function") {
    obj = filter2(prefix, obj);
  } else if (obj instanceof Date) {
    obj = serializeDate?.(obj);
  } else if (generateArrayPrefix === "comma" && is_array2(obj)) {
    obj = maybe_map(obj, function(value) {
      if (value instanceof Date) {
        return serializeDate?.(value);
      }
      return value;
    });
  }
  if (obj === null) {
    if (strictNullHandling) {
      return encoder && !encodeValuesOnly ? (
        // @ts-expect-error
        encoder(prefix, defaults.encoder, charset, "key", format)
      ) : prefix;
    }
    obj = "";
  }
  if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
    if (encoder) {
      const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format);
      return [
        formatter?.(key_value) + "=" + // @ts-expect-error
        formatter?.(encoder(obj, defaults.encoder, charset, "value", format))
      ];
    }
    return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
  }
  const values = [];
  if (typeof obj === "undefined") {
    return values;
  }
  let obj_keys;
  if (generateArrayPrefix === "comma" && is_array2(obj)) {
    if (encodeValuesOnly && encoder) {
      obj = maybe_map(obj, encoder);
    }
    obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
  } else if (is_array2(filter2)) {
    obj_keys = filter2;
  } else {
    const keys = Object.keys(obj);
    obj_keys = sort ? keys.sort(sort) : keys;
  }
  const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
  const adjusted_prefix = commaRoundTrip && is_array2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
  if (allowEmptyArrays && is_array2(obj) && obj.length === 0) {
    return adjusted_prefix + "[]";
  }
  for (let j3 = 0; j3 < obj_keys.length; ++j3) {
    const key = obj_keys[j3];
    const value = (
      // @ts-ignore
      typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]
    );
    if (skipNulls && value === null) {
      continue;
    }
    const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
    const key_prefix = is_array2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
    sideChannel.set(object, step);
    const valueSideChannel = /* @__PURE__ */ new WeakMap();
    valueSideChannel.set(sentinel, sideChannel);
    push_to_array(values, inner_stringify(
      value,
      key_prefix,
      generateArrayPrefix,
      commaRoundTrip,
      allowEmptyArrays,
      strictNullHandling,
      skipNulls,
      encodeDotInKeys,
      // @ts-ignore
      generateArrayPrefix === "comma" && encodeValuesOnly && is_array2(obj) ? null : encoder,
      filter2,
      sort,
      allowDots,
      serializeDate,
      format,
      formatter,
      encodeValuesOnly,
      charset,
      valueSideChannel
    ));
  }
  return values;
}
function normalize_stringify_options(opts = defaults) {
  if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
    throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
  }
  if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
    throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
  }
  if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
    throw new TypeError("Encoder has to be a function.");
  }
  const charset = opts.charset || defaults.charset;
  if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
    throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
  }
  let format = default_format;
  if (typeof opts.format !== "undefined") {
    if (!has.call(formatters, opts.format)) {
      throw new TypeError("Unknown format option provided.");
    }
    format = opts.format;
  }
  const formatter = formatters[format];
  let filter2 = defaults.filter;
  if (typeof opts.filter === "function" || is_array2(opts.filter)) {
    filter2 = opts.filter;
  }
  let arrayFormat;
  if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
    arrayFormat = opts.arrayFormat;
  } else if ("indices" in opts) {
    arrayFormat = opts.indices ? "indices" : "repeat";
  } else {
    arrayFormat = defaults.arrayFormat;
  }
  if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
    throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
  }
  const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
  return {
    addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
    // @ts-ignore
    allowDots,
    allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
    arrayFormat,
    charset,
    charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
    commaRoundTrip: !!opts.commaRoundTrip,
    delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
    encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
    encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
    encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
    encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
    filter: filter2,
    format,
    formatter,
    serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
    skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
    // @ts-ignore
    sort: typeof opts.sort === "function" ? opts.sort : null,
    strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
  };
}
function stringify2(object, opts = {}) {
  let obj = object;
  const options = normalize_stringify_options(opts);
  let obj_keys;
  let filter2;
  if (typeof options.filter === "function") {
    filter2 = options.filter;
    obj = filter2("", obj);
  } else if (is_array2(options.filter)) {
    filter2 = options.filter;
    obj_keys = filter2;
  }
  const keys = [];
  if (typeof obj !== "object" || obj === null) {
    return "";
  }
  const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
  const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
  if (!obj_keys) {
    obj_keys = Object.keys(obj);
  }
  if (options.sort) {
    obj_keys.sort(options.sort);
  }
  const sideChannel = /* @__PURE__ */ new WeakMap();
  for (let i3 = 0; i3 < obj_keys.length; ++i3) {
    const key = obj_keys[i3];
    if (options.skipNulls && obj[key] === null) {
      continue;
    }
    push_to_array(keys, inner_stringify(
      obj[key],
      key,
      // @ts-expect-error
      generateArrayPrefix,
      commaRoundTrip,
      options.allowEmptyArrays,
      options.strictNullHandling,
      options.skipNulls,
      options.encodeDotInKeys,
      options.encode ? options.encoder : null,
      options.filter,
      options.sort,
      options.allowDots,
      options.serializeDate,
      options.format,
      options.formatter,
      options.encodeValuesOnly,
      options.charset,
      sideChannel
    ));
  }
  const joined = keys.join(options.delimiter);
  let prefix = options.addQueryPrefix === true ? "?" : "";
  if (options.charsetSentinel) {
    if (options.charset === "iso-8859-1") {
      prefix += "utf8=%26%2310003%3B&";
    } else {
      prefix += "utf8=%E2%9C%93&";
    }
  }
  return joined.length > 0 ? prefix + joined : "";
}

// node_modules/openai/version.mjs
var VERSION = "4.73.1";

// node_modules/openai/_shims/registry.mjs
var auto = false;
var kind = void 0;
var fetch3 = void 0;
var Request3 = void 0;
var Response3 = void 0;
var Headers3 = void 0;
var FormData2 = void 0;
var Blob2 = void 0;
var File2 = void 0;
var ReadableStream2 = void 0;
var getMultipartRequestOptions = void 0;
var getDefaultAgent = void 0;
var fileFromPath = void 0;
var isFsReadStream = void 0;
function setShims(shims, options = { auto: false }) {
  if (auto) {
    throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`);
  }
  if (kind) {
    throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``);
  }
  auto = options.auto;
  kind = shims.kind;
  fetch3 = shims.fetch;
  Request3 = shims.Request;
  Response3 = shims.Response;
  Headers3 = shims.Headers;
  FormData2 = shims.FormData;
  Blob2 = shims.Blob;
  File2 = shims.File;
  ReadableStream2 = shims.ReadableStream;
  getMultipartRequestOptions = shims.getMultipartRequestOptions;
  getDefaultAgent = shims.getDefaultAgent;
  fileFromPath = shims.fileFromPath;
  isFsReadStream = shims.isFsReadStream;
}

// node_modules/openai/_shims/MultipartBody.mjs
var MultipartBody = class {
  constructor(body) {
    this.body = body;
  }
  get [Symbol.toStringTag]() {
    return "MultipartBody";
  }
};

// node_modules/openai/_shims/web-runtime.mjs
function getRuntime({ manuallyImported } = {}) {
  const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from 'openai'\`:
- \`import 'openai/shims/node'\` (if you're running on Node)
- \`import 'openai/shims/web'\` (otherwise)
`;
  let _fetch, _Request, _Response, _Headers;
  try {
    _fetch = fetch;
    _Request = Request;
    _Response = Response;
    _Headers = Headers;
  } catch (error) {
    throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
  }
  return {
    kind: "web",
    fetch: _fetch,
    Request: _Request,
    Response: _Response,
    Headers: _Headers,
    FormData: (
      // @ts-ignore
      typeof FormData !== "undefined" ? FormData : class FormData {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
        }
      }
    ),
    Blob: typeof Blob !== "undefined" ? Blob : class Blob {
      constructor() {
        throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
      }
    },
    File: (
      // @ts-ignore
      typeof File !== "undefined" ? File : class File {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
        }
      }
    ),
    ReadableStream: (
      // @ts-ignore
      typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream {
        // @ts-ignore
        constructor() {
          throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
        }
      }
    ),
    getMultipartRequestOptions: async (form, opts) => ({
      ...opts,
      body: new MultipartBody(form)
    }),
    getDefaultAgent: (url) => void 0,
    fileFromPath: () => {
      throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads");
    },
    isFsReadStream: (value) => false
  };
}

// node_modules/openai/_shims/index.mjs
if (!kind)
  setShims(getRuntime(), { auto: true });

// node_modules/openai/error.mjs
var OpenAIError = class extends Error {
};
var APIError = class extends OpenAIError {
  constructor(status, error, message, headers) {
    super(`${APIError.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.request_id = headers?.["x-request-id"];
    const data = error;
    this.error = data;
    this.code = data?.["code"];
    this.param = data?.["param"];
    this.type = data?.["type"];
  }
  static makeMessage(status, error, message) {
    const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status) {
      return new APIConnectionError({ message, cause: castToError(errorResponse) });
    }
    const error = errorResponse?.["error"];
    if (status === 400) {
      return new BadRequestError(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError(status, error, message, headers);
    }
    return new APIError(status, error, message, headers);
  }
};
var APIUserAbortError = class extends APIError {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
    this.status = void 0;
  }
};
var APIConnectionError = class extends APIError {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    this.status = void 0;
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError = class extends APIConnectionError {
  constructor({ message } = {}) {
    super({ message: message ?? "Request timed out." });
  }
};
var BadRequestError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 400;
  }
};
var AuthenticationError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 401;
  }
};
var PermissionDeniedError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 403;
  }
};
var NotFoundError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 404;
  }
};
var ConflictError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 409;
  }
};
var UnprocessableEntityError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 422;
  }
};
var RateLimitError = class extends APIError {
  constructor() {
    super(...arguments);
    this.status = 429;
  }
};
var InternalServerError = class extends APIError {
};
var LengthFinishReasonError = class extends OpenAIError {
  constructor() {
    super(`Could not parse response content as the length limit was reached`);
  }
};
var ContentFilterFinishReasonError = class extends OpenAIError {
  constructor() {
    super(`Could not parse response content as the request was rejected by the content filter`);
  }
};

// node_modules/openai/internal/decoders/line.mjs
var LineDecoder = class {
  constructor() {
    this.buffer = [];
    this.trailingCR = false;
  }
  decode(chunk) {
    let text = this.decodeText(chunk);
    if (this.trailingCR) {
      text = "\r" + text;
      this.trailingCR = false;
    }
    if (text.endsWith("\r")) {
      this.trailingCR = true;
      text = text.slice(0, -1);
    }
    if (!text) {
      return [];
    }
    const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
    let lines = text.split(LineDecoder.NEWLINE_REGEXP);
    if (trailingNewline) {
      lines.pop();
    }
    if (lines.length === 1 && !trailingNewline) {
      this.buffer.push(lines[0]);
      return [];
    }
    if (this.buffer.length > 0) {
      lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
      this.buffer = [];
    }
    if (!trailingNewline) {
      this.buffer = [lines.pop() || ""];
    }
    return lines;
  }
  decodeText(bytes) {
    if (bytes == null)
      return "";
    if (typeof bytes === "string")
      return bytes;
    if (typeof Buffer !== "undefined") {
      if (bytes instanceof Buffer) {
        return bytes.toString();
      }
      if (bytes instanceof Uint8Array) {
        return Buffer.from(bytes).toString();
      }
      throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
    }
    if (typeof TextDecoder !== "undefined") {
      if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
        this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
        return this.textDecoder.decode(bytes);
      }
      throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
    }
    throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
  }
  flush() {
    if (!this.buffer.length && !this.trailingCR) {
      return [];
    }
    const lines = [this.buffer.join("")];
    this.buffer = [];
    this.trailingCR = false;
    return lines;
  }
};
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;

// node_modules/openai/streaming.mjs
var Stream = class {
  constructor(iterator, controller) {
    this.iterator = iterator;
    this.controller = controller;
  }
  static fromSSEResponse(response, controller) {
    let consumed2 = false;
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const sse of _iterSSEMessages(response, controller)) {
          if (done)
            continue;
          if (sse.data.startsWith("[DONE]")) {
            done = true;
            continue;
          }
          if (sse.event === null) {
            let data;
            try {
              data = JSON.parse(sse.data);
            } catch (e3) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e3;
            }
            if (data && data.error) {
              throw new APIError(void 0, data.error, void 0, void 0);
            }
            yield data;
          } else {
            let data;
            try {
              data = JSON.parse(sse.data);
            } catch (e3) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e3;
            }
            if (sse.event == "error") {
              throw new APIError(void 0, data.error, data.message, void 0);
            }
            yield { event: sse.event, data };
          }
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream(iterator, controller);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller) {
    let consumed2 = false;
    async function* iterLines() {
      const lineDecoder = new LineDecoder();
      const iter = readableStreamAsyncIterable(readableStream);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          yield line;
        }
      }
      for (const line of lineDecoder.flush()) {
        yield line;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const line of iterLines()) {
          if (done)
            continue;
          if (line)
            yield JSON.parse(line);
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream(iterator, controller);
  }
  [Symbol.asyncIterator]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue2) => {
      return {
        next: () => {
          if (queue2.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue2.shift();
        }
      };
    };
    return [
      new Stream(() => teeIterator(left), this.controller),
      new Stream(() => teeIterator(right), this.controller)
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    const encoder = new TextEncoder();
    return new ReadableStream2({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encoder.encode(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        await iter.return?.();
      }
    });
  }
};
async function* _iterSSEMessages(response, controller) {
  if (!response.body) {
    controller.abort();
    throw new OpenAIError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder();
  const lineDecoder = new LineDecoder();
  const iter = readableStreamAsyncIterable(response.body);
  for await (const sseChunk of iterSSEChunks(iter)) {
    for (const line of lineDecoder.decode(sseChunk)) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield sse;
    }
  }
  for (const line of lineDecoder.flush()) {
    const sse = sseDecoder.decode(line);
    if (sse)
      yield sse;
  }
}
async function* iterSSEChunks(iterator) {
  let data = new Uint8Array();
  for await (const chunk of iterator) {
    if (chunk == null) {
      continue;
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
function findDoubleNewlineIndex(buffer) {
  const newline = 10;
  const carriage = 13;
  for (let i3 = 0; i3 < buffer.length - 2; i3++) {
    if (buffer[i3] === newline && buffer[i3 + 1] === newline) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === carriage) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === newline && i3 + 3 < buffer.length && buffer[i3 + 2] === carriage && buffer[i3 + 3] === newline) {
      return i3 + 4;
    }
  }
  return -1;
}
var SSEDecoder = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _2, value] = partition2(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
function partition2(str2, delimiter) {
  const index2 = str2.indexOf(delimiter);
  if (index2 !== -1) {
    return [str2.substring(0, index2), delimiter, str2.substring(index2 + delimiter.length)];
  }
  return [str2, "", ""];
}
function readableStreamAsyncIterable(stream) {
  if (stream[Symbol.asyncIterator])
    return stream;
  const reader = stream.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e3) {
        reader.releaseLock();
        throw e3;
      }
    },
    async return() {
      const cancelPromise2 = reader.cancel();
      reader.releaseLock();
      await cancelPromise2;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}

// node_modules/openai/uploads.mjs
var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
var isUploadable = (value) => {
  return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
};
async function toFile(value, name, options) {
  value = await value;
  if (isFileLike(value)) {
    return value;
  }
  if (isResponseLike(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
    const data = isBlobLike(blob) ? [await blob.arrayBuffer()] : [blob];
    return new File2(data, name, options);
  }
  const bits = await getBytes(value);
  name || (name = getName(value) ?? "unknown_file");
  if (!options?.type) {
    const type = bits[0]?.type;
    if (typeof type === "string") {
      options = { ...options, type };
    }
  }
  return new File2(bits, name, options);
}
async function getBytes(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike(value)) {
    parts.push(await value.arrayBuffer());
  } else if (isAsyncIterableIterator(value)) {
    for await (const chunk of value) {
      parts.push(chunk);
    }
  } else {
    throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
  }
  return parts;
}
function propsForError(value) {
  const props = Object.getOwnPropertyNames(value);
  return `[${props.map((p3) => `"${p3}"`).join(", ")}]`;
}
function getName(value) {
  return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
  getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
}
var getStringFromMaybeBuffer = (x2) => {
  if (typeof x2 === "string")
    return x2;
  if (typeof Buffer !== "undefined" && x2 instanceof Buffer)
    return String(x2);
  return void 0;
};
var isAsyncIterableIterator = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var isMultipartBody = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody";
var multipartFormRequestOptions = async (opts) => {
  const form = await createForm(opts.body);
  return getMultipartRequestOptions(form, opts);
};
var createForm = async (body) => {
  const form = new FormData2();
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
  return form;
};
var addFormValue = async (form, key, value) => {
  if (value === void 0)
    return;
  if (value == null) {
    throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
  }
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    form.append(key, String(value));
  } else if (isUploadable(value)) {
    const file = await toFile(value);
    form.append(key, file);
  } else if (Array.isArray(value)) {
    await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
  } else if (typeof value === "object") {
    await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
  } else {
    throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
  }
};

// node_modules/openai/core.mjs
var __classPrivateFieldSet6 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet6 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _AbstractPage_client;
async function defaultParseResponse(props) {
  const { response } = props;
  if (props.options.stream) {
    debug("response", response.status, response.url, response.headers, response.body);
    if (props.options.__streamClass) {
      return props.options.__streamClass.fromSSEResponse(response, props.controller);
    }
    return Stream.fromSSEResponse(response, props.controller);
  }
  if (response.status === 204) {
    return null;
  }
  if (props.options.__binaryResponse) {
    return response;
  }
  const contentType = response.headers.get("content-type");
  const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
  if (isJSON) {
    const json = await response.json();
    debug("response", response.status, response.url, response.headers, json);
    return _addRequestID(json, response);
  }
  const text = await response.text();
  debug("response", response.status, response.url, response.headers, text);
  return text;
}
function _addRequestID(value, response) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return value;
  }
  return Object.defineProperty(value, "_request_id", {
    value: response.headers.get("x-request-id"),
    enumerable: false
  });
}
var APIPromise = class extends Promise {
  constructor(responsePromise, parseResponse = defaultParseResponse) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse;
  }
  _thenUnwrap(transform) {
    return new APIPromise(this.responsePromise, async (props) => _addRequestID(transform(await this.parseResponse(props), props), props.response));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from 'openai'`:
   * - `import 'openai/shims/node'` (if you're running on Node)
   * - `import 'openai/shims/web'` (otherwise)
   */
  asResponse() {
    return this.responsePromise.then((p3) => p3.response);
  }
  /**
   * Gets the parsed response data, the raw `Response` instance and the ID of the request,
   * returned via the X-Request-ID header which is useful for debugging requests and reporting
   * issues to OpenAI.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from 'openai'`:
   * - `import 'openai/shims/node'` (if you're running on Node)
   * - `import 'openai/shims/web'` (otherwise)
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response, request_id: response.headers.get("x-request-id") };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then(this.parseResponse);
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
var APIClient = class {
  constructor({
    baseURL,
    maxRetries = 2,
    timeout = 6e5,
    // 10 minutes
    httpAgent,
    fetch: overridenFetch
  }) {
    this.baseURL = baseURL;
    this.maxRetries = validatePositiveInteger("maxRetries", maxRetries);
    this.timeout = validatePositiveInteger("timeout", timeout);
    this.httpAgent = httpAgent;
    this.fetch = overridenFetch ?? fetch3;
  }
  authHeaders(opts) {
    return {};
  }
  /**
   * Override this to add your own default headers, for example:
   *
   *  {
   *    ...super.defaultHeaders(),
   *    Authorization: 'Bearer 123',
   *  }
   */
  defaultHeaders(opts) {
    return {
      Accept: "application/json",
      "Content-Type": "application/json",
      "User-Agent": this.getUserAgent(),
      ...getPlatformHeaders(),
      ...this.authHeaders(opts)
    };
  }
  /**
   * Override this to add your own headers validation:
   */
  validateHeaders(headers, customHeaders) {
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid4()}`;
  }
  get(path, opts) {
    return this.methodRequest("get", path, opts);
  }
  post(path, opts) {
    return this.methodRequest("post", path, opts);
  }
  patch(path, opts) {
    return this.methodRequest("patch", path, opts);
  }
  put(path, opts) {
    return this.methodRequest("put", path, opts);
  }
  delete(path, opts) {
    return this.methodRequest("delete", path, opts);
  }
  methodRequest(method, path, opts) {
    return this.request(Promise.resolve(opts).then(async (opts2) => {
      const body = opts2 && isBlobLike(opts2?.body) ? new DataView(await opts2.body.arrayBuffer()) : opts2?.body instanceof DataView ? opts2.body : opts2?.body instanceof ArrayBuffer ? new DataView(opts2.body) : opts2 && ArrayBuffer.isView(opts2?.body) ? new DataView(opts2.body.buffer) : opts2?.body;
      return { method, path, ...opts2, body };
    }));
  }
  getAPIList(path, Page2, opts) {
    return this.requestAPIList(Page2, { method: "get", path, ...opts });
  }
  calculateContentLength(body) {
    if (typeof body === "string") {
      if (typeof Buffer !== "undefined") {
        return Buffer.byteLength(body, "utf8").toString();
      }
      if (typeof TextEncoder !== "undefined") {
        const encoder = new TextEncoder();
        const encoded = encoder.encode(body);
        return encoded.length.toString();
      }
    } else if (ArrayBuffer.isView(body)) {
      return body.byteLength.toString();
    }
    return null;
  }
  buildRequest(options, { retryCount = 0 } = {}) {
    const { method, path, query, headers = {} } = options;
    const body = ArrayBuffer.isView(options.body) || options.__binaryRequest && typeof options.body === "string" ? options.body : isMultipartBody(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null;
    const contentLength = this.calculateContentLength(body);
    const url = this.buildURL(path, query);
    if ("timeout" in options)
      validatePositiveInteger("timeout", options.timeout);
    const timeout = options.timeout ?? this.timeout;
    const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
    const minAgentTimeout = timeout + 1e3;
    if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
      httpAgent.options.timeout = minAgentTimeout;
    }
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      headers[this.idempotencyHeader] = options.idempotencyKey;
    }
    const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
    const req = {
      method,
      ...body && { body },
      headers: reqHeaders,
      ...httpAgent && { agent: httpAgent },
      // @ts-ignore node-fetch uses a custom AbortSignal type that is
      // not compatible with standard web types
      signal: options.signal ?? null
    };
    return { req, url, timeout };
  }
  buildHeaders({ options, headers, contentLength, retryCount }) {
    const reqHeaders = {};
    if (contentLength) {
      reqHeaders["content-length"] = contentLength;
    }
    const defaultHeaders = this.defaultHeaders(options);
    applyHeadersMut(reqHeaders, defaultHeaders);
    applyHeadersMut(reqHeaders, headers);
    if (isMultipartBody(options.body) && kind !== "node") {
      delete reqHeaders["content-type"];
    }
    if (getHeader(defaultHeaders, "x-stainless-retry-count") === void 0 && getHeader(headers, "x-stainless-retry-count") === void 0) {
      reqHeaders["x-stainless-retry-count"] = String(retryCount);
    }
    this.validateHeaders(reqHeaders, headers);
    return reqHeaders;
  }
  /**
   * Used as a callback for mutating the given `FinalRequestOptions` object.
   */
  async prepareOptions(options) {
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  parseHeaders(headers) {
    return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
  }
  makeStatusError(status, error, message, headers) {
    return APIError.generate(status, error, message, headers);
  }
  request(options, remainingRetries = null) {
    return new APIPromise(this.makeRequest(options, remainingRetries));
  }
  async makeRequest(optionsInput, retriesRemaining) {
    const options = await optionsInput;
    const maxRetries = options.maxRetries ?? this.maxRetries;
    if (retriesRemaining == null) {
      retriesRemaining = maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });
    await this.prepareRequest(req, { url, options });
    debug("request", url, options, req.headers);
    if (options.signal?.aborted) {
      throw new APIUserAbortError();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
    if (response instanceof Error) {
      if (options.signal?.aborted) {
        throw new APIUserAbortError();
      }
      if (retriesRemaining) {
        return this.retryRequest(options, retriesRemaining);
      }
      if (response.name === "AbortError") {
        throw new APIConnectionTimeoutError();
      }
      throw new APIConnectionError({ cause: response });
    }
    const responseHeaders = createResponseHeaders(response.headers);
    if (!response.ok) {
      if (retriesRemaining && this.shouldRetry(response)) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        debug(`response (error; ${retryMessage2})`, response.status, url, responseHeaders);
        return this.retryRequest(options, retriesRemaining, responseHeaders);
      }
      const errText = await response.text().catch((e3) => castToError(e3).message);
      const errJSON = safeJSON(errText);
      const errMessage = errJSON ? void 0 : errText;
      const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
      debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
      const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
      throw err;
    }
    return { response, options, controller };
  }
  requestAPIList(Page2, options) {
    const request = this.makeRequest(options, null);
    return new PagePromise(this, request, Page2);
  }
  buildURL(path, query) {
    const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path));
    const defaultQuery = this.defaultQuery();
    if (!isEmptyObj(defaultQuery)) {
      query = { ...defaultQuery, ...query };
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  stringifyQuery(query) {
    return Object.entries(query).filter(([_2, value]) => typeof value !== "undefined").map(([key, value]) => {
      if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }
      if (value === null) {
        return `${encodeURIComponent(key)}=`;
      }
      throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
    }).join("&");
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const { signal, ...options } = init || {};
    if (signal)
      signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => {
      clearTimeout(timeout);
    });
  }
  getRequestClient() {
    return { fetch: this.fetch };
  }
  shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, responseHeaders) {
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"];
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders?.["retry-after"];
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
      const maxRetries = options.maxRetries ?? this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION}`;
  }
};
var AbstractPage = class {
  constructor(client2, response, body, options) {
    _AbstractPage_client.set(this, void 0);
    __classPrivateFieldSet6(this, _AbstractPage_client, client2, "f");
    this.options = options;
    this.response = response;
    this.body = body;
  }
  hasNextPage() {
    const items = this.getPaginatedItems();
    if (!items.length)
      return false;
    return this.nextPageInfo() != null;
  }
  async getNextPage() {
    const nextInfo = this.nextPageInfo();
    if (!nextInfo) {
      throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    }
    const nextOptions = { ...this.options };
    if ("params" in nextInfo && typeof nextOptions.query === "object") {
      nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
    } else if ("url" in nextInfo) {
      const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
      for (const [key, value] of params) {
        nextInfo.url.searchParams.set(key, value);
      }
      nextOptions.query = void 0;
      nextOptions.path = nextInfo.url.toString();
    }
    return await __classPrivateFieldGet6(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
  }
  async *iterPages() {
    let page = this;
    yield page;
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      yield page;
    }
  }
  async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (const page of this.iterPages()) {
      for (const item of page.getPaginatedItems()) {
        yield item;
      }
    }
  }
};
var PagePromise = class extends APIPromise {
  constructor(client2, request, Page2) {
    super(request, async (props) => new Page2(client2, props.response, await defaultParseResponse(props), props.options));
  }
  /**
   * Allow auto-paginating iteration on an unawaited list call, eg:
   *
   *    for await (const item of client.items.list()) {
   *      console.log(item)
   *    }
   */
  async *[Symbol.asyncIterator]() {
    const page = await this;
    for await (const item of page) {
      yield item;
    }
  }
};
var createResponseHeaders = (headers) => {
  return new Proxy(Object.fromEntries(
    // @ts-ignore
    headers.entries()
  ), {
    get(target, name) {
      const key = name.toString();
      return target[key.toLowerCase()] || target[key];
    }
  });
};
var requestOptionsKeys = {
  method: true,
  path: true,
  query: true,
  body: true,
  headers: true,
  maxRetries: true,
  stream: true,
  timeout: true,
  httpAgent: true,
  signal: true,
  idempotencyKey: true,
  __binaryRequest: true,
  __binaryResponse: true,
  __streamClass: true
};
var isRequestOptions = (obj) => {
  return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k3) => hasOwn(requestOptionsKeys, k3));
};
var getPlatformProperties = () => {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": normalizePlatform(Deno.build.os),
      "X-Stainless-Arch": normalizeArch(Deno.build.arch),
      "X-Stainless-Runtime": "deno",
      "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
    };
  }
  if (typeof EdgeRuntime !== "undefined") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": `other:${EdgeRuntime}`,
      "X-Stainless-Runtime": "edge",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": normalizePlatform(process.platform),
      "X-Stainless-Arch": normalizeArch(process.arch),
      "X-Stainless-Runtime": "node",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  const browserInfo = getBrowserInfo();
  if (browserInfo) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": "unknown",
      "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
      "X-Stainless-Runtime-Version": browserInfo.version
    };
  }
  return {
    "X-Stainless-Lang": "js",
    "X-Stainless-Package-Version": VERSION,
    "X-Stainless-OS": "Unknown",
    "X-Stainless-Arch": "unknown",
    "X-Stainless-Runtime": "unknown",
    "X-Stainless-Runtime-Version": "unknown"
  };
};
function getBrowserInfo() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major}.${minor}.${patch}` };
    }
  }
  return null;
}
var normalizeArch = (arch) => {
  if (arch === "x32")
    return "x32";
  if (arch === "x86_64" || arch === "x64")
    return "x64";
  if (arch === "arm")
    return "arm";
  if (arch === "aarch64" || arch === "arm64")
    return "arm64";
  if (arch)
    return `other:${arch}`;
  return "unknown";
};
var normalizePlatform = (platform2) => {
  platform2 = platform2.toLowerCase();
  if (platform2.includes("ios"))
    return "iOS";
  if (platform2 === "android")
    return "Android";
  if (platform2 === "darwin")
    return "MacOS";
  if (platform2 === "win32")
    return "Windows";
  if (platform2 === "freebsd")
    return "FreeBSD";
  if (platform2 === "openbsd")
    return "OpenBSD";
  if (platform2 === "linux")
    return "Linux";
  if (platform2)
    return `Other:${platform2}`;
  return "Unknown";
};
var _platformHeaders;
var getPlatformHeaders = () => {
  return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
};
var safeJSON = (text) => {
  try {
    return JSON.parse(text);
  } catch (err) {
    return void 0;
  }
};
var startsWithSchemeRegexp = new RegExp("^(?:[a-z]+:)?//", "i");
var isAbsoluteURL = (url) => {
  return startsWithSchemeRegexp.test(url);
};
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
var validatePositiveInteger = (name, n4) => {
  if (typeof n4 !== "number" || !Number.isInteger(n4)) {
    throw new OpenAIError(`${name} must be an integer`);
  }
  if (n4 < 0) {
    throw new OpenAIError(`${name} must be a positive integer`);
  }
  return n4;
};
var castToError = (err) => {
  if (err instanceof Error)
    return err;
  if (typeof err === "object" && err !== null) {
    try {
      return new Error(JSON.stringify(err));
    } catch {
    }
  }
  return new Error(err);
};
var readEnv = (env) => {
  if (typeof process !== "undefined") {
    return process.env?.[env]?.trim() ?? void 0;
  }
  if (typeof Deno !== "undefined") {
    return Deno.env?.get?.(env)?.trim();
  }
  return void 0;
};
function isEmptyObj(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function applyHeadersMut(targetHeaders, newHeaders) {
  for (const k3 in newHeaders) {
    if (!hasOwn(newHeaders, k3))
      continue;
    const lowerKey = k3.toLowerCase();
    if (!lowerKey)
      continue;
    const val2 = newHeaders[k3];
    if (val2 === null) {
      delete targetHeaders[lowerKey];
    } else if (val2 !== void 0) {
      targetHeaders[lowerKey] = val2;
    }
  }
}
function debug(action, ...args) {
  if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
    console.log(`OpenAI:DEBUG:${action}`, ...args);
  }
}
var uuid4 = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c4) => {
    const r4 = Math.random() * 16 | 0;
    const v5 = c4 === "x" ? r4 : r4 & 3 | 8;
    return v5.toString(16);
  });
};
var isRunningInBrowser = () => {
  return (
    // @ts-ignore
    typeof window !== "undefined" && // @ts-ignore
    typeof window.document !== "undefined" && // @ts-ignore
    typeof navigator !== "undefined"
  );
};
var isHeadersProtocol = (headers) => {
  return typeof headers?.get === "function";
};
var getHeader = (headers, header) => {
  const lowerCasedHeader = header.toLowerCase();
  if (isHeadersProtocol(headers)) {
    const intercapsHeader = header[0]?.toUpperCase() + header.substring(1).replace(/([^\w])(\w)/g, (_m2, g1, g22) => g1 + g22.toUpperCase());
    for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
      const value = headers.get(key);
      if (value) {
        return value;
      }
    }
  }
  for (const [key, value] of Object.entries(headers)) {
    if (key.toLowerCase() === lowerCasedHeader) {
      if (Array.isArray(value)) {
        if (value.length <= 1)
          return value[0];
        console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
        return value[0];
      }
      return value;
    }
  }
  return void 0;
};
function isObj(obj) {
  return obj != null && typeof obj === "object" && !Array.isArray(obj);
}

// node_modules/openai/pagination.mjs
var Page = class extends AbstractPage {
  constructor(client2, response, body, options) {
    super(client2, response, body, options);
    this.data = body.data || [];
    this.object = body.object;
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  // @deprecated Please use `nextPageInfo()` instead
  /**
   * This page represents a response that isn't actually paginated at the API level
   * so there will never be any next page params.
   */
  nextPageParams() {
    return null;
  }
  nextPageInfo() {
    return null;
  }
};
var CursorPage = class extends AbstractPage {
  constructor(client2, response, body, options) {
    super(client2, response, body, options);
    this.data = body.data || [];
  }
  getPaginatedItems() {
    return this.data ?? [];
  }
  // @deprecated Please use `nextPageInfo()` instead
  nextPageParams() {
    const info = this.nextPageInfo();
    if (!info)
      return null;
    if ("params" in info)
      return info.params;
    const params = Object.fromEntries(info.url.searchParams);
    if (!Object.keys(params).length)
      return null;
    return params;
  }
  nextPageInfo() {
    const data = this.getPaginatedItems();
    if (!data.length) {
      return null;
    }
    const id = data[data.length - 1]?.id;
    if (!id) {
      return null;
    }
    return { params: { after: id } };
  }
};

// node_modules/openai/resource.mjs
var APIResource = class {
  constructor(client2) {
    this._client = client2;
  }
};

// node_modules/openai/resources/chat/completions.mjs
var Completions = class extends APIResource {
  create(body, options) {
    return this._client.post("/chat/completions", { body, ...options, stream: body.stream ?? false });
  }
};

// node_modules/openai/resources/chat/chat.mjs
var Chat = class extends APIResource {
  constructor() {
    super(...arguments);
    this.completions = new Completions(this._client);
  }
};
Chat.Completions = Completions;

// node_modules/openai/resources/audio/speech.mjs
var Speech = class extends APIResource {
  /**
   * Generates audio from the input text.
   */
  create(body, options) {
    return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true });
  }
};

// node_modules/openai/resources/audio/transcriptions.mjs
var Transcriptions = class extends APIResource {
  create(body, options) {
    return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ body, ...options }));
  }
};

// node_modules/openai/resources/audio/translations.mjs
var Translations = class extends APIResource {
  create(body, options) {
    return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options }));
  }
};

// node_modules/openai/resources/audio/audio.mjs
var Audio = class extends APIResource {
  constructor() {
    super(...arguments);
    this.transcriptions = new Transcriptions(this._client);
    this.translations = new Translations(this._client);
    this.speech = new Speech(this._client);
  }
};
Audio.Transcriptions = Transcriptions;
Audio.Translations = Translations;
Audio.Speech = Speech;

// node_modules/openai/resources/batches.mjs
var Batches = class extends APIResource {
  /**
   * Creates and executes a batch from an uploaded file of requests
   */
  create(body, options) {
    return this._client.post("/batches", { body, ...options });
  }
  /**
   * Retrieves a batch.
   */
  retrieve(batchId, options) {
    return this._client.get(`/batches/${batchId}`, options);
  }
  list(query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list({}, query);
    }
    return this._client.getAPIList("/batches", BatchesPage, { query, ...options });
  }
  /**
   * Cancels an in-progress batch. The batch will be in status `cancelling` for up to
   * 10 minutes, before changing to `cancelled`, where it will have partial results
   * (if any) available in the output file.
   */
  cancel(batchId, options) {
    return this._client.post(`/batches/${batchId}/cancel`, options);
  }
};
var BatchesPage = class extends CursorPage {
};
Batches.BatchesPage = BatchesPage;

// node_modules/openai/resources/beta/assistants.mjs
var Assistants = class extends APIResource {
  /**
   * Create an assistant with a model and instructions.
   */
  create(body, options) {
    return this._client.post("/assistants", {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieves an assistant.
   */
  retrieve(assistantId, options) {
    return this._client.get(`/assistants/${assistantId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Modifies an assistant.
   */
  update(assistantId, body, options) {
    return this._client.post(`/assistants/${assistantId}`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list({}, query);
    }
    return this._client.getAPIList("/assistants", AssistantsPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Delete an assistant.
   */
  del(assistantId, options) {
    return this._client.delete(`/assistants/${assistantId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
};
var AssistantsPage = class extends CursorPage {
};
Assistants.AssistantsPage = AssistantsPage;

// node_modules/openai/lib/RunnableFunction.mjs
function isRunnableFunctionWithParse(fn) {
  return typeof fn.parse === "function";
}

// node_modules/openai/lib/chatCompletionUtils.mjs
var isAssistantMessage = (message) => {
  return message?.role === "assistant";
};
var isFunctionMessage = (message) => {
  return message?.role === "function";
};
var isToolMessage3 = (message) => {
  return message?.role === "tool";
};

// node_modules/openai/lib/EventStream.mjs
var __classPrivateFieldSet7 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet7 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _EventStream_instances;
var _EventStream_connectedPromise;
var _EventStream_resolveConnectedPromise;
var _EventStream_rejectConnectedPromise;
var _EventStream_endPromise;
var _EventStream_resolveEndPromise;
var _EventStream_rejectEndPromise;
var _EventStream_listeners;
var _EventStream_ended;
var _EventStream_errored;
var _EventStream_aborted;
var _EventStream_catchingPromiseCreated;
var _EventStream_handleError;
var EventStream = class {
  constructor() {
    _EventStream_instances.add(this);
    this.controller = new AbortController();
    _EventStream_connectedPromise.set(this, void 0);
    _EventStream_resolveConnectedPromise.set(this, () => {
    });
    _EventStream_rejectConnectedPromise.set(this, () => {
    });
    _EventStream_endPromise.set(this, void 0);
    _EventStream_resolveEndPromise.set(this, () => {
    });
    _EventStream_rejectEndPromise.set(this, () => {
    });
    _EventStream_listeners.set(this, {});
    _EventStream_ended.set(this, false);
    _EventStream_errored.set(this, false);
    _EventStream_aborted.set(this, false);
    _EventStream_catchingPromiseCreated.set(this, false);
    __classPrivateFieldSet7(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet7(this, _EventStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet7(this, _EventStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet7(this, _EventStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet7(this, _EventStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet7(this, _EventStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet7(this, _EventStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet7(this, _EventStream_endPromise, "f").catch(() => {
    });
  }
  _run(executor) {
    setTimeout(() => {
      executor().then(() => {
        this._emitFinal();
        this._emit("end");
      }, __classPrivateFieldGet7(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
    }, 0);
  }
  _connected() {
    if (this.ended)
      return;
    __classPrivateFieldGet7(this, _EventStream_resolveConnectedPromise, "f").call(this);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet7(this, _EventStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet7(this, _EventStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet7(this, _EventStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet7(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet7(this, _EventStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet7(this, _EventStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index2 = listeners.findIndex((l4) => l4.listener === listener);
    if (index2 >= 0)
      listeners.splice(index2, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this ChatCompletionStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet7(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet7(this, _EventStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet7(this, _EventStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet7(this, _EventStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet7(this, _EventStream_endPromise, "f");
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet7(this, _EventStream_ended, "f")) {
      return;
    }
    if (event === "end") {
      __classPrivateFieldSet7(this, _EventStream_ended, true, "f");
      __classPrivateFieldGet7(this, _EventStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet7(this, _EventStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet7(this, _EventStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet7(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet7(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet7(this, _EventStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet7(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet7(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet7(this, _EventStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
  }
};
_EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_handleError = function _EventStream_handleError2(error) {
  __classPrivateFieldSet7(this, _EventStream_errored, true, "f");
  if (error instanceof Error && error.name === "AbortError") {
    error = new APIUserAbortError();
  }
  if (error instanceof APIUserAbortError) {
    __classPrivateFieldSet7(this, _EventStream_aborted, true, "f");
    return this._emit("abort", error);
  }
  if (error instanceof OpenAIError) {
    return this._emit("error", error);
  }
  if (error instanceof Error) {
    const openAIError = new OpenAIError(error.message);
    openAIError.cause = error;
    return this._emit("error", openAIError);
  }
  return this._emit("error", new OpenAIError(String(error)));
};

// node_modules/openai/lib/parser.mjs
function makeParseableResponseFormat(response_format, parser) {
  const obj = { ...response_format };
  Object.defineProperties(obj, {
    $brand: {
      value: "auto-parseable-response-format",
      enumerable: false
    },
    $parseRaw: {
      value: parser,
      enumerable: false
    }
  });
  return obj;
}
function isAutoParsableResponseFormat(response_format) {
  return response_format?.["$brand"] === "auto-parseable-response-format";
}
function makeParseableTool(tool2, { parser, callback }) {
  const obj = { ...tool2 };
  Object.defineProperties(obj, {
    $brand: {
      value: "auto-parseable-tool",
      enumerable: false
    },
    $parseRaw: {
      value: parser,
      enumerable: false
    },
    $callback: {
      value: callback,
      enumerable: false
    }
  });
  return obj;
}
function isAutoParsableTool(tool2) {
  return tool2?.["$brand"] === "auto-parseable-tool";
}
function maybeParseChatCompletion(completion, params) {
  if (!params || !hasAutoParseableInput(params)) {
    return {
      ...completion,
      choices: completion.choices.map((choice) => ({
        ...choice,
        message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] }
      }))
    };
  }
  return parseChatCompletion(completion, params);
}
function parseChatCompletion(completion, params) {
  const choices = completion.choices.map((choice) => {
    if (choice.finish_reason === "length") {
      throw new LengthFinishReasonError();
    }
    if (choice.finish_reason === "content_filter") {
      throw new ContentFilterFinishReasonError();
    }
    return {
      ...choice,
      message: {
        ...choice.message,
        tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [],
        parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null
      }
    };
  });
  return { ...completion, choices };
}
function parseResponseFormat(params, content) {
  if (params.response_format?.type !== "json_schema") {
    return null;
  }
  if (params.response_format?.type === "json_schema") {
    if ("$parseRaw" in params.response_format) {
      const response_format = params.response_format;
      return response_format.$parseRaw(content);
    }
    return JSON.parse(content);
  }
  return null;
}
function parseToolCall(params, toolCall) {
  const inputTool = params.tools?.find((inputTool2) => inputTool2.function?.name === toolCall.function.name);
  return {
    ...toolCall,
    function: {
      ...toolCall.function,
      parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null
    }
  };
}
function shouldParseToolCall(params, toolCall) {
  if (!params) {
    return false;
  }
  const inputTool = params.tools?.find((inputTool2) => inputTool2.function?.name === toolCall.function.name);
  return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;
}
function hasAutoParseableInput(params) {
  if (isAutoParsableResponseFormat(params.response_format)) {
    return true;
  }
  return params.tools?.some((t3) => isAutoParsableTool(t3) || t3.type === "function" && t3.function.strict === true) ?? false;
}
function validateInputTools(tools) {
  for (const tool2 of tools ?? []) {
    if (tool2.type !== "function") {
      throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool2.type}\``);
    }
    if (tool2.function.strict !== true) {
      throw new OpenAIError(`The \`${tool2.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
    }
  }
}

// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
var __classPrivateFieldGet8 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _AbstractChatCompletionRunner_instances;
var _AbstractChatCompletionRunner_getFinalContent;
var _AbstractChatCompletionRunner_getFinalMessage;
var _AbstractChatCompletionRunner_getFinalFunctionCall;
var _AbstractChatCompletionRunner_getFinalFunctionCallResult;
var _AbstractChatCompletionRunner_calculateTotalUsage;
var _AbstractChatCompletionRunner_validateParams;
var _AbstractChatCompletionRunner_stringifyFunctionCallResult;
var DEFAULT_MAX_CHAT_COMPLETIONS = 10;
var AbstractChatCompletionRunner = class extends EventStream {
  constructor() {
    super(...arguments);
    _AbstractChatCompletionRunner_instances.add(this);
    this._chatCompletions = [];
    this.messages = [];
  }
  _addChatCompletion(chatCompletion) {
    this._chatCompletions.push(chatCompletion);
    this._emit("chatCompletion", chatCompletion);
    const message = chatCompletion.choices[0]?.message;
    if (message)
      this._addMessage(message);
    return chatCompletion;
  }
  _addMessage(message, emit = true) {
    if (!("content" in message))
      message.content = null;
    this.messages.push(message);
    if (emit) {
      this._emit("message", message);
      if ((isFunctionMessage(message) || isToolMessage3(message)) && message.content) {
        this._emit("functionCallResult", message.content);
      } else if (isAssistantMessage(message) && message.function_call) {
        this._emit("functionCall", message.function_call);
      } else if (isAssistantMessage(message) && message.tool_calls) {
        for (const tool_call of message.tool_calls) {
          if (tool_call.type === "function") {
            this._emit("functionCall", tool_call.function);
          }
        }
      }
    }
  }
  /**
   * @returns a promise that resolves with the final ChatCompletion, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
   */
  async finalChatCompletion() {
    await this.done();
    const completion = this._chatCompletions[this._chatCompletions.length - 1];
    if (!completion)
      throw new OpenAIError("stream ended without producing a ChatCompletion");
    return completion;
  }
  /**
   * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalContent() {
    await this.done();
    return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
   * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the content of the final FunctionCall, or rejects
   * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
   */
  async finalFunctionCall() {
    await this.done();
    return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
  }
  async finalFunctionCallResult() {
    await this.done();
    return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
  }
  async totalUsage() {
    await this.done();
    return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
  }
  allChatCompletions() {
    return [...this._chatCompletions];
  }
  _emitFinal() {
    const completion = this._chatCompletions[this._chatCompletions.length - 1];
    if (completion)
      this._emit("finalChatCompletion", completion);
    const finalMessage = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
    if (finalMessage)
      this._emit("finalMessage", finalMessage);
    const finalContent = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
    if (finalContent)
      this._emit("finalContent", finalContent);
    const finalFunctionCall = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
    if (finalFunctionCall)
      this._emit("finalFunctionCall", finalFunctionCall);
    const finalFunctionCallResult = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
    if (finalFunctionCallResult != null)
      this._emit("finalFunctionCallResult", finalFunctionCallResult);
    if (this._chatCompletions.some((c4) => c4.usage)) {
      this._emit("totalUsage", __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
    }
  }
  async _createChatCompletion(client2, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
    const chatCompletion = await client2.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
    this._connected();
    return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
  }
  async _runChatCompletion(client2, params, options) {
    for (const message of params.messages) {
      this._addMessage(message, false);
    }
    return await this._createChatCompletion(client2, params, options);
  }
  async _runFunctions(client2, params, options) {
    const role = "function";
    const { function_call = "auto", stream, ...restParams } = params;
    const singleFunctionToCall = typeof function_call !== "string" && function_call?.name;
    const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
    const functionsByName = {};
    for (const f3 of params.functions) {
      functionsByName[f3.name || f3.function.name] = f3;
    }
    const functions = params.functions.map((f3) => ({
      name: f3.name || f3.function.name,
      parameters: f3.parameters,
      description: f3.description
    }));
    for (const message of params.messages) {
      this._addMessage(message, false);
    }
    for (let i3 = 0; i3 < maxChatCompletions; ++i3) {
      const chatCompletion = await this._createChatCompletion(client2, {
        ...restParams,
        function_call,
        functions,
        messages: [...this.messages]
      }, options);
      const message = chatCompletion.choices[0]?.message;
      if (!message) {
        throw new OpenAIError(`missing message in ChatCompletion response`);
      }
      if (!message.function_call)
        return;
      const { name, arguments: args } = message.function_call;
      const fn = functionsByName[name];
      if (!fn) {
        const content2 = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f3) => JSON.stringify(f3.name)).join(", ")}. Please try again`;
        this._addMessage({ role, name, content: content2 });
        continue;
      } else if (singleFunctionToCall && singleFunctionToCall !== name) {
        const content2 = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
        this._addMessage({ role, name, content: content2 });
        continue;
      }
      let parsed;
      try {
        parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
      } catch (error) {
        this._addMessage({
          role,
          name,
          content: error instanceof Error ? error.message : String(error)
        });
        continue;
      }
      const rawContent = await fn.function(parsed, this);
      const content = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
      this._addMessage({ role, name, content });
      if (singleFunctionToCall)
        return;
    }
  }
  async _runTools(client2, params, options) {
    const role = "tool";
    const { tool_choice = "auto", stream, ...restParams } = params;
    const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice?.function?.name;
    const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
    const inputTools = params.tools.map((tool2) => {
      if (isAutoParsableTool(tool2)) {
        if (!tool2.$callback) {
          throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
        }
        return {
          type: "function",
          function: {
            function: tool2.$callback,
            name: tool2.function.name,
            description: tool2.function.description || "",
            parameters: tool2.function.parameters,
            parse: tool2.$parseRaw,
            strict: true
          }
        };
      }
      return tool2;
    });
    const functionsByName = {};
    for (const f3 of inputTools) {
      if (f3.type === "function") {
        functionsByName[f3.function.name || f3.function.function.name] = f3.function;
      }
    }
    const tools = "tools" in params ? inputTools.map((t3) => t3.type === "function" ? {
      type: "function",
      function: {
        name: t3.function.name || t3.function.function.name,
        parameters: t3.function.parameters,
        description: t3.function.description,
        strict: t3.function.strict
      }
    } : t3) : void 0;
    for (const message of params.messages) {
      this._addMessage(message, false);
    }
    for (let i3 = 0; i3 < maxChatCompletions; ++i3) {
      const chatCompletion = await this._createChatCompletion(client2, {
        ...restParams,
        tool_choice,
        tools,
        messages: [...this.messages]
      }, options);
      const message = chatCompletion.choices[0]?.message;
      if (!message) {
        throw new OpenAIError(`missing message in ChatCompletion response`);
      }
      if (!message.tool_calls?.length) {
        return;
      }
      for (const tool_call of message.tool_calls) {
        if (tool_call.type !== "function")
          continue;
        const tool_call_id = tool_call.id;
        const { name, arguments: args } = tool_call.function;
        const fn = functionsByName[name];
        if (!fn) {
          const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        } else if (singleFunctionToCall && singleFunctionToCall !== name) {
          const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        }
        let parsed;
        try {
          parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
        } catch (error) {
          const content2 = error instanceof Error ? error.message : String(error);
          this._addMessage({ role, tool_call_id, content: content2 });
          continue;
        }
        const rawContent = await fn.function(parsed, this);
        const content = __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
        this._addMessage({ role, tool_call_id, content });
        if (singleFunctionToCall) {
          return;
        }
      }
    }
    return;
  }
};
_AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() {
  return __classPrivateFieldGet8(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
  let i3 = this.messages.length;
  while (i3-- > 0) {
    const message = this.messages[i3];
    if (isAssistantMessage(message)) {
      const { function_call, ...rest } = message;
      const ret = {
        ...rest,
        content: message.content ?? null,
        refusal: message.refusal ?? null
      };
      if (function_call) {
        ret.function_call = function_call;
      }
      return ret;
    }
  }
  throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall2() {
  for (let i3 = this.messages.length - 1; i3 >= 0; i3--) {
    const message = this.messages[i3];
    if (isAssistantMessage(message) && message?.function_call) {
      return message.function_call;
    }
    if (isAssistantMessage(message) && message?.tool_calls?.length) {
      return message.tool_calls.at(-1)?.function;
    }
  }
  return;
}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult2() {
  for (let i3 = this.messages.length - 1; i3 >= 0; i3--) {
    const message = this.messages[i3];
    if (isFunctionMessage(message) && message.content != null) {
      return message.content;
    }
    if (isToolMessage3(message) && message.content != null && typeof message.content === "string" && this.messages.some((x2) => x2.role === "assistant" && x2.tool_calls?.some((y2) => y2.type === "function" && y2.id === message.tool_call_id))) {
      return message.content;
    }
  }
  return;
}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() {
  const total = {
    completion_tokens: 0,
    prompt_tokens: 0,
    total_tokens: 0
  };
  for (const { usage } of this._chatCompletions) {
    if (usage) {
      total.completion_tokens += usage.completion_tokens;
      total.prompt_tokens += usage.prompt_tokens;
      total.total_tokens += usage.total_tokens;
    }
  }
  return total;
}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) {
  if (params.n != null && params.n > 1) {
    throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
  }
}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
  return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent);
};

// node_modules/openai/lib/ChatCompletionRunner.mjs
var ChatCompletionRunner = class extends AbstractChatCompletionRunner {
  /** @deprecated - please use `runTools` instead. */
  static runFunctions(client2, params, options) {
    const runner = new ChatCompletionRunner();
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" }
    };
    runner._run(() => runner._runFunctions(client2, params, opts));
    return runner;
  }
  static runTools(client2, params, options) {
    const runner = new ChatCompletionRunner();
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
    };
    runner._run(() => runner._runTools(client2, params, opts));
    return runner;
  }
  _addMessage(message, emit = true) {
    super._addMessage(message, emit);
    if (isAssistantMessage(message) && message.content) {
      this._emit("content", message.content);
    }
  }
};

// node_modules/openai/_vendor/partial-json-parser/parser.mjs
var STR = 1;
var NUM = 2;
var ARR = 4;
var OBJ = 8;
var NULL = 16;
var BOOL = 32;
var NAN = 64;
var INFINITY = 128;
var MINUS_INFINITY = 256;
var INF = INFINITY | MINUS_INFINITY;
var SPECIAL = NULL | BOOL | INF | NAN;
var ATOM = STR | NUM | SPECIAL;
var COLLECTION = ARR | OBJ;
var ALL = ATOM | COLLECTION;
var Allow = {
  STR,
  NUM,
  ARR,
  OBJ,
  NULL,
  BOOL,
  NAN,
  INFINITY,
  MINUS_INFINITY,
  INF,
  SPECIAL,
  ATOM,
  COLLECTION,
  ALL
};
var PartialJSON = class extends Error {
};
var MalformedJSON = class extends Error {
};
function parseJSON2(jsonString, allowPartial = Allow.ALL) {
  if (typeof jsonString !== "string") {
    throw new TypeError(`expecting str, got ${typeof jsonString}`);
  }
  if (!jsonString.trim()) {
    throw new Error(`${jsonString} is empty`);
  }
  return _parseJSON(jsonString.trim(), allowPartial);
}
var _parseJSON = (jsonString, allow) => {
  const length = jsonString.length;
  let index2 = 0;
  const markPartialJSON = (msg) => {
    throw new PartialJSON(`${msg} at position ${index2}`);
  };
  const throwMalformedError = (msg) => {
    throw new MalformedJSON(`${msg} at position ${index2}`);
  };
  const parseAny = () => {
    skipBlank();
    if (index2 >= length)
      markPartialJSON("Unexpected end of input");
    if (jsonString[index2] === '"')
      return parseStr();
    if (jsonString[index2] === "{")
      return parseObj();
    if (jsonString[index2] === "[")
      return parseArr();
    if (jsonString.substring(index2, index2 + 4) === "null" || Allow.NULL & allow && length - index2 < 4 && "null".startsWith(jsonString.substring(index2))) {
      index2 += 4;
      return null;
    }
    if (jsonString.substring(index2, index2 + 4) === "true" || Allow.BOOL & allow && length - index2 < 4 && "true".startsWith(jsonString.substring(index2))) {
      index2 += 4;
      return true;
    }
    if (jsonString.substring(index2, index2 + 5) === "false" || Allow.BOOL & allow && length - index2 < 5 && "false".startsWith(jsonString.substring(index2))) {
      index2 += 5;
      return false;
    }
    if (jsonString.substring(index2, index2 + 8) === "Infinity" || Allow.INFINITY & allow && length - index2 < 8 && "Infinity".startsWith(jsonString.substring(index2))) {
      index2 += 8;
      return Infinity;
    }
    if (jsonString.substring(index2, index2 + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index2 && length - index2 < 9 && "-Infinity".startsWith(jsonString.substring(index2))) {
      index2 += 9;
      return -Infinity;
    }
    if (jsonString.substring(index2, index2 + 3) === "NaN" || Allow.NAN & allow && length - index2 < 3 && "NaN".startsWith(jsonString.substring(index2))) {
      index2 += 3;
      return NaN;
    }
    return parseNum();
  };
  const parseStr = () => {
    const start = index2;
    let escape2 = false;
    index2++;
    while (index2 < length && (jsonString[index2] !== '"' || escape2 && jsonString[index2 - 1] === "\\")) {
      escape2 = jsonString[index2] === "\\" ? !escape2 : false;
      index2++;
    }
    if (jsonString.charAt(index2) == '"') {
      try {
        return JSON.parse(jsonString.substring(start, ++index2 - Number(escape2)));
      } catch (e3) {
        throwMalformedError(String(e3));
      }
    } else if (Allow.STR & allow) {
      try {
        return JSON.parse(jsonString.substring(start, index2 - Number(escape2)) + '"');
      } catch (e3) {
        return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
      }
    }
    markPartialJSON("Unterminated string literal");
  };
  const parseObj = () => {
    index2++;
    skipBlank();
    const obj = {};
    try {
      while (jsonString[index2] !== "}") {
        skipBlank();
        if (index2 >= length && Allow.OBJ & allow)
          return obj;
        const key = parseStr();
        skipBlank();
        index2++;
        try {
          const value = parseAny();
          Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
        } catch (e3) {
          if (Allow.OBJ & allow)
            return obj;
          else
            throw e3;
        }
        skipBlank();
        if (jsonString[index2] === ",")
          index2++;
      }
    } catch (e3) {
      if (Allow.OBJ & allow)
        return obj;
      else
        markPartialJSON("Expected '}' at end of object");
    }
    index2++;
    return obj;
  };
  const parseArr = () => {
    index2++;
    const arr2 = [];
    try {
      while (jsonString[index2] !== "]") {
        arr2.push(parseAny());
        skipBlank();
        if (jsonString[index2] === ",") {
          index2++;
        }
      }
    } catch (e3) {
      if (Allow.ARR & allow) {
        return arr2;
      }
      markPartialJSON("Expected ']' at end of array");
    }
    index2++;
    return arr2;
  };
  const parseNum = () => {
    if (index2 === 0) {
      if (jsonString === "-" && Allow.NUM & allow)
        markPartialJSON("Not sure what '-' is");
      try {
        return JSON.parse(jsonString);
      } catch (e3) {
        if (Allow.NUM & allow) {
          try {
            if ("." === jsonString[jsonString.length - 1])
              return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
            return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
          } catch (e4) {
          }
        }
        throwMalformedError(String(e3));
      }
    }
    const start = index2;
    if (jsonString[index2] === "-")
      index2++;
    while (jsonString[index2] && !",]}".includes(jsonString[index2]))
      index2++;
    if (index2 == length && !(Allow.NUM & allow))
      markPartialJSON("Unterminated number literal");
    try {
      return JSON.parse(jsonString.substring(start, index2));
    } catch (e3) {
      if (jsonString.substring(start, index2) === "-" && Allow.NUM & allow)
        markPartialJSON("Not sure what '-' is");
      try {
        return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
      } catch (e4) {
        throwMalformedError(String(e4));
      }
    }
  };
  const skipBlank = () => {
    while (index2 < length && " \n\r	".includes(jsonString[index2])) {
      index2++;
    }
  };
  return parseAny();
};
var partialParse = (input) => parseJSON2(input, Allow.ALL ^ Allow.NUM);

// node_modules/openai/lib/ChatCompletionStream.mjs
var __classPrivateFieldSet8 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet9 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _ChatCompletionStream_instances;
var _ChatCompletionStream_params;
var _ChatCompletionStream_choiceEventStates;
var _ChatCompletionStream_currentChatCompletionSnapshot;
var _ChatCompletionStream_beginRequest;
var _ChatCompletionStream_getChoiceEventState;
var _ChatCompletionStream_addChunk;
var _ChatCompletionStream_emitToolCallDoneEvent;
var _ChatCompletionStream_emitContentDoneEvents;
var _ChatCompletionStream_endRequest;
var _ChatCompletionStream_getAutoParseableResponseFormat;
var _ChatCompletionStream_accumulateChatCompletion;
var ChatCompletionStream = class extends AbstractChatCompletionRunner {
  constructor(params) {
    super();
    _ChatCompletionStream_instances.add(this);
    _ChatCompletionStream_params.set(this, void 0);
    _ChatCompletionStream_choiceEventStates.set(this, void 0);
    _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
    __classPrivateFieldSet8(this, _ChatCompletionStream_params, params, "f");
    __classPrivateFieldSet8(this, _ChatCompletionStream_choiceEventStates, [], "f");
  }
  get currentChatCompletionSnapshot() {
    return __classPrivateFieldGet9(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream) {
    const runner = new ChatCompletionStream(null);
    runner._run(() => runner._fromReadableStream(stream));
    return runner;
  }
  static createChatCompletion(client2, params, options) {
    const runner = new ChatCompletionStream(params);
    runner._run(() => runner._runChatCompletion(client2, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  async _createChatCompletion(client2, params, options) {
    super._createChatCompletion;
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
    const stream = await client2.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const chunk of stream) {
      __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addChatCompletion(__classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
    this._connected();
    const stream = Stream.fromReadableStream(readableStream, this.controller);
    let chatId;
    for await (const chunk of stream) {
      if (chatId && chatId !== chunk.id) {
        this._addChatCompletion(__classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
      }
      __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
      chatId = chunk.id;
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addChatCompletion(__classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
  }
  [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet8(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
  }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
    let state = __classPrivateFieldGet9(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
    if (state) {
      return state;
    }
    state = {
      content_done: false,
      refusal_done: false,
      logprobs_content_done: false,
      logprobs_refusal_done: false,
      done_tool_calls: /* @__PURE__ */ new Set(),
      current_tool_call_index: null
    };
    __classPrivateFieldGet9(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
    return state;
  }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
    if (this.ended)
      return;
    const completion = __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
    this._emit("chunk", chunk, completion);
    for (const choice of chunk.choices) {
      const choiceSnapshot = completion.choices[choice.index];
      if (choice.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
        this._emit("content", choice.delta.content, choiceSnapshot.message.content);
        this._emit("content.delta", {
          delta: choice.delta.content,
          snapshot: choiceSnapshot.message.content,
          parsed: choiceSnapshot.message.parsed
        });
      }
      if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
        this._emit("refusal.delta", {
          delta: choice.delta.refusal,
          snapshot: choiceSnapshot.message.refusal
        });
      }
      if (choice.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") {
        this._emit("logprobs.content.delta", {
          content: choice.logprobs?.content,
          snapshot: choiceSnapshot.logprobs?.content ?? []
        });
      }
      if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") {
        this._emit("logprobs.refusal.delta", {
          refusal: choice.logprobs?.refusal,
          snapshot: choiceSnapshot.logprobs?.refusal ?? []
        });
      }
      const state = __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
      if (choiceSnapshot.finish_reason) {
        __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
        if (state.current_tool_call_index != null) {
          __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
        }
      }
      for (const toolCall of choice.delta.tool_calls ?? []) {
        if (state.current_tool_call_index !== toolCall.index) {
          __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
          if (state.current_tool_call_index != null) {
            __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
          }
        }
        state.current_tool_call_index = toolCall.index;
      }
      for (const toolCallDelta of choice.delta.tool_calls ?? []) {
        const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
        if (!toolCallSnapshot?.type) {
          continue;
        }
        if (toolCallSnapshot?.type === "function") {
          this._emit("tool_calls.function.arguments.delta", {
            name: toolCallSnapshot.function?.name,
            index: toolCallDelta.index,
            arguments: toolCallSnapshot.function.arguments,
            parsed_arguments: toolCallSnapshot.function.parsed_arguments,
            arguments_delta: toolCallDelta.function?.arguments ?? ""
          });
        } else {
          assertNever(toolCallSnapshot?.type);
        }
      }
    }
  }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
    const state = __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
    if (state.done_tool_calls.has(toolCallIndex)) {
      return;
    }
    const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];
    if (!toolCallSnapshot) {
      throw new Error("no tool call snapshot");
    }
    if (!toolCallSnapshot.type) {
      throw new Error("tool call snapshot missing `type`");
    }
    if (toolCallSnapshot.type === "function") {
      const inputTool = __classPrivateFieldGet9(this, _ChatCompletionStream_params, "f")?.tools?.find((tool2) => tool2.type === "function" && tool2.function.name === toolCallSnapshot.function.name);
      this._emit("tool_calls.function.arguments.done", {
        name: toolCallSnapshot.function.name,
        index: toolCallIndex,
        arguments: toolCallSnapshot.function.arguments,
        parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null
      });
    } else {
      assertNever(toolCallSnapshot.type);
    }
  }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
    const state = __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
    if (choiceSnapshot.message.content && !state.content_done) {
      state.content_done = true;
      const responseFormat = __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
      this._emit("content.done", {
        content: choiceSnapshot.message.content,
        parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null
      });
    }
    if (choiceSnapshot.message.refusal && !state.refusal_done) {
      state.refusal_done = true;
      this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal });
    }
    if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {
      state.logprobs_content_done = true;
      this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
    }
    if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {
      state.logprobs_refusal_done = true;
      this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
    }
  }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() {
    if (this.ended) {
      throw new OpenAIError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet9(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
    if (!snapshot) {
      throw new OpenAIError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet8(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
    __classPrivateFieldSet8(this, _ChatCompletionStream_choiceEventStates, [], "f");
    return finalizeChatCompletion(snapshot, __classPrivateFieldGet9(this, _ChatCompletionStream_params, "f"));
  }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() {
    const responseFormat = __classPrivateFieldGet9(this, _ChatCompletionStream_params, "f")?.response_format;
    if (isAutoParsableResponseFormat(responseFormat)) {
      return responseFormat;
    }
    return null;
  }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
    var _a5, _b, _c, _d;
    let snapshot = __classPrivateFieldGet9(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
    const { choices, ...rest } = chunk;
    if (!snapshot) {
      snapshot = __classPrivateFieldSet8(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
        ...rest,
        choices: []
      }, "f");
    } else {
      Object.assign(snapshot, rest);
    }
    for (const { delta, finish_reason, index: index2, logprobs = null, ...other } of chunk.choices) {
      let choice = snapshot.choices[index2];
      if (!choice) {
        choice = snapshot.choices[index2] = { finish_reason, index: index2, message: {}, logprobs, ...other };
      }
      if (logprobs) {
        if (!choice.logprobs) {
          choice.logprobs = Object.assign({}, logprobs);
        } else {
          const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
          assertIsEmpty(rest3);
          Object.assign(choice.logprobs, rest3);
          if (content2) {
            (_a5 = choice.logprobs).content ?? (_a5.content = []);
            choice.logprobs.content.push(...content2);
          }
          if (refusal2) {
            (_b = choice.logprobs).refusal ?? (_b.refusal = []);
            choice.logprobs.refusal.push(...refusal2);
          }
        }
      }
      if (finish_reason) {
        choice.finish_reason = finish_reason;
        if (__classPrivateFieldGet9(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet9(this, _ChatCompletionStream_params, "f"))) {
          if (finish_reason === "length") {
            throw new LengthFinishReasonError();
          }
          if (finish_reason === "content_filter") {
            throw new ContentFilterFinishReasonError();
          }
        }
      }
      Object.assign(choice, other);
      if (!delta)
        continue;
      const { content, refusal, function_call, role, tool_calls, ...rest2 } = delta;
      assertIsEmpty(rest2);
      Object.assign(choice.message, rest2);
      if (refusal) {
        choice.message.refusal = (choice.message.refusal || "") + refusal;
      }
      if (role)
        choice.message.role = role;
      if (function_call) {
        if (!choice.message.function_call) {
          choice.message.function_call = function_call;
        } else {
          if (function_call.name)
            choice.message.function_call.name = function_call.name;
          if (function_call.arguments) {
            (_c = choice.message.function_call).arguments ?? (_c.arguments = "");
            choice.message.function_call.arguments += function_call.arguments;
          }
        }
      }
      if (content) {
        choice.message.content = (choice.message.content || "") + content;
        if (!choice.message.refusal && __classPrivateFieldGet9(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
          choice.message.parsed = partialParse(choice.message.content);
        }
      }
      if (tool_calls) {
        if (!choice.message.tool_calls)
          choice.message.tool_calls = [];
        for (const { index: index3, id, type, function: fn, ...rest3 } of tool_calls) {
          const tool_call = (_d = choice.message.tool_calls)[index3] ?? (_d[index3] = {});
          Object.assign(tool_call, rest3);
          if (id)
            tool_call.id = id;
          if (type)
            tool_call.type = type;
          if (fn)
            tool_call.function ?? (tool_call.function = { name: fn.name ?? "", arguments: "" });
          if (fn?.name)
            tool_call.function.name = fn.name;
          if (fn?.arguments) {
            tool_call.function.arguments += fn.arguments;
            if (shouldParseToolCall(__classPrivateFieldGet9(this, _ChatCompletionStream_params, "f"), tool_call)) {
              tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);
            }
          }
        }
      }
    }
    return snapshot;
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("chunk", (chunk) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(chunk);
      } else {
        pushQueue.push(chunk);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream.toReadableStream();
  }
};
function finalizeChatCompletion(snapshot, params) {
  const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
  const completion = {
    ...rest,
    id,
    choices: choices.map(({ message, finish_reason, index: index2, logprobs, ...choiceRest }) => {
      if (!finish_reason) {
        throw new OpenAIError(`missing finish_reason for choice ${index2}`);
      }
      const { content = null, function_call, tool_calls, ...messageRest } = message;
      const role = message.role;
      if (!role) {
        throw new OpenAIError(`missing role for choice ${index2}`);
      }
      if (function_call) {
        const { arguments: args, name } = function_call;
        if (args == null) {
          throw new OpenAIError(`missing function_call.arguments for choice ${index2}`);
        }
        if (!name) {
          throw new OpenAIError(`missing function_call.name for choice ${index2}`);
        }
        return {
          ...choiceRest,
          message: {
            content,
            function_call: { arguments: args, name },
            role,
            refusal: message.refusal ?? null
          },
          finish_reason,
          index: index2,
          logprobs
        };
      }
      if (tool_calls) {
        return {
          ...choiceRest,
          index: index2,
          finish_reason,
          logprobs,
          message: {
            ...messageRest,
            role,
            content,
            refusal: message.refusal ?? null,
            tool_calls: tool_calls.map((tool_call, i3) => {
              const { function: fn, type, id: id2, ...toolRest } = tool_call;
              const { arguments: args, name, ...fnRest } = fn || {};
              if (id2 == null) {
                throw new OpenAIError(`missing choices[${index2}].tool_calls[${i3}].id
${str(snapshot)}`);
              }
              if (type == null) {
                throw new OpenAIError(`missing choices[${index2}].tool_calls[${i3}].type
${str(snapshot)}`);
              }
              if (name == null) {
                throw new OpenAIError(`missing choices[${index2}].tool_calls[${i3}].function.name
${str(snapshot)}`);
              }
              if (args == null) {
                throw new OpenAIError(`missing choices[${index2}].tool_calls[${i3}].function.arguments
${str(snapshot)}`);
              }
              return { ...toolRest, id: id2, type, function: { ...fnRest, name, arguments: args } };
            })
          }
        };
      }
      return {
        ...choiceRest,
        message: { ...messageRest, content, role, refusal: message.refusal ?? null },
        finish_reason,
        index: index2,
        logprobs
      };
    }),
    created,
    model,
    object: "chat.completion",
    ...system_fingerprint ? { system_fingerprint } : {}
  };
  return maybeParseChatCompletion(completion, params);
}
function str(x2) {
  return JSON.stringify(x2);
}
function assertIsEmpty(obj) {
  return;
}
function assertNever(_x) {
}

// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
var ChatCompletionStreamingRunner = class extends ChatCompletionStream {
  static fromReadableStream(stream) {
    const runner = new ChatCompletionStreamingRunner(null);
    runner._run(() => runner._fromReadableStream(stream));
    return runner;
  }
  /** @deprecated - please use `runTools` instead. */
  static runFunctions(client2, params, options) {
    const runner = new ChatCompletionStreamingRunner(null);
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" }
    };
    runner._run(() => runner._runFunctions(client2, params, opts));
    return runner;
  }
  static runTools(client2, params, options) {
    const runner = new ChatCompletionStreamingRunner(
      // @ts-expect-error TODO these types are incompatible
      params
    );
    const opts = {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
    };
    runner._run(() => runner._runTools(client2, params, opts));
    return runner;
  }
};

// node_modules/openai/resources/beta/chat/completions.mjs
var Completions2 = class extends APIResource {
  parse(body, options) {
    validateInputTools(body.tools);
    return this._client.chat.completions.create(body, {
      ...options,
      headers: {
        ...options?.headers,
        "X-Stainless-Helper-Method": "beta.chat.completions.parse"
      }
    })._thenUnwrap((completion) => parseChatCompletion(completion, body));
  }
  runFunctions(body, options) {
    if (body.stream) {
      return ChatCompletionStreamingRunner.runFunctions(this._client, body, options);
    }
    return ChatCompletionRunner.runFunctions(this._client, body, options);
  }
  runTools(body, options) {
    if (body.stream) {
      return ChatCompletionStreamingRunner.runTools(this._client, body, options);
    }
    return ChatCompletionRunner.runTools(this._client, body, options);
  }
  /**
   * Creates a chat completion stream
   */
  stream(body, options) {
    return ChatCompletionStream.createChatCompletion(this._client, body, options);
  }
};

// node_modules/openai/resources/beta/chat/chat.mjs
var Chat2 = class extends APIResource {
  constructor() {
    super(...arguments);
    this.completions = new Completions2(this._client);
  }
};
(function(Chat5) {
  Chat5.Completions = Completions2;
})(Chat2 || (Chat2 = {}));

// node_modules/openai/lib/AssistantStream.mjs
var __classPrivateFieldGet10 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var __classPrivateFieldSet9 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var _AssistantStream_instances;
var _AssistantStream_events;
var _AssistantStream_runStepSnapshots;
var _AssistantStream_messageSnapshots;
var _AssistantStream_messageSnapshot;
var _AssistantStream_finalRun;
var _AssistantStream_currentContentIndex;
var _AssistantStream_currentContent;
var _AssistantStream_currentToolCallIndex;
var _AssistantStream_currentToolCall;
var _AssistantStream_currentEvent;
var _AssistantStream_currentRunSnapshot;
var _AssistantStream_currentRunStepSnapshot;
var _AssistantStream_addEvent;
var _AssistantStream_endRequest;
var _AssistantStream_handleMessage;
var _AssistantStream_handleRunStep;
var _AssistantStream_handleEvent;
var _AssistantStream_accumulateRunStep;
var _AssistantStream_accumulateMessage;
var _AssistantStream_accumulateContent;
var _AssistantStream_handleRun;
var AssistantStream = class extends EventStream {
  constructor() {
    super(...arguments);
    _AssistantStream_instances.add(this);
    _AssistantStream_events.set(this, []);
    _AssistantStream_runStepSnapshots.set(this, {});
    _AssistantStream_messageSnapshots.set(this, {});
    _AssistantStream_messageSnapshot.set(this, void 0);
    _AssistantStream_finalRun.set(this, void 0);
    _AssistantStream_currentContentIndex.set(this, void 0);
    _AssistantStream_currentContent.set(this, void 0);
    _AssistantStream_currentToolCallIndex.set(this, void 0);
    _AssistantStream_currentToolCall.set(this, void 0);
    _AssistantStream_currentEvent.set(this, void 0);
    _AssistantStream_currentRunSnapshot.set(this, void 0);
    _AssistantStream_currentRunStepSnapshot.set(this, void 0);
  }
  [(_AssistantStream_events = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("event", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  static fromReadableStream(stream) {
    const runner = new AssistantStream();
    runner._run(() => runner._fromReadableStream(stream));
    return runner;
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    this._connected();
    const stream = Stream.fromReadableStream(readableStream, this.controller);
    for await (const event of stream) {
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addRun(__classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  toReadableStream() {
    const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream.toReadableStream();
  }
  static createToolAssistantStream(threadId, runId, runs, params, options) {
    const runner = new AssistantStream();
    runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  async _createToolAssistantStream(run, threadId, runId, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream = await run.submitToolOutputs(threadId, runId, body, {
      ...options,
      signal: this.controller.signal
    });
    this._connected();
    for await (const event of stream) {
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addRun(__classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  static createThreadAssistantStream(params, thread, options) {
    const runner = new AssistantStream();
    runner._run(() => runner._threadAssistantStream(params, thread, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  static createAssistantStream(threadId, runs, params, options) {
    const runner = new AssistantStream();
    runner._run(() => runner._runAssistantStream(threadId, runs, params, {
      ...options,
      headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" }
    }));
    return runner;
  }
  currentEvent() {
    return __classPrivateFieldGet10(this, _AssistantStream_currentEvent, "f");
  }
  currentRun() {
    return __classPrivateFieldGet10(this, _AssistantStream_currentRunSnapshot, "f");
  }
  currentMessageSnapshot() {
    return __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f");
  }
  currentRunStepSnapshot() {
    return __classPrivateFieldGet10(this, _AssistantStream_currentRunStepSnapshot, "f");
  }
  async finalRunSteps() {
    await this.done();
    return Object.values(__classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f"));
  }
  async finalMessages() {
    await this.done();
    return Object.values(__classPrivateFieldGet10(this, _AssistantStream_messageSnapshots, "f"));
  }
  async finalRun() {
    await this.done();
    if (!__classPrivateFieldGet10(this, _AssistantStream_finalRun, "f"))
      throw Error("Final run was not received.");
    return __classPrivateFieldGet10(this, _AssistantStream_finalRun, "f");
  }
  async _createThreadAssistantStream(thread, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream) {
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addRun(__classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  async _createAssistantStream(run, threadId, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    const body = { ...params, stream: true };
    const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream) {
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError();
    }
    return this._addRun(__classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
  }
  static accumulateDelta(acc, delta) {
    for (const [key, deltaValue] of Object.entries(delta)) {
      if (!acc.hasOwnProperty(key)) {
        acc[key] = deltaValue;
        continue;
      }
      let accValue = acc[key];
      if (accValue === null || accValue === void 0) {
        acc[key] = deltaValue;
        continue;
      }
      if (key === "index" || key === "type") {
        acc[key] = deltaValue;
        continue;
      }
      if (typeof accValue === "string" && typeof deltaValue === "string") {
        accValue += deltaValue;
      } else if (typeof accValue === "number" && typeof deltaValue === "number") {
        accValue += deltaValue;
      } else if (isObj(accValue) && isObj(deltaValue)) {
        accValue = this.accumulateDelta(accValue, deltaValue);
      } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {
        if (accValue.every((x2) => typeof x2 === "string" || typeof x2 === "number")) {
          accValue.push(...deltaValue);
          continue;
        }
        for (const deltaEntry of deltaValue) {
          if (!isObj(deltaEntry)) {
            throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);
          }
          const index2 = deltaEntry["index"];
          if (index2 == null) {
            console.error(deltaEntry);
            throw new Error("Expected array delta entry to have an `index` property");
          }
          if (typeof index2 !== "number") {
            throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index2}`);
          }
          const accEntry = accValue[index2];
          if (accEntry == null) {
            accValue.push(deltaEntry);
          } else {
            accValue[index2] = this.accumulateDelta(accEntry, deltaEntry);
          }
        }
        continue;
      } else {
        throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);
      }
      acc[key] = accValue;
    }
    return acc;
  }
  _addRun(run) {
    return run;
  }
  async _threadAssistantStream(params, thread, options) {
    return await this._createThreadAssistantStream(thread, params, options);
  }
  async _runAssistantStream(threadId, runs, params, options) {
    return await this._createAssistantStream(runs, threadId, params, options);
  }
  async _runToolAssistantStream(threadId, runId, runs, params, options) {
    return await this._createToolAssistantStream(runs, threadId, runId, params, options);
  }
};
_AssistantStream_addEvent = function _AssistantStream_addEvent2(event) {
  if (this.ended)
    return;
  __classPrivateFieldSet9(this, _AssistantStream_currentEvent, event, "f");
  __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
  switch (event.event) {
    case "thread.created":
      break;
    case "thread.run.created":
    case "thread.run.queued":
    case "thread.run.in_progress":
    case "thread.run.requires_action":
    case "thread.run.completed":
    case "thread.run.failed":
    case "thread.run.cancelling":
    case "thread.run.cancelled":
    case "thread.run.expired":
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
      break;
    case "thread.run.step.created":
    case "thread.run.step.in_progress":
    case "thread.run.step.delta":
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
      break;
    case "thread.message.created":
    case "thread.message.in_progress":
    case "thread.message.delta":
    case "thread.message.completed":
    case "thread.message.incomplete":
      __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
      break;
    case "error":
      throw new Error("Encountered an error event in event processing - errors should be processed earlier");
  }
}, _AssistantStream_endRequest = function _AssistantStream_endRequest2() {
  if (this.ended) {
    throw new OpenAIError(`stream has ended, this shouldn't happen`);
  }
  if (!__classPrivateFieldGet10(this, _AssistantStream_finalRun, "f"))
    throw Error("Final run has not been received");
  return __classPrivateFieldGet10(this, _AssistantStream_finalRun, "f");
}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) {
  const [accumulatedMessage, newContent] = __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f"));
  __classPrivateFieldSet9(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
  __classPrivateFieldGet10(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
  for (const content of newContent) {
    const snapshotContent = accumulatedMessage.content[content.index];
    if (snapshotContent?.type == "text") {
      this._emit("textCreated", snapshotContent.text);
    }
  }
  switch (event.event) {
    case "thread.message.created":
      this._emit("messageCreated", event.data);
      break;
    case "thread.message.in_progress":
      break;
    case "thread.message.delta":
      this._emit("messageDelta", event.data.delta, accumulatedMessage);
      if (event.data.delta.content) {
        for (const content of event.data.delta.content) {
          if (content.type == "text" && content.text) {
            let textDelta = content.text;
            let snapshot = accumulatedMessage.content[content.index];
            if (snapshot && snapshot.type == "text") {
              this._emit("textDelta", textDelta, snapshot.text);
            } else {
              throw Error("The snapshot associated with this text delta is not text or missing");
            }
          }
          if (content.index != __classPrivateFieldGet10(this, _AssistantStream_currentContentIndex, "f")) {
            if (__classPrivateFieldGet10(this, _AssistantStream_currentContent, "f")) {
              switch (__classPrivateFieldGet10(this, _AssistantStream_currentContent, "f").type) {
                case "text":
                  this._emit("textDone", __classPrivateFieldGet10(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f"));
                  break;
                case "image_file":
                  this._emit("imageFileDone", __classPrivateFieldGet10(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f"));
                  break;
              }
            }
            __classPrivateFieldSet9(this, _AssistantStream_currentContentIndex, content.index, "f");
          }
          __classPrivateFieldSet9(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
        }
      }
      break;
    case "thread.message.completed":
    case "thread.message.incomplete":
      if (__classPrivateFieldGet10(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
        const currentContent = event.data.content[__classPrivateFieldGet10(this, _AssistantStream_currentContentIndex, "f")];
        if (currentContent) {
          switch (currentContent.type) {
            case "image_file":
              this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f"));
              break;
            case "text":
              this._emit("textDone", currentContent.text, __classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f"));
              break;
          }
        }
      }
      if (__classPrivateFieldGet10(this, _AssistantStream_messageSnapshot, "f")) {
        this._emit("messageDone", event.data);
      }
      __classPrivateFieldSet9(this, _AssistantStream_messageSnapshot, void 0, "f");
  }
}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event) {
  const accumulatedRunStep = __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
  __classPrivateFieldSet9(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
  switch (event.event) {
    case "thread.run.step.created":
      this._emit("runStepCreated", event.data);
      break;
    case "thread.run.step.delta":
      const delta = event.data.delta;
      if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") {
        for (const toolCall of delta.step_details.tool_calls) {
          if (toolCall.index == __classPrivateFieldGet10(this, _AssistantStream_currentToolCallIndex, "f")) {
            this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
          } else {
            if (__classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f")) {
              this._emit("toolCallDone", __classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f"));
            }
            __classPrivateFieldSet9(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
            __classPrivateFieldSet9(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
            if (__classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f"))
              this._emit("toolCallCreated", __classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f"));
          }
        }
      }
      this._emit("runStepDelta", event.data.delta, accumulatedRunStep);
      break;
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
      __classPrivateFieldSet9(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
      const details = event.data.step_details;
      if (details.type == "tool_calls") {
        if (__classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f")) {
          this._emit("toolCallDone", __classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f"));
          __classPrivateFieldSet9(this, _AssistantStream_currentToolCall, void 0, "f");
        }
      }
      this._emit("runStepDone", event.data, accumulatedRunStep);
      break;
    case "thread.run.step.in_progress":
      break;
  }
}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event) {
  __classPrivateFieldGet10(this, _AssistantStream_events, "f").push(event);
  this._emit("event", event);
}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event) {
  switch (event.event) {
    case "thread.run.step.created":
      __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
      return event.data;
    case "thread.run.step.delta":
      let snapshot = __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
      if (!snapshot) {
        throw Error("Received a RunStepDelta before creation of a snapshot");
      }
      let data = event.data;
      if (data.delta) {
        const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta);
        __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
      }
      return __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
    case "thread.run.step.completed":
    case "thread.run.step.failed":
    case "thread.run.step.cancelled":
    case "thread.run.step.expired":
    case "thread.run.step.in_progress":
      __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
      break;
  }
  if (__classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
    return __classPrivateFieldGet10(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
  throw new Error("No snapshot available");
}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event, snapshot) {
  let newContent = [];
  switch (event.event) {
    case "thread.message.created":
      return [event.data, newContent];
    case "thread.message.delta":
      if (!snapshot) {
        throw Error("Received a delta with no existing snapshot (there should be one from message creation)");
      }
      let data = event.data;
      if (data.delta.content) {
        for (const contentElement of data.delta.content) {
          if (contentElement.index in snapshot.content) {
            let currentContent = snapshot.content[contentElement.index];
            snapshot.content[contentElement.index] = __classPrivateFieldGet10(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
          } else {
            snapshot.content[contentElement.index] = contentElement;
            newContent.push(contentElement);
          }
        }
      }
      return [snapshot, newContent];
    case "thread.message.in_progress":
    case "thread.message.completed":
    case "thread.message.incomplete":
      if (snapshot) {
        return [snapshot, newContent];
      } else {
        throw Error("Received thread message event with no existing snapshot");
      }
  }
  throw Error("Tried to accumulate a non-message event");
}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent) {
  return AssistantStream.accumulateDelta(currentContent, contentElement);
}, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event) {
  __classPrivateFieldSet9(this, _AssistantStream_currentRunSnapshot, event.data, "f");
  switch (event.event) {
    case "thread.run.created":
      break;
    case "thread.run.queued":
      break;
    case "thread.run.in_progress":
      break;
    case "thread.run.requires_action":
    case "thread.run.cancelled":
    case "thread.run.failed":
    case "thread.run.completed":
    case "thread.run.expired":
      __classPrivateFieldSet9(this, _AssistantStream_finalRun, event.data, "f");
      if (__classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f")) {
        this._emit("toolCallDone", __classPrivateFieldGet10(this, _AssistantStream_currentToolCall, "f"));
        __classPrivateFieldSet9(this, _AssistantStream_currentToolCall, void 0, "f");
      }
      break;
    case "thread.run.cancelling":
      break;
  }
};

// node_modules/openai/resources/beta/threads/messages.mjs
var Messages = class extends APIResource {
  /**
   * Create a message.
   */
  create(threadId, body, options) {
    return this._client.post(`/threads/${threadId}/messages`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieve a message.
   */
  retrieve(threadId, messageId, options) {
    return this._client.get(`/threads/${threadId}/messages/${messageId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Modifies a message.
   */
  update(threadId, messageId, body, options) {
    return this._client.post(`/threads/${threadId}/messages/${messageId}`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(threadId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list(threadId, {}, query);
    }
    return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Deletes a message.
   */
  del(threadId, messageId, options) {
    return this._client.delete(`/threads/${threadId}/messages/${messageId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
};
var MessagesPage = class extends CursorPage {
};
Messages.MessagesPage = MessagesPage;

// node_modules/openai/resources/beta/threads/runs/steps.mjs
var Steps = class extends APIResource {
  retrieve(threadId, runId, stepId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.retrieve(threadId, runId, stepId, {}, query);
    }
    return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(threadId, runId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list(threadId, runId, {}, query);
    }
    return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
};
var RunStepsPage = class extends CursorPage {
};
Steps.RunStepsPage = RunStepsPage;

// node_modules/openai/resources/beta/threads/runs/runs.mjs
var Runs = class extends APIResource {
  constructor() {
    super(...arguments);
    this.steps = new Steps(this._client);
  }
  create(threadId, params, options) {
    const { include, ...body } = params;
    return this._client.post(`/threads/${threadId}/runs`, {
      query: { include },
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers },
      stream: params.stream ?? false
    });
  }
  /**
   * Retrieves a run.
   */
  retrieve(threadId, runId, options) {
    return this._client.get(`/threads/${threadId}/runs/${runId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Modifies a run.
   */
  update(threadId, runId, body, options) {
    return this._client.post(`/threads/${threadId}/runs/${runId}`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(threadId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list(threadId, {}, query);
    }
    return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Cancels a run that is `in_progress`.
   */
  cancel(threadId, runId, options) {
    return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * A helper to create a run an poll for a terminal state. More information on Run
   * lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async createAndPoll(threadId, body, options) {
    const run = await this.create(threadId, body, options);
    return await this.poll(threadId, run.id, options);
  }
  /**
   * Create a Run stream
   *
   * @deprecated use `stream` instead
   */
  createAndStream(threadId, body, options) {
    return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
  }
  /**
   * A helper to poll a run status until it reaches a terminal state. More
   * information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async poll(threadId, runId, options) {
    const headers = { ...options?.headers, "X-Stainless-Poll-Helper": "true" };
    if (options?.pollIntervalMs) {
      headers["X-Stainless-Custom-Poll-Interval"] = options.pollIntervalMs.toString();
    }
    while (true) {
      const { data: run, response } = await this.retrieve(threadId, runId, {
        ...options,
        headers: { ...options?.headers, ...headers }
      }).withResponse();
      switch (run.status) {
        case "queued":
        case "in_progress":
        case "cancelling":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep(sleepInterval);
          break;
        case "requires_action":
        case "incomplete":
        case "cancelled":
        case "completed":
        case "failed":
        case "expired":
          return run;
      }
    }
  }
  /**
   * Create a Run stream
   */
  stream(threadId, body, options) {
    return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
  }
  submitToolOutputs(threadId, runId, body, options) {
    return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers },
      stream: body.stream ?? false
    });
  }
  /**
   * A helper to submit a tool output to a run and poll for a terminal run state.
   * More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async submitToolOutputsAndPoll(threadId, runId, body, options) {
    const run = await this.submitToolOutputs(threadId, runId, body, options);
    return await this.poll(threadId, run.id, options);
  }
  /**
   * Submit the tool outputs from a previous run and stream the run to a terminal
   * state. More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  submitToolOutputsStream(threadId, runId, body, options) {
    return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options);
  }
};
var RunsPage = class extends CursorPage {
};
Runs.RunsPage = RunsPage;
Runs.Steps = Steps;
Runs.RunStepsPage = RunStepsPage;

// node_modules/openai/resources/beta/threads/threads.mjs
var Threads = class extends APIResource {
  constructor() {
    super(...arguments);
    this.runs = new Runs(this._client);
    this.messages = new Messages(this._client);
  }
  create(body = {}, options) {
    if (isRequestOptions(body)) {
      return this.create({}, body);
    }
    return this._client.post("/threads", {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieves a thread.
   */
  retrieve(threadId, options) {
    return this._client.get(`/threads/${threadId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Modifies a thread.
   */
  update(threadId, body, options) {
    return this._client.post(`/threads/${threadId}`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Delete a thread.
   */
  del(threadId, options) {
    return this._client.delete(`/threads/${threadId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  createAndRun(body, options) {
    return this._client.post("/threads/runs", {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers },
      stream: body.stream ?? false
    });
  }
  /**
   * A helper to create a thread, start a run and then poll for a terminal state.
   * More information on Run lifecycles can be found here:
   * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
   */
  async createAndRunPoll(body, options) {
    const run = await this.createAndRun(body, options);
    return await this.runs.poll(run.thread_id, run.id, options);
  }
  /**
   * Create a thread and stream the run back
   */
  createAndRunStream(body, options) {
    return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);
  }
};
Threads.Runs = Runs;
Threads.RunsPage = RunsPage;
Threads.Messages = Messages;
Threads.MessagesPage = MessagesPage;

// node_modules/openai/lib/Util.mjs
var allSettledWithThrow = async (promises) => {
  const results = await Promise.allSettled(promises);
  const rejected = results.filter((result) => result.status === "rejected");
  if (rejected.length) {
    for (const result of rejected) {
      console.error(result.reason);
    }
    throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
  }
  const values = [];
  for (const result of results) {
    if (result.status === "fulfilled") {
      values.push(result.value);
    }
  }
  return values;
};

// node_modules/openai/resources/beta/vector-stores/files.mjs
var Files = class extends APIResource {
  /**
   * Create a vector store file by attaching a
   * [File](https://platform.openai.com/docs/api-reference/files) to a
   * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
   */
  create(vectorStoreId, body, options) {
    return this._client.post(`/vector_stores/${vectorStoreId}/files`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieves a vector store file.
   */
  retrieve(vectorStoreId, fileId, options) {
    return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(vectorStoreId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list(vectorStoreId, {}, query);
    }
    return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Delete a vector store file. This will remove the file from the vector store but
   * the file itself will not be deleted. To delete the file, use the
   * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
   * endpoint.
   */
  del(vectorStoreId, fileId, options) {
    return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Attach a file to the given vector store and wait for it to be processed.
   */
  async createAndPoll(vectorStoreId, body, options) {
    const file = await this.create(vectorStoreId, body, options);
    return await this.poll(vectorStoreId, file.id, options);
  }
  /**
   * Wait for the vector store file to finish processing.
   *
   * Note: this will return even if the file failed to process, you need to check
   * file.last_error and file.status to handle these cases
   */
  async poll(vectorStoreId, fileId, options) {
    const headers = { ...options?.headers, "X-Stainless-Poll-Helper": "true" };
    if (options?.pollIntervalMs) {
      headers["X-Stainless-Custom-Poll-Interval"] = options.pollIntervalMs.toString();
    }
    while (true) {
      const fileResponse = await this.retrieve(vectorStoreId, fileId, {
        ...options,
        headers
      }).withResponse();
      const file = fileResponse.data;
      switch (file.status) {
        case "in_progress":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep(sleepInterval);
          break;
        case "failed":
        case "completed":
          return file;
      }
    }
  }
  /**
   * Upload a file to the `files` API and then attach it to the given vector store.
   *
   * Note the file will be asynchronously processed (you can use the alternative
   * polling helper method to wait for processing to complete).
   */
  async upload(vectorStoreId, file, options) {
    const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options);
    return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
  }
  /**
   * Add a file to a vector store and poll until processing is complete.
   */
  async uploadAndPoll(vectorStoreId, file, options) {
    const fileInfo = await this.upload(vectorStoreId, file, options);
    return await this.poll(vectorStoreId, fileInfo.id, options);
  }
};
var VectorStoreFilesPage = class extends CursorPage {
};
Files.VectorStoreFilesPage = VectorStoreFilesPage;

// node_modules/openai/resources/beta/vector-stores/file-batches.mjs
var FileBatches = class extends APIResource {
  /**
   * Create a vector store file batch.
   */
  create(vectorStoreId, body, options) {
    return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieves a vector store file batch.
   */
  retrieve(vectorStoreId, batchId, options) {
    return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Cancel a vector store file batch. This attempts to cancel the processing of
   * files in this batch as soon as possible.
   */
  cancel(vectorStoreId, batchId, options) {
    return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Create a vector store batch and poll until all files have been processed.
   */
  async createAndPoll(vectorStoreId, body, options) {
    const batch = await this.create(vectorStoreId, body);
    return await this.poll(vectorStoreId, batch.id, options);
  }
  listFiles(vectorStoreId, batchId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.listFiles(vectorStoreId, batchId, {}, query);
    }
    return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers } });
  }
  /**
   * Wait for the given file batch to be processed.
   *
   * Note: this will return even if one of the files failed to process, you need to
   * check batch.file_counts.failed_count to handle this case.
   */
  async poll(vectorStoreId, batchId, options) {
    const headers = { ...options?.headers, "X-Stainless-Poll-Helper": "true" };
    if (options?.pollIntervalMs) {
      headers["X-Stainless-Custom-Poll-Interval"] = options.pollIntervalMs.toString();
    }
    while (true) {
      const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {
        ...options,
        headers
      }).withResponse();
      switch (batch.status) {
        case "in_progress":
          let sleepInterval = 5e3;
          if (options?.pollIntervalMs) {
            sleepInterval = options.pollIntervalMs;
          } else {
            const headerInterval = response.headers.get("openai-poll-after-ms");
            if (headerInterval) {
              const headerIntervalMs = parseInt(headerInterval);
              if (!isNaN(headerIntervalMs)) {
                sleepInterval = headerIntervalMs;
              }
            }
          }
          await sleep(sleepInterval);
          break;
        case "failed":
        case "cancelled":
        case "completed":
          return batch;
      }
    }
  }
  /**
   * Uploads the given files concurrently and then creates a vector store file batch.
   *
   * The concurrency limit is configurable using the `maxConcurrency` parameter.
   */
  async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
    if (files == null || files.length == 0) {
      throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
    }
    const configuredConcurrency = options?.maxConcurrency ?? 5;
    const concurrencyLimit = Math.min(configuredConcurrency, files.length);
    const client2 = this._client;
    const fileIterator = files.values();
    const allFileIds = [...fileIds];
    async function processFiles(iterator) {
      for (let item of iterator) {
        const fileObj = await client2.files.create({ file: item, purpose: "assistants" }, options);
        allFileIds.push(fileObj.id);
      }
    }
    const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
    await allSettledWithThrow(workers);
    return await this.createAndPoll(vectorStoreId, {
      file_ids: allFileIds
    });
  }
};

// node_modules/openai/resources/beta/vector-stores/vector-stores.mjs
var VectorStores = class extends APIResource {
  constructor() {
    super(...arguments);
    this.files = new Files(this._client);
    this.fileBatches = new FileBatches(this._client);
  }
  /**
   * Create a vector store.
   */
  create(body, options) {
    return this._client.post("/vector_stores", {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Retrieves a vector store.
   */
  retrieve(vectorStoreId, options) {
    return this._client.get(`/vector_stores/${vectorStoreId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Modifies a vector store.
   */
  update(vectorStoreId, body, options) {
    return this._client.post(`/vector_stores/${vectorStoreId}`, {
      body,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  list(query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list({}, query);
    }
    return this._client.getAPIList("/vector_stores", VectorStoresPage, {
      query,
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
  /**
   * Delete a vector store.
   */
  del(vectorStoreId, options) {
    return this._client.delete(`/vector_stores/${vectorStoreId}`, {
      ...options,
      headers: { "OpenAI-Beta": "assistants=v2", ...options?.headers }
    });
  }
};
var VectorStoresPage = class extends CursorPage {
};
VectorStores.VectorStoresPage = VectorStoresPage;
VectorStores.Files = Files;
VectorStores.VectorStoreFilesPage = VectorStoreFilesPage;
VectorStores.FileBatches = FileBatches;

// node_modules/openai/resources/beta/beta.mjs
var Beta = class extends APIResource {
  constructor() {
    super(...arguments);
    this.vectorStores = new VectorStores(this._client);
    this.chat = new Chat2(this._client);
    this.assistants = new Assistants(this._client);
    this.threads = new Threads(this._client);
  }
};
Beta.VectorStores = VectorStores;
Beta.VectorStoresPage = VectorStoresPage;
Beta.Assistants = Assistants;
Beta.AssistantsPage = AssistantsPage;
Beta.Threads = Threads;

// node_modules/openai/resources/completions.mjs
var Completions3 = class extends APIResource {
  create(body, options) {
    return this._client.post("/completions", { body, ...options, stream: body.stream ?? false });
  }
};

// node_modules/openai/resources/embeddings.mjs
var Embeddings2 = class extends APIResource {
  /**
   * Creates an embedding vector representing the input text.
   */
  create(body, options) {
    return this._client.post("/embeddings", { body, ...options });
  }
};

// node_modules/openai/resources/files.mjs
var Files2 = class extends APIResource {
  /**
   * Upload a file that can be used across various endpoints. Individual files can be
   * up to 512 MB, and the size of all files uploaded by one organization can be up
   * to 100 GB.
   *
   * The Assistants API supports files up to 2 million tokens and of specific file
   * types. See the
   * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
   * details.
   *
   * The Fine-tuning API only supports `.jsonl` files. The input also has certain
   * required formats for fine-tuning
   * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
   * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
   * models.
   *
   * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
   * has a specific required
   * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
   *
   * Please [contact us](https://help.openai.com/) if you need to increase these
   * storage limits.
   */
  create(body, options) {
    return this._client.post("/files", multipartFormRequestOptions({ body, ...options }));
  }
  /**
   * Returns information about a specific file.
   */
  retrieve(fileId, options) {
    return this._client.get(`/files/${fileId}`, options);
  }
  list(query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list({}, query);
    }
    return this._client.getAPIList("/files", FileObjectsPage, { query, ...options });
  }
  /**
   * Delete a file.
   */
  del(fileId, options) {
    return this._client.delete(`/files/${fileId}`, options);
  }
  /**
   * Returns the contents of the specified file.
   */
  content(fileId, options) {
    return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true });
  }
  /**
   * Returns the contents of the specified file.
   *
   * @deprecated The `.content()` method should be used instead
   */
  retrieveContent(fileId, options) {
    return this._client.get(`/files/${fileId}/content`, {
      ...options,
      headers: { Accept: "application/json", ...options?.headers }
    });
  }
  /**
   * Waits for the given file to be processed, default timeout is 30 mins.
   */
  async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
    const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
    const start = Date.now();
    let file = await this.retrieve(id);
    while (!file.status || !TERMINAL_STATES.has(file.status)) {
      await sleep(pollInterval);
      file = await this.retrieve(id);
      if (Date.now() - start > maxWait) {
        throw new APIConnectionTimeoutError({
          message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
        });
      }
    }
    return file;
  }
};
var FileObjectsPage = class extends CursorPage {
};
Files2.FileObjectsPage = FileObjectsPage;

// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
var Checkpoints = class extends APIResource {
  list(fineTuningJobId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list(fineTuningJobId, {}, query);
    }
    return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });
  }
};
var FineTuningJobCheckpointsPage = class extends CursorPage {
};
Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;

// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
var Jobs = class extends APIResource {
  constructor() {
    super(...arguments);
    this.checkpoints = new Checkpoints(this._client);
  }
  /**
   * Creates a fine-tuning job which begins the process of creating a new model from
   * a given dataset.
   *
   * Response includes details of the enqueued job including job status and the name
   * of the fine-tuned models once complete.
   *
   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
   */
  create(body, options) {
    return this._client.post("/fine_tuning/jobs", { body, ...options });
  }
  /**
   * Get info about a fine-tuning job.
   *
   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
   */
  retrieve(fineTuningJobId, options) {
    return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);
  }
  list(query = {}, options) {
    if (isRequestOptions(query)) {
      return this.list({}, query);
    }
    return this._client.getAPIList("/fine_tuning/jobs", FineTuningJobsPage, { query, ...options });
  }
  /**
   * Immediately cancel a fine-tune job.
   */
  cancel(fineTuningJobId, options) {
    return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);
  }
  listEvents(fineTuningJobId, query = {}, options) {
    if (isRequestOptions(query)) {
      return this.listEvents(fineTuningJobId, {}, query);
    }
    return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {
      query,
      ...options
    });
  }
};
var FineTuningJobsPage = class extends CursorPage {
};
var FineTuningJobEventsPage = class extends CursorPage {
};
Jobs.FineTuningJobsPage = FineTuningJobsPage;
Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage;
Jobs.Checkpoints = Checkpoints;
Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;

// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
var FineTuning = class extends APIResource {
  constructor() {
    super(...arguments);
    this.jobs = new Jobs(this._client);
  }
};
FineTuning.Jobs = Jobs;
FineTuning.FineTuningJobsPage = FineTuningJobsPage;
FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;

// node_modules/openai/resources/images.mjs
var Images = class extends APIResource {
  /**
   * Creates a variation of a given image.
   */
  createVariation(body, options) {
    return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options }));
  }
  /**
   * Creates an edited or extended image given an original image and a prompt.
   */
  edit(body, options) {
    return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options }));
  }
  /**
   * Creates an image given a prompt.
   */
  generate(body, options) {
    return this._client.post("/images/generations", { body, ...options });
  }
};

// node_modules/openai/resources/models.mjs
var Models = class extends APIResource {
  /**
   * Retrieves a model instance, providing basic information about the model such as
   * the owner and permissioning.
   */
  retrieve(model, options) {
    return this._client.get(`/models/${model}`, options);
  }
  /**
   * Lists the currently available models, and provides basic information about each
   * one such as the owner and availability.
   */
  list(options) {
    return this._client.getAPIList("/models", ModelsPage, options);
  }
  /**
   * Delete a fine-tuned model. You must have the Owner role in your organization to
   * delete a model.
   */
  del(model, options) {
    return this._client.delete(`/models/${model}`, options);
  }
};
var ModelsPage = class extends Page {
};
Models.ModelsPage = ModelsPage;

// node_modules/openai/resources/moderations.mjs
var Moderations = class extends APIResource {
  /**
   * Classifies if text and/or image inputs are potentially harmful. Learn more in
   * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
   */
  create(body, options) {
    return this._client.post("/moderations", { body, ...options });
  }
};

// node_modules/openai/resources/uploads/parts.mjs
var Parts = class extends APIResource {
  /**
   * Adds a
   * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
   * A Part represents a chunk of bytes from the file you are trying to upload.
   *
   * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
   * maximum of 8 GB.
   *
   * It is possible to add multiple Parts in parallel. You can decide the intended
   * order of the Parts when you
   * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
   */
  create(uploadId, body, options) {
    return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options }));
  }
};

// node_modules/openai/resources/uploads/uploads.mjs
var Uploads = class extends APIResource {
  constructor() {
    super(...arguments);
    this.parts = new Parts(this._client);
  }
  /**
   * Creates an intermediate
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
   * that you can add
   * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
   * Currently, an Upload can accept at most 8 GB in total and expires after an hour
   * after you create it.
   *
   * Once you complete the Upload, we will create a
   * [File](https://platform.openai.com/docs/api-reference/files/object) object that
   * contains all the parts you uploaded. This File is usable in the rest of our
   * platform as a regular File object.
   *
   * For certain `purpose`s, the correct `mime_type` must be specified. Please refer
   * to documentation for the supported MIME types for your use case:
   *
   * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files)
   *
   * For guidance on the proper filename extensions for each purpose, please follow
   * the documentation on
   * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
   */
  create(body, options) {
    return this._client.post("/uploads", { body, ...options });
  }
  /**
   * Cancels the Upload. No Parts may be added after an Upload is cancelled.
   */
  cancel(uploadId, options) {
    return this._client.post(`/uploads/${uploadId}/cancel`, options);
  }
  /**
   * Completes the
   * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
   *
   * Within the returned Upload object, there is a nested
   * [File](https://platform.openai.com/docs/api-reference/files/object) object that
   * is ready to use in the rest of the platform.
   *
   * You can specify the order of the Parts by passing in an ordered list of the Part
   * IDs.
   *
   * The number of bytes uploaded upon completion must match the number of bytes
   * initially specified when creating the Upload object. No Parts may be added after
   * an Upload is completed.
   */
  complete(uploadId, body, options) {
    return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });
  }
};
Uploads.Parts = Parts;

// node_modules/openai/index.mjs
var _a2;
var OpenAI = class extends APIClient {
  /**
   * API Client for interfacing with the OpenAI API.
   *
   * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
   * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
   * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
   * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
   * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
   * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, ...opts } = {}) {
    if (apiKey === void 0) {
      throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");
    }
    const options = {
      apiKey,
      organization,
      project,
      ...opts,
      baseURL: baseURL || `https://api.openai.com/v1`
    };
    if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
      throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
    }
    super({
      baseURL: options.baseURL,
      timeout: options.timeout ?? 6e5,
      httpAgent: options.httpAgent,
      maxRetries: options.maxRetries,
      fetch: options.fetch
    });
    this.completions = new Completions3(this);
    this.chat = new Chat(this);
    this.embeddings = new Embeddings2(this);
    this.files = new Files2(this);
    this.images = new Images(this);
    this.audio = new Audio(this);
    this.moderations = new Moderations(this);
    this.models = new Models(this);
    this.fineTuning = new FineTuning(this);
    this.beta = new Beta(this);
    this.batches = new Batches(this);
    this.uploads = new Uploads(this);
    this._options = options;
    this.apiKey = apiKey;
    this.organization = organization;
    this.project = project;
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  defaultHeaders(opts) {
    return {
      ...super.defaultHeaders(opts),
      "OpenAI-Organization": this.organization,
      "OpenAI-Project": this.project,
      ...this._options.defaultHeaders
    };
  }
  authHeaders(opts) {
    return { Authorization: `Bearer ${this.apiKey}` };
  }
  stringifyQuery(query) {
    return stringify2(query, { arrayFormat: "brackets" });
  }
};
_a2 = OpenAI;
OpenAI.OpenAI = _a2;
OpenAI.DEFAULT_TIMEOUT = 6e5;
OpenAI.OpenAIError = OpenAIError;
OpenAI.APIError = APIError;
OpenAI.APIConnectionError = APIConnectionError;
OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
OpenAI.APIUserAbortError = APIUserAbortError;
OpenAI.NotFoundError = NotFoundError;
OpenAI.ConflictError = ConflictError;
OpenAI.RateLimitError = RateLimitError;
OpenAI.BadRequestError = BadRequestError;
OpenAI.AuthenticationError = AuthenticationError;
OpenAI.InternalServerError = InternalServerError;
OpenAI.PermissionDeniedError = PermissionDeniedError;
OpenAI.UnprocessableEntityError = UnprocessableEntityError;
OpenAI.toFile = toFile;
OpenAI.fileFromPath = fileFromPath;
OpenAI.Completions = Completions3;
OpenAI.Chat = Chat;
OpenAI.Embeddings = Embeddings2;
OpenAI.Files = Files2;
OpenAI.FileObjectsPage = FileObjectsPage;
OpenAI.Images = Images;
OpenAI.Audio = Audio;
OpenAI.Moderations = Moderations;
OpenAI.Models = Models;
OpenAI.ModelsPage = ModelsPage;
OpenAI.FineTuning = FineTuning;
OpenAI.Beta = Beta;
OpenAI.Batches = Batches;
OpenAI.BatchesPage = BatchesPage;
OpenAI.Uploads = Uploads;

// node_modules/@langchain/openai/dist/chat_models.js
init_outputs2();
init_base9();
init_runnables2();
init_output_parsers2();

// node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js
init_base5();
init_json2();
init_transform();
init_ai();
function parseToolCall2(rawToolCall, options) {
  if (rawToolCall.function === void 0) {
    return void 0;
  }
  let functionArgs;
  if (options?.partial) {
    try {
      functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}");
    } catch (e3) {
      return void 0;
    }
  } else {
    try {
      functionArgs = JSON.parse(rawToolCall.function.arguments);
    } catch (e3) {
      throw new OutputParserException([
        `Function "${rawToolCall.function.name}" arguments:`,
        ``,
        rawToolCall.function.arguments,
        ``,
        `are not valid JSON.`,
        `Error: ${e3.message}`
      ].join("\n"));
    }
  }
  const parsedToolCall = {
    name: rawToolCall.function.name,
    args: functionArgs,
    type: "tool_call"
  };
  if (options?.returnId) {
    parsedToolCall.id = rawToolCall.id;
  }
  return parsedToolCall;
}
function convertLangChainToolCallToOpenAI(toolCall) {
  if (toolCall.id === void 0) {
    throw new Error(`All OpenAI tool calls must have an "id" field.`);
  }
  return {
    id: toolCall.id,
    type: "function",
    function: {
      name: toolCall.name,
      arguments: JSON.stringify(toolCall.args)
    }
  };
}
function makeInvalidToolCall(rawToolCall, errorMsg) {
  return {
    name: rawToolCall.function?.name,
    args: rawToolCall.function?.arguments,
    id: rawToolCall.id,
    error: errorMsg,
    type: "invalid_tool_call"
  };
}
var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser {
  static lc_name() {
    return "JsonOutputToolsParser";
  }
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "returnId", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "output_parsers", "openai_tools"]
    });
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    this.returnId = fields?.returnId ?? this.returnId;
  }
  _diff() {
    throw new Error("Not supported.");
  }
  async parse() {
    throw new Error("Not implemented.");
  }
  async parseResult(generations) {
    const result = await this.parsePartialResult(generations, false);
    return result;
  }
  /**
   * Parses the output and returns a JSON object. If `argsOnly` is true,
   * only the arguments of the function call are returned.
   * @param generations The output of the LLM to parse.
   * @returns A JSON object representation of the function call or its arguments.
   */
  async parsePartialResult(generations, partial = true) {
    const message = generations[0].message;
    let toolCalls;
    if (isAIMessage(message) && message.tool_calls?.length) {
      toolCalls = message.tool_calls.map((toolCall) => {
        const { id, ...rest } = toolCall;
        if (!this.returnId) {
          return rest;
        }
        return {
          id,
          ...rest
        };
      });
    } else if (message.additional_kwargs.tool_calls !== void 0) {
      const rawToolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls));
      toolCalls = rawToolCalls.map((rawToolCall) => {
        return parseToolCall2(rawToolCall, { returnId: this.returnId, partial });
      });
    }
    if (!toolCalls) {
      return [];
    }
    const parsedToolCalls = [];
    for (const toolCall of toolCalls) {
      if (toolCall !== void 0) {
        const backwardsCompatibleToolCall = {
          type: toolCall.name,
          args: toolCall.args,
          id: toolCall.id
        };
        parsedToolCalls.push(backwardsCompatibleToolCall);
      }
    }
    return parsedToolCalls;
  }
};
var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser {
  static lc_name() {
    return "JsonOutputKeyToolsParser";
  }
  constructor(params) {
    super(params);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "output_parsers", "openai_tools"]
    });
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "returnId", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "keyName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "returnSingle", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "zodSchema", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.keyName = params.keyName;
    this.returnSingle = params.returnSingle ?? this.returnSingle;
    this.zodSchema = params.zodSchema;
  }
  async _validateResult(result) {
    if (this.zodSchema === void 0) {
      return result;
    }
    const zodParsedResult = await this.zodSchema.safeParseAsync(result);
    if (zodParsedResult.success) {
      return zodParsedResult.data;
    } else {
      throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2));
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async parsePartialResult(generations) {
    const results = await super.parsePartialResult(generations);
    const matchingResults = results.filter((result) => result.type === this.keyName);
    let returnedValues = matchingResults;
    if (!matchingResults.length) {
      return void 0;
    }
    if (!this.returnId) {
      returnedValues = matchingResults.map((result) => result.args);
    }
    if (this.returnSingle) {
      return returnedValues[0];
    }
    return returnedValues;
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async parseResult(generations) {
    const results = await super.parsePartialResult(generations, false);
    const matchingResults = results.filter((result) => result.type === this.keyName);
    let returnedValues = matchingResults;
    if (!matchingResults.length) {
      return void 0;
    }
    if (!this.returnId) {
      returnedValues = matchingResults.map((result) => result.args);
    }
    if (this.returnSingle) {
      return this._validateResult(returnedValues[0]);
    }
    const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value)));
    return toolCallResults;
  }
};

// node_modules/@langchain/openai/dist/chat_models.js
init_esm();

// node_modules/openai/_vendor/zod-to-json-schema/Options.mjs
var ignoreOverride2 = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions3 = {
  name: void 0,
  $refStrategy: "root",
  effectStrategy: "input",
  pipeStrategy: "all",
  dateStrategy: "format:date-time",
  mapStrategy: "entries",
  nullableStrategy: "from-target",
  removeAdditionalStrategy: "passthrough",
  definitionPath: "definitions",
  target: "jsonSchema7",
  strictUnions: false,
  errorMessages: false,
  markdownDescription: false,
  patternStrategy: "escape",
  applyRegexFlags: false,
  emailStrategy: "format:email",
  base64Strategy: "contentEncoding:base64",
  nameStrategy: "ref"
};
var getDefaultOptions2 = (options) => {
  return typeof options === "string" ? {
    ...defaultOptions3,
    basePath: ["#"],
    definitions: {},
    name: options
  } : {
    ...defaultOptions3,
    basePath: ["#"],
    definitions: {},
    ...options
  };
};

// node_modules/openai/_vendor/zod-to-json-schema/util.mjs
var zodDef = (zodSchema) => {
  return "_def" in zodSchema ? zodSchema._def : zodSchema;
};
function isEmptyObj2(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}

// node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs
var getRefs2 = (options) => {
  const _options = getDefaultOptions2(options);
  const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
  return {
    ..._options,
    currentPath,
    propertyPath: void 0,
    seenRefs: /* @__PURE__ */ new Set(),
    seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
      zodDef(def),
      {
        def: zodDef(def),
        path: [..._options.basePath, _options.definitionPath, name],
        // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
        jsonSchema: void 0
      }
    ]))
  };
};

// node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs
function addErrorMessage2(res, key, errorMessage, refs) {
  if (!refs?.errorMessages)
    return;
  if (errorMessage) {
    res.errorMessage = {
      ...res.errorMessage,
      [key]: errorMessage
    };
  }
}
function setResponseValueAndErrors2(res, key, value, errorMessage, refs) {
  res[key] = value;
  addErrorMessage2(res, key, errorMessage, refs);
}

// node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs
init_lib();

// node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs
function parseAnyDef2() {
  return {};
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs
init_lib();
function parseArrayDef2(def, refs) {
  const res = {
    type: "array"
  };
  if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
    res.items = parseDef2(def.type._def, {
      ...refs,
      currentPath: [...refs.currentPath, "items"]
    });
  }
  if (def.minLength) {
    setResponseValueAndErrors2(res, "minItems", def.minLength.value, def.minLength.message, refs);
  }
  if (def.maxLength) {
    setResponseValueAndErrors2(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
  }
  if (def.exactLength) {
    setResponseValueAndErrors2(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
    setResponseValueAndErrors2(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
  }
  return res;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs
function parseBigintDef2(def, refs) {
  const res = {
    type: "integer",
    format: "int64"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors2(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors2(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors2(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors2(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors2(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors2(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors2(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs
function parseBooleanDef2() {
  return {
    type: "boolean"
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs
function parseBrandedDef2(_def, refs) {
  return parseDef2(_def.type._def, refs);
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs
var parseCatchDef2 = (def, refs) => {
  return parseDef2(def.innerType._def, refs);
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs
function parseDateDef2(def, refs, overrideDateStrategy) {
  const strategy = overrideDateStrategy ?? refs.dateStrategy;
  if (Array.isArray(strategy)) {
    return {
      anyOf: strategy.map((item, i3) => parseDateDef2(def, refs, item))
    };
  }
  switch (strategy) {
    case "string":
    case "format:date-time":
      return {
        type: "string",
        format: "date-time"
      };
    case "format:date":
      return {
        type: "string",
        format: "date"
      };
    case "integer":
      return integerDateParser2(def, refs);
  }
}
var integerDateParser2 = (def, refs) => {
  const res = {
    type: "integer",
    format: "unix-time"
  };
  if (refs.target === "openApi3") {
    return res;
  }
  for (const check of def.checks) {
    switch (check.kind) {
      case "min":
        setResponseValueAndErrors2(
          res,
          "minimum",
          check.value,
          // This is in milliseconds
          check.message,
          refs
        );
        break;
      case "max":
        setResponseValueAndErrors2(
          res,
          "maximum",
          check.value,
          // This is in milliseconds
          check.message,
          refs
        );
        break;
    }
  }
  return res;
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs
function parseDefaultDef2(_def, refs) {
  return {
    ...parseDef2(_def.innerType._def, refs),
    default: _def.defaultValue()
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs
function parseEffectsDef2(_def, refs, forceResolution) {
  return refs.effectStrategy === "input" ? parseDef2(_def.schema._def, refs, forceResolution) : {};
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs
function parseEnumDef2(def) {
  return {
    type: "string",
    enum: [...def.values]
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs
var isJsonSchema7AllOfType2 = (type) => {
  if ("type" in type && type.type === "string")
    return false;
  return "allOf" in type;
};
function parseIntersectionDef2(def, refs) {
  const allOf = [
    parseDef2(def.left._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "0"]
    }),
    parseDef2(def.right._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "1"]
    })
  ].filter((x2) => !!x2);
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
  const mergedAllOf = [];
  allOf.forEach((schema) => {
    if (isJsonSchema7AllOfType2(schema)) {
      mergedAllOf.push(...schema.allOf);
      if (schema.unevaluatedProperties === void 0) {
        unevaluatedProperties = void 0;
      }
    } else {
      let nestedSchema = schema;
      if ("additionalProperties" in schema && schema.additionalProperties === false) {
        const { additionalProperties, ...rest } = schema;
        nestedSchema = rest;
      } else {
        unevaluatedProperties = void 0;
      }
      mergedAllOf.push(nestedSchema);
    }
  });
  return mergedAllOf.length ? {
    allOf: mergedAllOf,
    ...unevaluatedProperties
  } : void 0;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs
function parseLiteralDef2(def, refs) {
  const parsedType = typeof def.value;
  if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
    return {
      type: Array.isArray(def.value) ? "array" : "object"
    };
  }
  if (refs.target === "openApi3") {
    return {
      type: parsedType === "bigint" ? "integer" : parsedType,
      enum: [def.value]
    };
  }
  return {
    type: parsedType === "bigint" ? "integer" : parsedType,
    const: def.value
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs
init_lib();

// node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs
var emojiRegex3;
var zodPatterns2 = {
  /**
   * `c` was changed to `[cC]` to replicate /i flag
   */
  cuid: /^[cC][^\s-]{8,}$/,
  cuid2: /^[0-9a-z]+$/,
  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
  /**
   * `a-z` was added to replicate /i flag
   */
  email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
  /**
   * Constructed a valid Unicode RegExp
   *
   * Lazily instantiate since this type of regex isn't supported
   * in all envs (e.g. React Native).
   *
   * See:
   * https://github.com/colinhacks/zod/issues/2433
   * Fix in Zod:
   * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
   */
  emoji: () => {
    if (emojiRegex3 === void 0) {
      emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
    }
    return emojiRegex3;
  },
  /**
   * Unused
   */
  uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
  /**
   * Unused
   */
  ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
  /**
   * Unused
   */
  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
  nanoid: /^[a-zA-Z0-9_-]{21}$/
};
function parseStringDef2(def, refs) {
  const res = {
    type: "string"
  };
  function processPattern(value) {
    return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(value) : value;
  }
  if (def.checks) {
    for (const check of def.checks) {
      switch (check.kind) {
        case "min":
          setResponseValueAndErrors2(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          break;
        case "max":
          setResponseValueAndErrors2(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "email":
          switch (refs.emailStrategy) {
            case "format:email":
              addFormat2(res, "email", check.message, refs);
              break;
            case "format:idn-email":
              addFormat2(res, "idn-email", check.message, refs);
              break;
            case "pattern:zod":
              addPattern2(res, zodPatterns2.email, check.message, refs);
              break;
          }
          break;
        case "url":
          addFormat2(res, "uri", check.message, refs);
          break;
        case "uuid":
          addFormat2(res, "uuid", check.message, refs);
          break;
        case "regex":
          addPattern2(res, check.regex, check.message, refs);
          break;
        case "cuid":
          addPattern2(res, zodPatterns2.cuid, check.message, refs);
          break;
        case "cuid2":
          addPattern2(res, zodPatterns2.cuid2, check.message, refs);
          break;
        case "startsWith":
          addPattern2(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);
          break;
        case "endsWith":
          addPattern2(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);
          break;
        case "datetime":
          addFormat2(res, "date-time", check.message, refs);
          break;
        case "date":
          addFormat2(res, "date", check.message, refs);
          break;
        case "time":
          addFormat2(res, "time", check.message, refs);
          break;
        case "duration":
          addFormat2(res, "duration", check.message, refs);
          break;
        case "length":
          setResponseValueAndErrors2(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          setResponseValueAndErrors2(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "includes": {
          addPattern2(res, RegExp(processPattern(check.value)), check.message, refs);
          break;
        }
        case "ip": {
          if (check.version !== "v6") {
            addFormat2(res, "ipv4", check.message, refs);
          }
          if (check.version !== "v4") {
            addFormat2(res, "ipv6", check.message, refs);
          }
          break;
        }
        case "emoji":
          addPattern2(res, zodPatterns2.emoji, check.message, refs);
          break;
        case "ulid": {
          addPattern2(res, zodPatterns2.ulid, check.message, refs);
          break;
        }
        case "base64": {
          switch (refs.base64Strategy) {
            case "format:binary": {
              addFormat2(res, "binary", check.message, refs);
              break;
            }
            case "contentEncoding:base64": {
              setResponseValueAndErrors2(res, "contentEncoding", "base64", check.message, refs);
              break;
            }
            case "pattern:zod": {
              addPattern2(res, zodPatterns2.base64, check.message, refs);
              break;
            }
          }
          break;
        }
        case "nanoid": {
          addPattern2(res, zodPatterns2.nanoid, check.message, refs);
        }
        case "toLowerCase":
        case "toUpperCase":
        case "trim":
          break;
        default:
          ((_2) => {
          })(check);
      }
    }
  }
  return res;
}
var escapeNonAlphaNumeric2 = (value) => Array.from(value).map((c4) => /[a-zA-Z0-9]/.test(c4) ? c4 : `\\${c4}`).join("");
var addFormat2 = (schema, value, message, refs) => {
  if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
    if (!schema.anyOf) {
      schema.anyOf = [];
    }
    if (schema.format) {
      schema.anyOf.push({
        format: schema.format,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { format: schema.errorMessage.format }
        }
      });
      delete schema.format;
      if (schema.errorMessage) {
        delete schema.errorMessage.format;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.anyOf.push({
      format: value,
      ...message && refs.errorMessages && { errorMessage: { format: message } }
    });
  } else {
    setResponseValueAndErrors2(schema, "format", value, message, refs);
  }
};
var addPattern2 = (schema, regex2, message, refs) => {
  if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
    if (!schema.allOf) {
      schema.allOf = [];
    }
    if (schema.pattern) {
      schema.allOf.push({
        pattern: schema.pattern,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { pattern: schema.errorMessage.pattern }
        }
      });
      delete schema.pattern;
      if (schema.errorMessage) {
        delete schema.errorMessage.pattern;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.allOf.push({
      pattern: processRegExp(regex2, refs),
      ...message && refs.errorMessages && { errorMessage: { pattern: message } }
    });
  } else {
    setResponseValueAndErrors2(schema, "pattern", processRegExp(regex2, refs), message, refs);
  }
};
var processRegExp = (regexOrFunction, refs) => {
  const regex2 = typeof regexOrFunction === "function" ? regexOrFunction() : regexOrFunction;
  if (!refs.applyRegexFlags || !regex2.flags)
    return regex2.source;
  const flags = {
    i: regex2.flags.includes("i"),
    m: regex2.flags.includes("m"),
    s: regex2.flags.includes("s")
    // `.` matches newlines
  };
  const source = flags.i ? regex2.source.toLowerCase() : regex2.source;
  let pattern = "";
  let isEscaped = false;
  let inCharGroup = false;
  let inCharRange = false;
  for (let i3 = 0; i3 < source.length; i3++) {
    if (isEscaped) {
      pattern += source[i3];
      isEscaped = false;
      continue;
    }
    if (flags.i) {
      if (inCharGroup) {
        if (source[i3].match(/[a-z]/)) {
          if (inCharRange) {
            pattern += source[i3];
            pattern += `${source[i3 - 2]}-${source[i3]}`.toUpperCase();
            inCharRange = false;
          } else if (source[i3 + 1] === "-" && source[i3 + 2]?.match(/[a-z]/)) {
            pattern += source[i3];
            inCharRange = true;
          } else {
            pattern += `${source[i3]}${source[i3].toUpperCase()}`;
          }
          continue;
        }
      } else if (source[i3].match(/[a-z]/)) {
        pattern += `[${source[i3]}${source[i3].toUpperCase()}]`;
        continue;
      }
    }
    if (flags.m) {
      if (source[i3] === "^") {
        pattern += `(^|(?<=[\r
]))`;
        continue;
      } else if (source[i3] === "$") {
        pattern += `($|(?=[\r
]))`;
        continue;
      }
    }
    if (flags.s && source[i3] === ".") {
      pattern += inCharGroup ? `${source[i3]}\r
` : `[${source[i3]}\r
]`;
      continue;
    }
    pattern += source[i3];
    if (source[i3] === "\\") {
      isEscaped = true;
    } else if (inCharGroup && source[i3] === "]") {
      inCharGroup = false;
    } else if (!inCharGroup && source[i3] === "[") {
      inCharGroup = true;
    }
  }
  try {
    const regexTest = new RegExp(pattern);
  } catch {
    console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
    return regex2.source;
  }
  return pattern;
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs
function parseRecordDef2(def, refs) {
  if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      type: "object",
      required: def.keyType._def.values,
      properties: def.keyType._def.values.reduce((acc, key) => ({
        ...acc,
        [key]: parseDef2(def.valueType._def, {
          ...refs,
          currentPath: [...refs.currentPath, "properties", key]
        }) ?? {}
      }), {}),
      additionalProperties: false
    };
  }
  const schema = {
    type: "object",
    additionalProperties: parseDef2(def.valueType._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? {}
  };
  if (refs.target === "openApi3") {
    return schema;
  }
  if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
    const keyType = Object.entries(parseStringDef2(def.keyType._def, refs)).reduce((acc, [key, value]) => key === "type" ? acc : { ...acc, [key]: value }, {});
    return {
      ...schema,
      propertyNames: keyType
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      ...schema,
      propertyNames: {
        enum: def.keyType._def.values
      }
    };
  }
  return schema;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs
function parseMapDef2(def, refs) {
  if (refs.mapStrategy === "record") {
    return parseRecordDef2(def, refs);
  }
  const keys = parseDef2(def.keyType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "0"]
  }) || {};
  const values = parseDef2(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "1"]
  }) || {};
  return {
    type: "array",
    maxItems: 125,
    items: {
      type: "array",
      items: [keys, values],
      minItems: 2,
      maxItems: 2
    }
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs
function parseNativeEnumDef2(def) {
  const object = def.values;
  const actualKeys = Object.keys(def.values).filter((key) => {
    return typeof object[object[key]] !== "number";
  });
  const actualValues = actualKeys.map((key) => object[key]);
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
  return {
    type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
    enum: actualValues
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs
function parseNeverDef2() {
  return {
    not: {}
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs
function parseNullDef2(refs) {
  return refs.target === "openApi3" ? {
    enum: ["null"],
    nullable: true
  } : {
    type: "null"
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs
var primitiveMappings2 = {
  ZodString: "string",
  ZodNumber: "number",
  ZodBigInt: "integer",
  ZodBoolean: "boolean",
  ZodNull: "null"
};
function parseUnionDef2(def, refs) {
  if (refs.target === "openApi3")
    return asAnyOf2(def, refs);
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
  if (options.every((x2) => x2._def.typeName in primitiveMappings2 && (!x2._def.checks || !x2._def.checks.length))) {
    const types = options.reduce((types2, x2) => {
      const type = primitiveMappings2[x2._def.typeName];
      return type && !types2.includes(type) ? [...types2, type] : types2;
    }, []);
    return {
      type: types.length > 1 ? types : types[0]
    };
  } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
    const types = options.reduce((acc, x2) => {
      const type = typeof x2._def.value;
      switch (type) {
        case "string":
        case "number":
        case "boolean":
          return [...acc, type];
        case "bigint":
          return [...acc, "integer"];
        case "object":
          if (x2._def.value === null)
            return [...acc, "null"];
        case "symbol":
        case "undefined":
        case "function":
        default:
          return acc;
      }
    }, []);
    if (types.length === options.length) {
      const uniqueTypes = types.filter((x2, i3, a3) => a3.indexOf(x2) === i3);
      return {
        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
        enum: options.reduce((acc, x2) => {
          return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
        }, [])
      };
    }
  } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
    return {
      type: "string",
      enum: options.reduce((acc, x2) => [...acc, ...x2._def.values.filter((x3) => !acc.includes(x3))], [])
    };
  }
  return asAnyOf2(def, refs);
}
var asAnyOf2 = (def, refs) => {
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i3) => parseDef2(x2._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", `${i3}`]
  })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
  return anyOf.length ? { anyOf } : void 0;
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs
function parseNullableDef2(def, refs) {
  if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
    if (refs.target === "openApi3" || refs.nullableStrategy === "property") {
      return {
        type: primitiveMappings2[def.innerType._def.typeName],
        nullable: true
      };
    }
    return {
      type: [primitiveMappings2[def.innerType._def.typeName], "null"]
    };
  }
  if (refs.target === "openApi3") {
    const base2 = parseDef2(def.innerType._def, {
      ...refs,
      currentPath: [...refs.currentPath]
    });
    if (base2 && "$ref" in base2)
      return { allOf: [base2], nullable: true };
    return base2 && { ...base2, nullable: true };
  }
  const base = parseDef2(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "0"]
  });
  return base && { anyOf: [base, { type: "null" }] };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs
function parseNumberDef2(def, refs) {
  const res = {
    type: "number"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "int":
        res.type = "integer";
        addErrorMessage2(res, "type", check.message, refs);
        break;
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors2(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors2(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors2(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors2(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors2(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors2(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors2(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs
function decideAdditionalProperties2(def, refs) {
  if (refs.removeAdditionalStrategy === "strict") {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef2(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  } else {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef2(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  }
}
function parseObjectDef2(def, refs) {
  const result = {
    type: "object",
    ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
      if (propDef === void 0 || propDef._def === void 0)
        return acc;
      const parsedDef = parseDef2(propDef._def, {
        ...refs,
        currentPath: [...refs.currentPath, "properties", propName],
        propertyPath: [...refs.currentPath, "properties", propName]
      });
      if (parsedDef === void 0)
        return acc;
      return {
        properties: {
          ...acc.properties,
          [propName]: parsedDef
        },
        required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName]
      };
    }, { properties: {}, required: [] }),
    additionalProperties: decideAdditionalProperties2(def, refs)
  };
  if (!result.required.length)
    delete result.required;
  return result;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs
var parseOptionalDef2 = (def, refs) => {
  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
    return parseDef2(def.innerType._def, refs);
  }
  const innerSchema = parseDef2(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "1"]
  });
  return innerSchema ? {
    anyOf: [
      {
        not: {}
      },
      innerSchema
    ]
  } : {};
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs
var parsePipelineDef2 = (def, refs) => {
  if (refs.pipeStrategy === "input") {
    return parseDef2(def.in._def, refs);
  } else if (refs.pipeStrategy === "output") {
    return parseDef2(def.out._def, refs);
  }
  const a3 = parseDef2(def.in._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", "0"]
  });
  const b3 = parseDef2(def.out._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"]
  });
  return {
    allOf: [a3, b3].filter((x2) => x2 !== void 0)
  };
};

// node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs
function parsePromiseDef2(def, refs) {
  return parseDef2(def.type._def, refs);
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs
function parseSetDef2(def, refs) {
  const items = parseDef2(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items"]
  });
  const schema = {
    type: "array",
    uniqueItems: true,
    items
  };
  if (def.minSize) {
    setResponseValueAndErrors2(schema, "minItems", def.minSize.value, def.minSize.message, refs);
  }
  if (def.maxSize) {
    setResponseValueAndErrors2(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
  }
  return schema;
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs
function parseTupleDef2(def, refs) {
  if (def.rest) {
    return {
      type: "array",
      minItems: def.items.length,
      items: def.items.map((x2, i3) => parseDef2(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i3}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
      additionalItems: parseDef2(def.rest._def, {
        ...refs,
        currentPath: [...refs.currentPath, "additionalItems"]
      })
    };
  } else {
    return {
      type: "array",
      minItems: def.items.length,
      maxItems: def.items.length,
      items: def.items.map((x2, i3) => parseDef2(x2._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i3}`]
      })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
    };
  }
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs
function parseUndefinedDef2() {
  return {
    not: {}
  };
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs
function parseUnknownDef2() {
  return {};
}

// node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs
var parseReadonlyDef2 = (def, refs) => {
  return parseDef2(def.innerType._def, refs);
};

// node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs
function parseDef2(def, refs, forceResolution = false) {
  const seenItem = refs.seen.get(def);
  if (refs.override) {
    const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
    if (overrideResult !== ignoreOverride2) {
      return overrideResult;
    }
  }
  if (seenItem && !forceResolution) {
    const seenSchema = get$ref2(seenItem, refs);
    if (seenSchema !== void 0) {
      if ("$ref" in seenSchema) {
        refs.seenRefs.add(seenSchema.$ref);
      }
      return seenSchema;
    }
  }
  const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
  refs.seen.set(def, newItem);
  const jsonSchema = selectParser2(def, def.typeName, refs, forceResolution);
  if (jsonSchema) {
    addMeta2(def, refs, jsonSchema);
  }
  newItem.jsonSchema = jsonSchema;
  return jsonSchema;
}
var get$ref2 = (item, refs) => {
  switch (refs.$refStrategy) {
    case "root":
      return { $ref: item.path.join("/") };
    case "extract-to-root":
      const name = item.path.slice(refs.basePath.length + 1).join("_");
      if (name !== refs.name && refs.nameStrategy === "duplicate-ref") {
        refs.definitions[name] = item.def;
      }
      return { $ref: [...refs.basePath, refs.definitionPath, name].join("/") };
    case "relative":
      return { $ref: getRelativePath2(refs.currentPath, item.path) };
    case "none":
    case "seen": {
      if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) {
        console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
        return {};
      }
      return refs.$refStrategy === "seen" ? {} : void 0;
    }
  }
};
var getRelativePath2 = (pathA, pathB) => {
  let i3 = 0;
  for (; i3 < pathA.length && i3 < pathB.length; i3++) {
    if (pathA[i3] !== pathB[i3])
      break;
  }
  return [(pathA.length - i3).toString(), ...pathB.slice(i3)].join("/");
};
var selectParser2 = (def, typeName, refs, forceResolution) => {
  switch (typeName) {
    case ZodFirstPartyTypeKind.ZodString:
      return parseStringDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodNumber:
      return parseNumberDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodObject:
      return parseObjectDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodBigInt:
      return parseBigintDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodBoolean:
      return parseBooleanDef2();
    case ZodFirstPartyTypeKind.ZodDate:
      return parseDateDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodUndefined:
      return parseUndefinedDef2();
    case ZodFirstPartyTypeKind.ZodNull:
      return parseNullDef2(refs);
    case ZodFirstPartyTypeKind.ZodArray:
      return parseArrayDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodUnion:
    case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
      return parseUnionDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodIntersection:
      return parseIntersectionDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodTuple:
      return parseTupleDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodRecord:
      return parseRecordDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodLiteral:
      return parseLiteralDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodEnum:
      return parseEnumDef2(def);
    case ZodFirstPartyTypeKind.ZodNativeEnum:
      return parseNativeEnumDef2(def);
    case ZodFirstPartyTypeKind.ZodNullable:
      return parseNullableDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodOptional:
      return parseOptionalDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodMap:
      return parseMapDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodSet:
      return parseSetDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodLazy:
      return parseDef2(def.getter()._def, refs);
    case ZodFirstPartyTypeKind.ZodPromise:
      return parsePromiseDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodNaN:
    case ZodFirstPartyTypeKind.ZodNever:
      return parseNeverDef2();
    case ZodFirstPartyTypeKind.ZodEffects:
      return parseEffectsDef2(def, refs, forceResolution);
    case ZodFirstPartyTypeKind.ZodAny:
      return parseAnyDef2();
    case ZodFirstPartyTypeKind.ZodUnknown:
      return parseUnknownDef2();
    case ZodFirstPartyTypeKind.ZodDefault:
      return parseDefaultDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodBranded:
      return parseBrandedDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodReadonly:
      return parseReadonlyDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodCatch:
      return parseCatchDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodPipeline:
      return parsePipelineDef2(def, refs);
    case ZodFirstPartyTypeKind.ZodFunction:
    case ZodFirstPartyTypeKind.ZodVoid:
    case ZodFirstPartyTypeKind.ZodSymbol:
      return void 0;
    default:
      return ((_2) => void 0)(typeName);
  }
};
var addMeta2 = (def, refs, jsonSchema) => {
  if (def.description) {
    jsonSchema.description = def.description;
    if (refs.markdownDescription) {
      jsonSchema.markdownDescription = def.description;
    }
  }
  return jsonSchema;
};

// node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs
var zodToJsonSchema2 = (schema, options) => {
  const refs = getRefs2(options);
  const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
  const main = parseDef2(schema._def, name === void 0 ? refs : {
    ...refs,
    currentPath: [...refs.basePath, refs.definitionPath, name]
  }, false) ?? {};
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
  if (title !== void 0) {
    main.title = title;
  }
  const definitions = (() => {
    if (isEmptyObj2(refs.definitions)) {
      return void 0;
    }
    const definitions2 = {};
    const processedDefinitions = /* @__PURE__ */ new Set();
    for (let i3 = 0; i3 < 500; i3++) {
      const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));
      if (newDefinitions.length === 0)
        break;
      for (const [key, schema2] of newDefinitions) {
        definitions2[key] = parseDef2(zodDef(schema2), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};
        processedDefinitions.add(key);
      }
    }
    return definitions2;
  })();
  const combined = name === void 0 ? definitions ? {
    ...main,
    [refs.definitionPath]: definitions
  } : main : refs.nameStrategy === "duplicate-ref" ? {
    ...main,
    ...definitions || refs.seenRefs.size ? {
      [refs.definitionPath]: {
        ...definitions,
        // only actually duplicate the schema definition if it was ever referenced
        // otherwise the duplication is completely pointless
        ...refs.seenRefs.size ? { [name]: main } : void 0
      }
    } : void 0
  } : {
    $ref: [...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name].join("/"),
    [refs.definitionPath]: {
      ...definitions,
      [name]: main
    }
  };
  if (refs.target === "jsonSchema7") {
    combined.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (refs.target === "jsonSchema2019-09") {
    combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
  }
  return combined;
};

// node_modules/openai/helpers/zod.mjs
function zodToJsonSchema3(schema, options) {
  return zodToJsonSchema2(schema, {
    openaiStrictMode: true,
    name: options.name,
    nameStrategy: "duplicate-ref",
    $refStrategy: "extract-to-root",
    nullableStrategy: "property"
  });
}
function zodResponseFormat(zodObject, name, props) {
  return makeParseableResponseFormat({
    type: "json_schema",
    json_schema: {
      ...props,
      name,
      strict: true,
      schema: zodToJsonSchema3(zodObject, { name })
    }
  }, (content) => zodObject.parse(JSON.parse(content)));
}
function zodFunction(options) {
  return makeParseableTool({
    type: "function",
    function: {
      name: options.name,
      parameters: zodToJsonSchema3(options.parameters, { name: options.name }),
      strict: true,
      ...options.description ? { description: options.description } : void 0
    }
  }, {
    callback: options.function,
    parser: (args) => options.parameters.parse(JSON.parse(args))
  });
}

// node_modules/@langchain/openai/dist/utils/azure.js
function getEndpoint(config) {
  const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config;
  if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) {
    return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`;
  }
  if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) {
    return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`;
  }
  if (azureOpenAIApiKey || azureADTokenProvider) {
    if (!azureOpenAIApiInstanceName) {
      throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");
    }
    if (!azureOpenAIApiDeploymentName) {
      throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");
    }
    return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`;
  }
  return baseURL;
}

// node_modules/@langchain/openai/dist/utils/openai.js
init_esm();

// node_modules/@langchain/openai/dist/utils/errors.js
function addLangChainErrorFields2(error, lc_error_code) {
  error.lc_error_code = lc_error_code;
  error.message = `${error.message}

Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/
`;
  return error;
}

// node_modules/@langchain/openai/dist/utils/openai.js
function wrapOpenAIClientError(e3) {
  let error;
  if (e3.constructor.name === APIConnectionTimeoutError.name) {
    error = new Error(e3.message);
    error.name = "TimeoutError";
  } else if (e3.constructor.name === APIUserAbortError.name) {
    error = new Error(e3.message);
    error.name = "AbortError";
  } else if (e3.status === 400 && e3.message.includes("tool_calls")) {
    error = addLangChainErrorFields2(e3, "INVALID_TOOL_RESULTS");
  } else if (e3.status === 401) {
    error = addLangChainErrorFields2(e3, "MODEL_AUTHENTICATION");
  } else if (e3.status === 429) {
    error = addLangChainErrorFields2(e3, "MODEL_RATE_LIMIT");
  } else if (e3.status === 404) {
    error = addLangChainErrorFields2(e3, "MODEL_NOT_FOUND");
  } else {
    error = e3;
  }
  return error;
}
function formatToOpenAIToolChoice(toolChoice) {
  if (!toolChoice) {
    return void 0;
  } else if (toolChoice === "any" || toolChoice === "required") {
    return "required";
  } else if (toolChoice === "auto") {
    return "auto";
  } else if (toolChoice === "none") {
    return "none";
  } else if (typeof toolChoice === "string") {
    return {
      type: "function",
      function: {
        name: toolChoice
      }
    };
  } else {
    return toolChoice;
  }
}

// node_modules/@langchain/openai/dist/utils/openai-format-fndef.js
function isAnyOfProp(prop) {
  return prop.anyOf !== void 0 && Array.isArray(prop.anyOf);
}
function formatFunctionDefinitions(functions) {
  const lines = ["namespace functions {", ""];
  for (const f3 of functions) {
    if (f3.description) {
      lines.push(`// ${f3.description}`);
    }
    if (Object.keys(f3.parameters.properties ?? {}).length > 0) {
      lines.push(`type ${f3.name} = (_: {`);
      lines.push(formatObjectProperties(f3.parameters, 0));
      lines.push("}) => any;");
    } else {
      lines.push(`type ${f3.name} = () => any;`);
    }
    lines.push("");
  }
  lines.push("} // namespace functions");
  return lines.join("\n");
}
function formatObjectProperties(obj, indent) {
  const lines = [];
  for (const [name, param] of Object.entries(obj.properties ?? {})) {
    if (param.description && indent < 2) {
      lines.push(`// ${param.description}`);
    }
    if (obj.required?.includes(name)) {
      lines.push(`${name}: ${formatType(param, indent)},`);
    } else {
      lines.push(`${name}?: ${formatType(param, indent)},`);
    }
  }
  return lines.map((line) => " ".repeat(indent) + line).join("\n");
}
function formatType(param, indent) {
  if (isAnyOfProp(param)) {
    return param.anyOf.map((v5) => formatType(v5, indent)).join(" | ");
  }
  switch (param.type) {
    case "string":
      if (param.enum) {
        return param.enum.map((v5) => `"${v5}"`).join(" | ");
      }
      return "string";
    case "number":
      if (param.enum) {
        return param.enum.map((v5) => `${v5}`).join(" | ");
      }
      return "number";
    case "integer":
      if (param.enum) {
        return param.enum.map((v5) => `${v5}`).join(" | ");
      }
      return "number";
    case "boolean":
      return "boolean";
    case "null":
      return "null";
    case "object":
      return ["{", formatObjectProperties(param, indent + 2), "}"].join("\n");
    case "array":
      if (param.items) {
        return `${formatType(param.items, indent)}[]`;
      }
      return "any[]";
    default:
      return "";
  }
}

// node_modules/@langchain/openai/dist/utils/tools.js
function _convertToOpenAITool(tool2, fields) {
  let toolDef;
  if (isLangChainTool(tool2)) {
    const oaiToolDef = zodFunction({
      name: tool2.name,
      parameters: tool2.schema,
      description: tool2.description
    });
    if (!oaiToolDef.function.parameters) {
      toolDef = {
        type: "function",
        function: convertToOpenAIFunction(tool2, fields)
      };
    } else {
      toolDef = {
        type: oaiToolDef.type,
        function: {
          name: oaiToolDef.function.name,
          description: oaiToolDef.function.description,
          parameters: oaiToolDef.function.parameters,
          ...fields?.strict !== void 0 ? { strict: fields.strict } : {}
        }
      };
    }
  } else {
    toolDef = tool2;
  }
  if (fields?.strict !== void 0) {
    toolDef.function.strict = fields.strict;
  }
  return toolDef;
}

// node_modules/@langchain/openai/dist/chat_models.js
function extractGenericMessageCustomRole(message) {
  if (message.role !== "system" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") {
    console.warn(`Unknown message role: ${message.role}`);
  }
  return message.role;
}
function messageToOpenAIRole(message) {
  const type = message._getType();
  switch (type) {
    case "system":
      return "system";
    case "ai":
      return "assistant";
    case "human":
      return "user";
    case "function":
      return "function";
    case "tool":
      return "tool";
    case "generic": {
      if (!ChatMessage.isInstance(message))
        throw new Error("Invalid generic chat message");
      return extractGenericMessageCustomRole(message);
    }
    default:
      throw new Error(`Unknown message type: ${type}`);
  }
}
function openAIResponseToChatMessage(message, rawResponse, includeRawResponse) {
  const rawToolCalls = message.tool_calls;
  switch (message.role) {
    case "assistant": {
      const toolCalls = [];
      const invalidToolCalls = [];
      for (const rawToolCall of rawToolCalls ?? []) {
        try {
          toolCalls.push(parseToolCall2(rawToolCall, { returnId: true }));
        } catch (e3) {
          invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e3.message));
        }
      }
      const additional_kwargs = {
        function_call: message.function_call,
        tool_calls: rawToolCalls
      };
      if (includeRawResponse !== void 0) {
        additional_kwargs.__raw_response = rawResponse;
      }
      let response_metadata;
      if (rawResponse.system_fingerprint) {
        response_metadata = {
          usage: { ...rawResponse.usage },
          system_fingerprint: rawResponse.system_fingerprint
        };
      }
      if (message.audio) {
        additional_kwargs.audio = message.audio;
      }
      return new AIMessage({
        content: message.content || "",
        tool_calls: toolCalls,
        invalid_tool_calls: invalidToolCalls,
        additional_kwargs,
        response_metadata,
        id: rawResponse.id
      });
    }
    default:
      return new ChatMessage(message.content || "", message.role ?? "unknown");
  }
}
function _convertDeltaToMessageChunk(delta, rawResponse, defaultRole, includeRawResponse) {
  const role = delta.role ?? defaultRole;
  const content = delta.content ?? "";
  let additional_kwargs;
  if (delta.function_call) {
    additional_kwargs = {
      function_call: delta.function_call
    };
  } else if (delta.tool_calls) {
    additional_kwargs = {
      tool_calls: delta.tool_calls
    };
  } else {
    additional_kwargs = {};
  }
  if (includeRawResponse) {
    additional_kwargs.__raw_response = rawResponse;
  }
  if (delta.audio) {
    additional_kwargs.audio = {
      ...delta.audio,
      index: rawResponse.choices[0].index
    };
  }
  const response_metadata = { usage: { ...rawResponse.usage } };
  if (role === "user") {
    return new HumanMessageChunk({ content, response_metadata });
  } else if (role === "assistant") {
    const toolCallChunks = [];
    if (Array.isArray(delta.tool_calls)) {
      for (const rawToolCall of delta.tool_calls) {
        toolCallChunks.push({
          name: rawToolCall.function?.name,
          args: rawToolCall.function?.arguments,
          id: rawToolCall.id,
          index: rawToolCall.index,
          type: "tool_call_chunk"
        });
      }
    }
    return new AIMessageChunk({
      content,
      tool_call_chunks: toolCallChunks,
      additional_kwargs,
      id: rawResponse.id,
      response_metadata
    });
  } else if (role === "system") {
    return new SystemMessageChunk({ content, response_metadata });
  } else if (role === "function") {
    return new FunctionMessageChunk({
      content,
      additional_kwargs,
      name: delta.name,
      response_metadata
    });
  } else if (role === "tool") {
    return new ToolMessageChunk({
      content,
      additional_kwargs,
      tool_call_id: delta.tool_call_id,
      response_metadata
    });
  } else {
    return new ChatMessageChunk({ content, role, response_metadata });
  }
}
function _convertMessagesToOpenAIParams(messages) {
  return messages.flatMap((message) => {
    const completionParam = {
      role: messageToOpenAIRole(message),
      content: message.content
    };
    if (message.name != null) {
      completionParam.name = message.name;
    }
    if (message.additional_kwargs.function_call != null) {
      completionParam.function_call = message.additional_kwargs.function_call;
      completionParam.content = null;
    }
    if (isAIMessage(message) && !!message.tool_calls?.length) {
      completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI);
      completionParam.content = null;
    } else {
      if (message.additional_kwargs.tool_calls != null) {
        completionParam.tool_calls = message.additional_kwargs.tool_calls;
      }
      if (message.tool_call_id != null) {
        completionParam.tool_call_id = message.tool_call_id;
      }
    }
    if (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === "object" && "id" in message.additional_kwargs.audio) {
      const audioMessage = {
        role: "assistant",
        audio: {
          id: message.additional_kwargs.audio.id
        }
      };
      return [completionParam, audioMessage];
    }
    return completionParam;
  });
}
function _convertChatOpenAIToolTypeToOpenAITool(tool2, fields) {
  if (isOpenAITool(tool2)) {
    if (fields?.strict !== void 0) {
      return {
        ...tool2,
        function: {
          ...tool2.function,
          strict: fields.strict
        }
      };
    }
    return tool2;
  }
  return _convertToOpenAITool(tool2, fields);
}
var ChatOpenAI = class extends BaseChatModel {
  static lc_name() {
    return "ChatOpenAI";
  }
  get callKeys() {
    return [
      ...super.callKeys,
      "options",
      "function_call",
      "functions",
      "tools",
      "tool_choice",
      "promptIndex",
      "response_format",
      "seed"
    ];
  }
  get lc_secrets() {
    return {
      openAIApiKey: "OPENAI_API_KEY",
      apiKey: "OPENAI_API_KEY",
      azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
      organization: "OPENAI_ORGANIZATION"
    };
  }
  get lc_aliases() {
    return {
      modelName: "model",
      openAIApiKey: "openai_api_key",
      apiKey: "openai_api_key",
      azureOpenAIApiVersion: "azure_openai_api_version",
      azureOpenAIApiKey: "azure_openai_api_key",
      azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
      azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name"
    };
  }
  constructor(fields, configuration2) {
    super(fields ?? {});
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1
    });
    Object.defineProperty(this, "topP", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1
    });
    Object.defineProperty(this, "frequencyPenalty", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 0
    });
    Object.defineProperty(this, "presencePenalty", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 0
    });
    Object.defineProperty(this, "n", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1
    });
    Object.defineProperty(this, "logitBias", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "gpt-3.5-turbo"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "gpt-3.5-turbo"
    });
    Object.defineProperty(this, "modelKwargs", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stop", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stopSequences", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "user", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "timeout", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "streamUsage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "maxTokens", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "logprobs", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "topLogprobs", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "openAIApiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiVersion", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureADTokenProvider", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiInstanceName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIBasePath", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIEndpoint", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "organization", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "__includeRawResponse", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "clientConfig", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "supportsStrictToolCalling", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "audio", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "modalities", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? fields?.configuration?.apiKey ?? getEnvironmentVariable2("OPENAI_API_KEY");
    this.apiKey = this.openAIApiKey;
    this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? getEnvironmentVariable2("AZURE_OPENAI_API_KEY");
    this.azureADTokenProvider = fields?.azureADTokenProvider ?? void 0;
    if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) {
      throw new Error("OpenAI or Azure OpenAI API key or Token Provider not found");
    }
    this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable2("AZURE_OPENAI_API_INSTANCE_NAME");
    this.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? getEnvironmentVariable2("AZURE_OPENAI_API_DEPLOYMENT_NAME");
    this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? getEnvironmentVariable2("AZURE_OPENAI_API_VERSION");
    this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable2("AZURE_OPENAI_BASE_PATH");
    this.organization = fields?.configuration?.organization ?? getEnvironmentVariable2("OPENAI_ORGANIZATION");
    this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable2("AZURE_OPENAI_ENDPOINT");
    this.modelName = fields?.model ?? fields?.modelName ?? this.model;
    this.model = this.modelName;
    this.modelKwargs = fields?.modelKwargs ?? {};
    this.timeout = fields?.timeout;
    this.temperature = fields?.temperature ?? this.temperature;
    this.topP = fields?.topP ?? this.topP;
    this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
    this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
    this.maxTokens = fields?.maxTokens;
    this.logprobs = fields?.logprobs;
    this.topLogprobs = fields?.topLogprobs;
    this.n = fields?.n ?? this.n;
    this.logitBias = fields?.logitBias;
    this.stop = fields?.stopSequences ?? fields?.stop;
    this.stopSequences = this?.stop;
    this.user = fields?.user;
    this.__includeRawResponse = fields?.__includeRawResponse;
    this.audio = fields?.audio;
    this.modalities = fields?.modalities;
    if (this.azureOpenAIApiKey || this.azureADTokenProvider) {
      if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath && !this.azureOpenAIEndpoint) {
        throw new Error("Azure OpenAI API instance name not found");
      }
      if (!this.azureOpenAIApiDeploymentName && this.azureOpenAIBasePath) {
        const parts = this.azureOpenAIBasePath.split("/openai/deployments/");
        if (parts.length === 2) {
          const [, deployment] = parts;
          this.azureOpenAIApiDeploymentName = deployment;
        }
      }
      if (!this.azureOpenAIApiDeploymentName) {
        throw new Error("Azure OpenAI API deployment name not found");
      }
      if (!this.azureOpenAIApiVersion) {
        throw new Error("Azure OpenAI API version not found");
      }
      this.apiKey = this.apiKey ?? "";
      this.streamUsage = false;
    }
    this.streaming = fields?.streaming ?? false;
    this.streamUsage = fields?.streamUsage ?? this.streamUsage;
    this.clientConfig = {
      apiKey: this.apiKey,
      organization: this.organization,
      baseURL: configuration2?.basePath ?? fields?.configuration?.basePath,
      dangerouslyAllowBrowser: true,
      defaultHeaders: configuration2?.baseOptions?.headers ?? fields?.configuration?.baseOptions?.headers,
      defaultQuery: configuration2?.baseOptions?.params ?? fields?.configuration?.baseOptions?.params,
      ...configuration2,
      ...fields?.configuration
    };
    if (fields?.supportsStrictToolCalling !== void 0) {
      this.supportsStrictToolCalling = fields.supportsStrictToolCalling;
    }
  }
  getLsParams(options) {
    const params = this.invocationParams(options);
    return {
      ls_provider: "openai",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: params.temperature ?? void 0,
      ls_max_tokens: params.max_tokens ?? void 0,
      ls_stop: options.stop
    };
  }
  bindTools(tools, kwargs) {
    let strict2;
    if (kwargs?.strict !== void 0) {
      strict2 = kwargs.strict;
    } else if (this.supportsStrictToolCalling !== void 0) {
      strict2 = this.supportsStrictToolCalling;
    }
    return this.bind({
      tools: tools.map((tool2) => _convertChatOpenAIToolTypeToOpenAITool(tool2, { strict: strict2 })),
      ...kwargs
    });
  }
  createResponseFormat(resFormat) {
    if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && isZodSchema2(resFormat.json_schema.schema)) {
      return zodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, {
        description: resFormat.json_schema.description
      });
    }
    return resFormat;
  }
  /**
   * Get the parameters used to invoke the model
   */
  invocationParams(options, extra) {
    let strict2;
    if (options?.strict !== void 0) {
      strict2 = options.strict;
    } else if (this.supportsStrictToolCalling !== void 0) {
      strict2 = this.supportsStrictToolCalling;
    }
    let streamOptionsConfig = {};
    if (options?.stream_options !== void 0) {
      streamOptionsConfig = { stream_options: options.stream_options };
    } else if (this.streamUsage && (this.streaming || extra?.streaming)) {
      streamOptionsConfig = { stream_options: { include_usage: true } };
    }
    const params = {
      model: this.model,
      temperature: this.temperature,
      top_p: this.topP,
      frequency_penalty: this.frequencyPenalty,
      presence_penalty: this.presencePenalty,
      max_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens,
      logprobs: this.logprobs,
      top_logprobs: this.topLogprobs,
      n: this.n,
      logit_bias: this.logitBias,
      stop: options?.stop ?? this.stopSequences,
      user: this.user,
      // if include_usage is set or streamUsage then stream must be set to true.
      stream: this.streaming,
      functions: options?.functions,
      function_call: options?.function_call,
      tools: options?.tools?.length ? options.tools.map((tool2) => _convertChatOpenAIToolTypeToOpenAITool(tool2, { strict: strict2 })) : void 0,
      tool_choice: formatToOpenAIToolChoice(options?.tool_choice),
      response_format: this.createResponseFormat(options?.response_format),
      seed: options?.seed,
      ...streamOptionsConfig,
      parallel_tool_calls: options?.parallel_tool_calls,
      ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {},
      ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {},
      ...this.modelKwargs
    };
    if (options?.prediction !== void 0) {
      params.prediction = options.prediction;
    }
    return params;
  }
  /** @ignore */
  _identifyingParams() {
    return {
      model_name: this.model,
      ...this.invocationParams(),
      ...this.clientConfig
    };
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const messagesMapped = _convertMessagesToOpenAIParams(messages);
    const params = {
      ...this.invocationParams(options, {
        streaming: true
      }),
      messages: messagesMapped,
      stream: true
    };
    let defaultRole;
    const streamIterable = await this.completionWithRetry(params, options);
    let usage;
    for await (const data of streamIterable) {
      const choice = data?.choices?.[0];
      if (data.usage) {
        usage = data.usage;
      }
      if (!choice) {
        continue;
      }
      const { delta } = choice;
      if (!delta) {
        continue;
      }
      const chunk = _convertDeltaToMessageChunk(delta, data, defaultRole, this.__includeRawResponse);
      defaultRole = delta.role ?? defaultRole;
      const newTokenIndices = {
        prompt: options.promptIndex ?? 0,
        completion: choice.index ?? 0
      };
      if (typeof chunk.content !== "string") {
        console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");
        continue;
      }
      const generationInfo = { ...newTokenIndices };
      if (choice.finish_reason != null) {
        generationInfo.finish_reason = choice.finish_reason;
        generationInfo.system_fingerprint = data.system_fingerprint;
      }
      if (this.logprobs) {
        generationInfo.logprobs = choice.logprobs;
      }
      const generationChunk = new ChatGenerationChunk({
        message: chunk,
        text: chunk.content,
        generationInfo
      });
      yield generationChunk;
      await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk });
    }
    if (usage) {
      const inputTokenDetails = {
        ...usage.prompt_tokens_details?.audio_tokens !== null && {
          audio: usage.prompt_tokens_details?.audio_tokens
        },
        ...usage.prompt_tokens_details?.cached_tokens !== null && {
          cache_read: usage.prompt_tokens_details?.cached_tokens
        }
      };
      const outputTokenDetails = {
        ...usage.completion_tokens_details?.audio_tokens !== null && {
          audio: usage.completion_tokens_details?.audio_tokens
        },
        ...usage.completion_tokens_details?.reasoning_tokens !== null && {
          reasoning: usage.completion_tokens_details?.reasoning_tokens
        }
      };
      const generationChunk = new ChatGenerationChunk({
        message: new AIMessageChunk({
          content: "",
          response_metadata: {
            usage: { ...usage }
          },
          usage_metadata: {
            input_tokens: usage.prompt_tokens,
            output_tokens: usage.completion_tokens,
            total_tokens: usage.total_tokens,
            ...Object.keys(inputTokenDetails).length > 0 && {
              input_token_details: inputTokenDetails
            },
            ...Object.keys(outputTokenDetails).length > 0 && {
              output_token_details: outputTokenDetails
            }
          }
        }),
        text: ""
      });
      yield generationChunk;
    }
    if (options.signal?.aborted) {
      throw new Error("AbortError");
    }
  }
  /**
   * Get the identifying parameters for the model
   *
   */
  identifyingParams() {
    return this._identifyingParams();
  }
  /** @ignore */
  async _generate(messages, options, runManager) {
    const usageMetadata = {};
    const params = this.invocationParams(options);
    const messagesMapped = _convertMessagesToOpenAIParams(messages);
    if (params.stream) {
      const stream = this._streamResponseChunks(messages, options, runManager);
      const finalChunks = {};
      for await (const chunk of stream) {
        chunk.message.response_metadata = {
          ...chunk.generationInfo,
          ...chunk.message.response_metadata
        };
        const index2 = chunk.generationInfo?.completion ?? 0;
        if (finalChunks[index2] === void 0) {
          finalChunks[index2] = chunk;
        } else {
          finalChunks[index2] = finalChunks[index2].concat(chunk);
        }
      }
      const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_2, value]) => value);
      const { functions, function_call } = this.invocationParams(options);
      const promptTokenUsage = await this.getEstimatedTokenCountFromPrompt(messages, functions, function_call);
      const completionTokenUsage = await this.getNumTokensFromGenerations(generations);
      usageMetadata.input_tokens = promptTokenUsage;
      usageMetadata.output_tokens = completionTokenUsage;
      usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage;
      return {
        generations,
        llmOutput: {
          estimatedTokenUsage: {
            promptTokens: usageMetadata.input_tokens,
            completionTokens: usageMetadata.output_tokens,
            totalTokens: usageMetadata.total_tokens
          }
        }
      };
    } else {
      let data;
      if (options.response_format && options.response_format.type === "json_schema") {
        data = await this.betaParsedCompletionWithRetry({
          ...params,
          stream: false,
          messages: messagesMapped
        }, {
          signal: options?.signal,
          ...options?.options
        });
      } else {
        data = await this.completionWithRetry({
          ...params,
          stream: false,
          messages: messagesMapped
        }, {
          signal: options?.signal,
          ...options?.options
        });
      }
      const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {};
      if (completionTokens) {
        usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens;
      }
      if (promptTokens) {
        usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens;
      }
      if (totalTokens) {
        usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens;
      }
      if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) {
        usageMetadata.input_token_details = {
          ...promptTokensDetails?.audio_tokens !== null && {
            audio: promptTokensDetails?.audio_tokens
          },
          ...promptTokensDetails?.cached_tokens !== null && {
            cache_read: promptTokensDetails?.cached_tokens
          }
        };
      }
      if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) {
        usageMetadata.output_token_details = {
          ...completionTokensDetails?.audio_tokens !== null && {
            audio: completionTokensDetails?.audio_tokens
          },
          ...completionTokensDetails?.reasoning_tokens !== null && {
            reasoning: completionTokensDetails?.reasoning_tokens
          }
        };
      }
      const generations = [];
      for (const part of data?.choices ?? []) {
        const text = part.message?.content ?? "";
        const generation = {
          text,
          message: openAIResponseToChatMessage(part.message ?? { role: "assistant" }, data, this.__includeRawResponse)
        };
        generation.generationInfo = {
          ...part.finish_reason ? { finish_reason: part.finish_reason } : {},
          ...part.logprobs ? { logprobs: part.logprobs } : {}
        };
        if (isAIMessage(generation.message)) {
          generation.message.usage_metadata = usageMetadata;
        }
        generation.message = new AIMessage({
          ...generation.message
        });
        generations.push(generation);
      }
      return {
        generations,
        llmOutput: {
          tokenUsage: {
            promptTokens: usageMetadata.input_tokens,
            completionTokens: usageMetadata.output_tokens,
            totalTokens: usageMetadata.total_tokens
          }
        }
      };
    }
  }
  /**
   * Estimate the number of tokens a prompt will use.
   * Modified from: https://github.com/hmarr/openai-chat-tokens/blob/main/src/index.ts
   */
  async getEstimatedTokenCountFromPrompt(messages, functions, function_call) {
    let tokens = (await this.getNumTokensFromMessages(messages)).totalCount;
    if (functions && function_call !== "auto") {
      const promptDefinitions = formatFunctionDefinitions(functions);
      tokens += await this.getNumTokens(promptDefinitions);
      tokens += 9;
    }
    if (functions && messages.find((m3) => m3._getType() === "system")) {
      tokens -= 4;
    }
    if (function_call === "none") {
      tokens += 1;
    } else if (typeof function_call === "object") {
      tokens += await this.getNumTokens(function_call.name) + 4;
    }
    return tokens;
  }
  /**
   * Estimate the number of tokens an array of generations have used.
   */
  async getNumTokensFromGenerations(generations) {
    const generationUsages = await Promise.all(generations.map(async (generation) => {
      if (generation.message.additional_kwargs?.function_call) {
        return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0];
      } else {
        return await this.getNumTokens(generation.message.content);
      }
    }));
    return generationUsages.reduce((a3, b3) => a3 + b3, 0);
  }
  async getNumTokensFromMessages(messages) {
    let totalCount = 0;
    let tokensPerMessage = 0;
    let tokensPerName = 0;
    if (this.model === "gpt-3.5-turbo-0301") {
      tokensPerMessage = 4;
      tokensPerName = -1;
    } else {
      tokensPerMessage = 3;
      tokensPerName = 1;
    }
    const countPerMessage = await Promise.all(messages.map(async (message) => {
      const textCount = await this.getNumTokens(message.content);
      const roleCount = await this.getNumTokens(messageToOpenAIRole(message));
      const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0;
      let count5 = textCount + tokensPerMessage + roleCount + nameCount;
      const openAIMessage = message;
      if (openAIMessage._getType() === "function") {
        count5 -= 2;
      }
      if (openAIMessage.additional_kwargs?.function_call) {
        count5 += 3;
      }
      if (openAIMessage?.additional_kwargs.function_call?.name) {
        count5 += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);
      }
      if (openAIMessage.additional_kwargs.function_call?.arguments) {
        try {
          count5 += await this.getNumTokens(
            // Remove newlines and spaces
            JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))
          );
        } catch (error) {
          console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call));
          count5 += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);
        }
      }
      totalCount += count5;
      return count5;
    }));
    totalCount += 3;
    return { totalCount, countPerMessage };
  }
  async completionWithRetry(request, options) {
    const requestOptions = this._getClientOptions(options);
    return this.caller.call(async () => {
      try {
        const res = await this.client.chat.completions.create(request, requestOptions);
        return res;
      } catch (e3) {
        const error = wrapOpenAIClientError(e3);
        throw error;
      }
    });
  }
  /**
   * Call the beta chat completions parse endpoint. This should only be called if
   * response_format is set to "json_object".
   * @param {OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming} request
   * @param {OpenAICoreRequestOptions | undefined} options
   */
  async betaParsedCompletionWithRetry(request, options) {
    const requestOptions = this._getClientOptions(options);
    return this.caller.call(async () => {
      try {
        const res = await this.client.beta.chat.completions.parse(request, requestOptions);
        return res;
      } catch (e3) {
        const error = wrapOpenAIClientError(e3);
        throw error;
      }
    });
  }
  _getClientOptions(options) {
    if (!this.client) {
      const openAIEndpointConfig = {
        azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,
        azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,
        azureOpenAIApiKey: this.azureOpenAIApiKey,
        azureOpenAIBasePath: this.azureOpenAIBasePath,
        baseURL: this.clientConfig.baseURL,
        azureOpenAIEndpoint: this.azureOpenAIEndpoint
      };
      const endpoint = getEndpoint(openAIEndpointConfig);
      const params = {
        ...this.clientConfig,
        baseURL: endpoint,
        timeout: this.timeout,
        maxRetries: 0
      };
      if (!params.baseURL) {
        delete params.baseURL;
      }
      this.client = new OpenAI(params);
    }
    const requestOptions = {
      ...this.clientConfig,
      ...options
    };
    if (this.azureOpenAIApiKey) {
      requestOptions.headers = {
        "api-key": this.azureOpenAIApiKey,
        ...requestOptions.headers
      };
      requestOptions.query = {
        "api-version": this.azureOpenAIApiVersion,
        ...requestOptions.query
      };
    }
    return requestOptions;
  }
  _llmType() {
    return "openai";
  }
  /** @ignore */
  _combineLLMOutput(...llmOutputs) {
    return llmOutputs.reduce((acc, llmOutput) => {
      if (llmOutput && llmOutput.tokenUsage) {
        acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0;
        acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0;
        acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0;
      }
      return acc;
    }, {
      tokenUsage: {
        completionTokens: 0,
        promptTokens: 0,
        totalTokens: 0
      }
    });
  }
  withStructuredOutput(outputSchema, config) {
    let schema;
    let name;
    let method;
    let includeRaw;
    if (isStructuredOutputMethodParams(outputSchema)) {
      schema = outputSchema.schema;
      name = outputSchema.name;
      method = outputSchema.method;
      includeRaw = outputSchema.includeRaw;
    } else {
      schema = outputSchema;
      name = config?.name;
      method = config?.method;
      includeRaw = config?.includeRaw;
    }
    let llm;
    let outputParser;
    if (config?.strict !== void 0 && method === "jsonMode") {
      throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");
    }
    if (method === "jsonMode") {
      llm = this.bind({
        response_format: { type: "json_object" }
      });
      if (isZodSchema2(schema)) {
        outputParser = StructuredOutputParser.fromZodSchema(schema);
      } else {
        outputParser = new JsonOutputParser();
      }
    } else if (method === "jsonSchema") {
      llm = this.bind({
        response_format: {
          type: "json_schema",
          json_schema: {
            name: name ?? "extract",
            description: schema.description,
            schema,
            strict: config?.strict
          }
        }
      });
      if (isZodSchema2(schema)) {
        outputParser = StructuredOutputParser.fromZodSchema(schema);
      } else {
        outputParser = new JsonOutputParser();
      }
    } else {
      let functionName = name ?? "extract";
      if (isZodSchema2(schema)) {
        const asJsonSchema = zodToJsonSchema(schema);
        llm = this.bind({
          tools: [
            {
              type: "function",
              function: {
                name: functionName,
                description: asJsonSchema.description,
                parameters: asJsonSchema
              }
            }
          ],
          tool_choice: {
            type: "function",
            function: {
              name: functionName
            }
          },
          // Do not pass `strict` argument to OpenAI if `config.strict` is undefined
          ...config?.strict !== void 0 ? { strict: config.strict } : {}
        });
        outputParser = new JsonOutputKeyToolsParser({
          returnSingle: true,
          keyName: functionName,
          zodSchema: schema
        });
      } else {
        let openAIFunctionDefinition;
        if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
          openAIFunctionDefinition = schema;
          functionName = schema.name;
        } else {
          functionName = schema.title ?? functionName;
          openAIFunctionDefinition = {
            name: functionName,
            description: schema.description ?? "",
            parameters: schema
          };
        }
        llm = this.bind({
          tools: [
            {
              type: "function",
              function: openAIFunctionDefinition
            }
          ],
          tool_choice: {
            type: "function",
            function: {
              name: functionName
            }
          },
          // Do not pass `strict` argument to OpenAI if `config.strict` is undefined
          ...config?.strict !== void 0 ? { strict: config.strict } : {}
        });
        outputParser = new JsonOutputKeyToolsParser({
          returnSingle: true,
          keyName: functionName
        });
      }
    }
    if (!includeRaw) {
      return llm.pipe(outputParser);
    }
    const parserAssign = RunnablePassthrough.assign({
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parsed: (input, config2) => outputParser.invoke(input.raw, config2)
    });
    const parserNone = RunnablePassthrough.assign({
      parsed: () => null
    });
    const parsedWithFallback = parserAssign.withFallbacks({
      fallbacks: [parserNone]
    });
    return RunnableSequence.from([
      {
        raw: llm
      },
      parsedWithFallback
    ]);
  }
};
function isZodSchema2(input) {
  return typeof input?.parse === "function";
}
function isStructuredOutputMethodParams(x2) {
  return x2 !== void 0 && // eslint-disable-next-line @typescript-eslint/no-explicit-any
  typeof x2.schema === "object";
}

// node_modules/@langchain/openai/dist/llms.js
init_base9();
init_outputs2();

// node_modules/@langchain/openai/dist/legacy.js
init_outputs2();

// node_modules/@langchain/openai/dist/embeddings.js
var OpenAIEmbeddings = class extends Embeddings {
  constructor(fields, configuration2) {
    const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
    super(fieldsWithDefaults);
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "text-embedding-ada-002"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "text-embedding-ada-002"
    });
    Object.defineProperty(this, "batchSize", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 512
    });
    Object.defineProperty(this, "stripNewLines", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "dimensions", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "timeout", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiVersion", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureADTokenProvider", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiInstanceName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "azureOpenAIBasePath", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "organization", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "clientConfig", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    let apiKey = fieldsWithDefaults?.apiKey ?? fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable2("OPENAI_API_KEY");
    const azureApiKey = fieldsWithDefaults?.azureOpenAIApiKey ?? getEnvironmentVariable2("AZURE_OPENAI_API_KEY");
    this.azureADTokenProvider = fields?.azureADTokenProvider ?? void 0;
    if (!azureApiKey && !apiKey && !this.azureADTokenProvider) {
      throw new Error("OpenAI or Azure OpenAI API key or Token Provider not found");
    }
    const azureApiInstanceName = fieldsWithDefaults?.azureOpenAIApiInstanceName ?? getEnvironmentVariable2("AZURE_OPENAI_API_INSTANCE_NAME");
    const azureApiDeploymentName = (fieldsWithDefaults?.azureOpenAIApiEmbeddingsDeploymentName || fieldsWithDefaults?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable2("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable2("AZURE_OPENAI_API_DEPLOYMENT_NAME"));
    const azureApiVersion = fieldsWithDefaults?.azureOpenAIApiVersion ?? getEnvironmentVariable2("AZURE_OPENAI_API_VERSION");
    this.azureOpenAIBasePath = fieldsWithDefaults?.azureOpenAIBasePath ?? getEnvironmentVariable2("AZURE_OPENAI_BASE_PATH");
    this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable2("OPENAI_ORGANIZATION");
    this.modelName = fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;
    this.model = this.modelName;
    this.batchSize = fieldsWithDefaults?.batchSize ?? (azureApiKey ? 1 : this.batchSize);
    this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
    this.timeout = fieldsWithDefaults?.timeout;
    this.dimensions = fieldsWithDefaults?.dimensions;
    this.azureOpenAIApiVersion = azureApiVersion;
    this.azureOpenAIApiKey = azureApiKey;
    this.azureOpenAIApiInstanceName = azureApiInstanceName;
    this.azureOpenAIApiDeploymentName = azureApiDeploymentName;
    if (this.azureOpenAIApiKey || this.azureADTokenProvider) {
      if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) {
        throw new Error("Azure OpenAI API instance name not found");
      }
      if (!this.azureOpenAIApiDeploymentName) {
        throw new Error("Azure OpenAI API deployment name not found");
      }
      if (!this.azureOpenAIApiVersion) {
        throw new Error("Azure OpenAI API version not found");
      }
      apiKey = apiKey ?? "";
    }
    this.clientConfig = {
      apiKey,
      organization: this.organization,
      baseURL: configuration2?.basePath,
      dangerouslyAllowBrowser: true,
      defaultHeaders: configuration2?.baseOptions?.headers,
      defaultQuery: configuration2?.baseOptions?.params,
      ...configuration2,
      ...fields?.configuration
    };
  }
  /**
   * Method to generate embeddings for an array of documents. Splits the
   * documents into batches and makes requests to the OpenAI API to generate
   * embeddings.
   * @param texts Array of documents to generate embeddings for.
   * @returns Promise that resolves to a 2D array of embeddings for each document.
   */
  async embedDocuments(texts) {
    const batches = chunkArray(this.stripNewLines ? texts.map((t3) => t3.replace(/\n/g, " ")) : texts, this.batchSize);
    const batchRequests = batches.map((batch) => {
      const params = {
        model: this.model,
        input: batch
      };
      if (this.dimensions) {
        params.dimensions = this.dimensions;
      }
      return this.embeddingWithRetry(params);
    });
    const batchResponses = await Promise.all(batchRequests);
    const embeddings = [];
    for (let i3 = 0; i3 < batchResponses.length; i3 += 1) {
      const batch = batches[i3];
      const { data: batchResponse } = batchResponses[i3];
      for (let j3 = 0; j3 < batch.length; j3 += 1) {
        embeddings.push(batchResponse[j3].embedding);
      }
    }
    return embeddings;
  }
  /**
   * Method to generate an embedding for a single document. Calls the
   * embeddingWithRetry method with the document as the input.
   * @param text Document to generate an embedding for.
   * @returns Promise that resolves to an embedding for the document.
   */
  async embedQuery(text) {
    const params = {
      model: this.model,
      input: this.stripNewLines ? text.replace(/\n/g, " ") : text
    };
    if (this.dimensions) {
      params.dimensions = this.dimensions;
    }
    const { data } = await this.embeddingWithRetry(params);
    return data[0].embedding;
  }
  /**
   * Private method to make a request to the OpenAI API to generate
   * embeddings. Handles the retry logic and returns the response from the
   * API.
   * @param request Request to send to the OpenAI API.
   * @returns Promise that resolves to the response from the API.
   */
  async embeddingWithRetry(request) {
    if (!this.client) {
      const openAIEndpointConfig = {
        azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,
        azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,
        azureOpenAIApiKey: this.azureOpenAIApiKey,
        azureOpenAIBasePath: this.azureOpenAIBasePath,
        baseURL: this.clientConfig.baseURL
      };
      const endpoint = getEndpoint(openAIEndpointConfig);
      const params = {
        ...this.clientConfig,
        baseURL: endpoint,
        timeout: this.timeout,
        maxRetries: 0
      };
      if (!params.baseURL) {
        delete params.baseURL;
      }
      this.client = new OpenAI(params);
    }
    const requestOptions = {};
    if (this.azureOpenAIApiKey) {
      requestOptions.headers = {
        "api-key": this.azureOpenAIApiKey,
        ...requestOptions.headers
      };
      requestOptions.query = {
        "api-version": this.azureOpenAIApiVersion,
        ...requestOptions.query
      };
    }
    return this.caller.call(async () => {
      try {
        const res = await this.client.embeddings.create(request, requestOptions);
        return res;
      } catch (e3) {
        const error = wrapOpenAIClientError(e3);
        throw error;
      }
    });
  }
};

// node_modules/@langchain/core/dist/tools/index.js
init_lib();
init_manager();
init_base8();
init_config();
init_tool();
init_singletons();
init_utils();
var StructuredTool = class extends BaseLangChain {
  get lc_namespace() {
    return ["langchain", "tools"];
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "returnDirect", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "verboseParsingErrors", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "responseFormat", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "content"
    });
    this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors;
    this.responseFormat = fields?.responseFormat ?? this.responseFormat;
  }
  /**
   * Invokes the tool with the provided input and configuration.
   * @param input The input for the tool.
   * @param config Optional configuration for the tool.
   * @returns A Promise that resolves with a string.
   */
  async invoke(input, config) {
    let tool_call_id;
    let toolInput;
    let enrichedConfig = ensureConfig(config);
    if (_isToolCall(input)) {
      tool_call_id = input.id;
      toolInput = input.args;
      enrichedConfig = {
        ...enrichedConfig,
        toolCall: input,
        configurable: {
          ...enrichedConfig.configurable,
          tool_call_id
        }
      };
    } else {
      toolInput = input;
    }
    return this.call(toolInput, enrichedConfig);
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
   *
   * Calls the tool with the provided argument, configuration, and tags. It
   * parses the input according to the schema, handles any errors, and
   * manages callbacks.
   * @param arg The input argument for the tool.
   * @param configArg Optional configuration or callbacks for the tool.
   * @param tags Optional tags for the tool.
   * @returns A Promise that resolves with a string.
   */
  async call(arg, configArg, tags) {
    let parsed;
    try {
      parsed = await this.schema.parseAsync(arg);
    } catch (e3) {
      let message = `Received tool input did not match expected schema`;
      if (this.verboseParsingErrors) {
        message = `${message}
Details: ${e3.message}`;
      }
      throw new ToolInputParsingException(message, JSON.stringify(arg));
    }
    const config = parseCallbackConfigArg(configArg);
    const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
    const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), config.runId, void 0, void 0, void 0, config.runName);
    delete config.runId;
    let result;
    try {
      result = await this._call(parsed, runManager, config);
    } catch (e3) {
      await runManager?.handleToolError(e3);
      throw e3;
    }
    let content;
    let artifact;
    if (this.responseFormat === "content_and_artifact") {
      if (Array.isArray(result) && result.length === 2) {
        [content, artifact] = result;
      } else {
        throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(result)}`);
      }
    } else {
      content = result;
    }
    let toolCallId;
    if (config && "configurable" in config) {
      toolCallId = config.configurable.tool_call_id;
    }
    const formattedOutput = _formatToolOutput({
      content,
      artifact,
      toolCallId,
      name: this.name
    });
    await runManager?.handleToolEnd(formattedOutput);
    return formattedOutput;
  }
};
var Tool = class extends StructuredTool {
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "schema", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: z.object({ input: z.string().optional() }).transform((obj) => obj.input)
    });
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
   *
   * Calls the tool with the provided argument and callbacks. It handles
   * string inputs specifically.
   * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.
   * @param callbacks Optional callbacks for the tool.
   * @returns A Promise that resolves with a string.
   */
  call(arg, callbacks) {
    return super.call(typeof arg === "string" || !arg ? { input: arg } : arg, callbacks);
  }
};
var DynamicTool = class extends Tool {
  static lc_name() {
    return "DynamicTool";
  }
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "name", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "description", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "func", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.name = fields.name;
    this.description = fields.description;
    this.func = fields.func;
    this.returnDirect = fields.returnDirect ?? this.returnDirect;
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
   */
  async call(arg, configArg) {
    const config = parseCallbackConfigArg(configArg);
    if (config.runName === void 0) {
      config.runName = this.name;
    }
    return super.call(arg, config);
  }
  /** @ignore */
  async _call(input, runManager, parentConfig) {
    return this.func(input, runManager, parentConfig);
  }
};
var DynamicStructuredTool = class extends StructuredTool {
  static lc_name() {
    return "DynamicStructuredTool";
  }
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "name", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "description", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "func", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "schema", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.name = fields.name;
    this.description = fields.description;
    this.func = fields.func;
    this.returnDirect = fields.returnDirect ?? this.returnDirect;
    this.schema = isZodSchema(fields.schema) ? fields.schema : z.object({}).passthrough();
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
   */
  async call(arg, configArg, tags) {
    const config = parseCallbackConfigArg(configArg);
    if (config.runName === void 0) {
      config.runName = this.name;
    }
    return super.call(arg, config, tags);
  }
  _call(arg, runManager, parentConfig) {
    return this.func(arg, runManager, parentConfig);
  }
};
function tool(func, fields) {
  if (!fields.schema || isZodSchema(fields.schema) && (!("shape" in fields.schema) || !fields.schema.shape)) {
    return new DynamicTool({
      ...fields,
      description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`,
      func: async (input, runManager, config) => {
        return new Promise((resolve, reject) => {
          const childConfig = patchConfig(config, {
            callbacks: runManager?.getChild()
          });
          void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
            try {
              resolve(func(input, childConfig));
            } catch (e3) {
              reject(e3);
            }
          });
        });
      }
    });
  }
  const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`;
  return new DynamicStructuredTool({
    ...fields,
    description,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    schema: fields.schema,
    // TODO: Consider moving into DynamicStructuredTool constructor
    func: async (input, runManager, config) => {
      return new Promise((resolve, reject) => {
        const childConfig = patchConfig(config, {
          callbacks: runManager?.getChild()
        });
        void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
          try {
            resolve(func(input, childConfig));
          } catch (e3) {
            reject(e3);
          }
        });
      });
    }
  });
}
function _formatToolOutput(params) {
  const { content, artifact, toolCallId } = params;
  if (toolCallId && !isDirectToolOutput(content)) {
    if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) {
      return new ToolMessage({
        content,
        artifact,
        tool_call_id: toolCallId,
        name: params.name
      });
    } else {
      return new ToolMessage({
        content: _stringify(content),
        artifact,
        tool_call_id: toolCallId,
        name: params.name
      });
    }
  } else {
    return content;
  }
}
function _stringify(content) {
  try {
    return JSON.stringify(content, null, 2);
  } catch (_noOp) {
    return `${content}`;
  }
}

// node_modules/@langchain/openai/dist/tools/dalle.js
var DallEAPIWrapper = class extends Tool {
  static lc_name() {
    return "DallEAPIWrapper";
  }
  constructor(fields) {
    if (fields?.responseFormat !== void 0 && ["url", "b64_json"].includes(fields.responseFormat)) {
      fields.dallEResponseFormat = fields.responseFormat;
      fields.responseFormat = "content";
    }
    super(fields);
    Object.defineProperty(this, "name", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "dalle_api_wrapper"
    });
    Object.defineProperty(this, "description", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "dall-e-3"
    });
    Object.defineProperty(this, "style", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "vivid"
    });
    Object.defineProperty(this, "quality", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "standard"
    });
    Object.defineProperty(this, "n", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1
    });
    Object.defineProperty(this, "size", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "1024x1024"
    });
    Object.defineProperty(this, "dallEResponseFormat", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "url"
    });
    Object.defineProperty(this, "user", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    const openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable2("OPENAI_API_KEY");
    const organization = fields?.organization ?? getEnvironmentVariable2("OPENAI_ORGANIZATION");
    const clientConfig = {
      apiKey: openAIApiKey,
      organization,
      dangerouslyAllowBrowser: true,
      baseUrl: fields?.baseUrl
    };
    this.client = new OpenAI(clientConfig);
    this.model = fields?.model ?? fields?.modelName ?? this.model;
    this.style = fields?.style ?? this.style;
    this.quality = fields?.quality ?? this.quality;
    this.n = fields?.n ?? this.n;
    this.size = fields?.size ?? this.size;
    this.dallEResponseFormat = fields?.dallEResponseFormat ?? this.dallEResponseFormat;
    this.user = fields?.user;
  }
  /**
   * Processes the API response if multiple images are generated.
   * Returns a list of MessageContentImageUrl objects. If the response
   * format is `url`, then the `image_url` field will contain the URL.
   * If it is `b64_json`, then the `image_url` field will contain an object
   * with a `url` field with the base64 encoded image.
   *
   * @param {OpenAIClient.Images.ImagesResponse[]} response The API response
   * @returns {MessageContentImageUrl[]}
   */
  processMultipleGeneratedUrls(response) {
    if (this.dallEResponseFormat === "url") {
      return response.flatMap((res) => {
        const imageUrlContent = res.data.flatMap((item) => {
          if (!item.url)
            return [];
          return {
            type: "image_url",
            image_url: item.url
          };
        }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "string" && item.image_url !== void 0);
        return imageUrlContent;
      });
    } else {
      return response.flatMap((res) => {
        const b64Content = res.data.flatMap((item) => {
          if (!item.b64_json)
            return [];
          return {
            type: "image_url",
            image_url: {
              url: item.b64_json
            }
          };
        }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "object" && "url" in item.image_url && typeof item.image_url.url === "string" && item.image_url.url !== void 0);
        return b64Content;
      });
    }
  }
  /** @ignore */
  async _call(input) {
    const generateImageFields = {
      model: this.model,
      prompt: input,
      n: 1,
      size: this.size,
      response_format: this.dallEResponseFormat,
      style: this.style,
      quality: this.quality,
      user: this.user
    };
    if (this.n > 1) {
      const results = await Promise.all(Array.from({ length: this.n }).map(() => this.client.images.generate(generateImageFields)));
      return this.processMultipleGeneratedUrls(results);
    }
    const response = await this.client.images.generate(generateImageFields);
    let data = "";
    if (this.dallEResponseFormat === "url") {
      [data] = response.data.map((item) => item.url).filter((url) => url !== "undefined");
    } else {
      [data] = response.data.map((item) => item.b64_json).filter((b64_json) => b64_json !== "undefined");
    }
    return data;
  }
};
Object.defineProperty(DallEAPIWrapper, "toolName", {
  enumerable: true,
  configurable: true,
  writable: true,
  value: "dalle_api_wrapper"
});

// src/LLMProviders/embeddingManager.ts
var import_obsidian4 = require("obsidian");

// node_modules/@langchain/community/dist/embeddings/jina.js
var JinaEmbeddings = class extends Embeddings {
  constructor(fields) {
    const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
    super(fieldsWithDefaults);
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "jina-clip-v2"
    });
    Object.defineProperty(this, "batchSize", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 24
    });
    Object.defineProperty(this, "baseUrl", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "https://api.jina.ai/v1/embeddings"
    });
    Object.defineProperty(this, "stripNewLines", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "dimensions", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1024
    });
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "normalized", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    const apiKey = fieldsWithDefaults?.apiKey || getEnvironmentVariable2("JINA_API_KEY") || getEnvironmentVariable2("JINA_AUTH_TOKEN");
    if (!apiKey)
      throw new Error("Jina API key not found");
    this.apiKey = apiKey;
    this.model = fieldsWithDefaults?.model ?? this.model;
    this.dimensions = fieldsWithDefaults?.dimensions ?? this.dimensions;
    this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
    this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
    this.normalized = fieldsWithDefaults?.normalized ?? this.normalized;
  }
  doStripNewLines(input) {
    if (this.stripNewLines) {
      return input.map((i3) => {
        if (typeof i3 === "string") {
          return i3.replace(/\n/g, " ");
        }
        if (i3.text) {
          return { text: i3.text.replace(/\n/g, " ") };
        }
        return i3;
      });
    }
    return input;
  }
  async embedDocuments(input) {
    const batches = chunkArray(this.doStripNewLines(input), this.batchSize);
    const batchRequests = batches.map((batch) => {
      const params = this.getParams(batch);
      return this.embeddingWithRetry(params);
    });
    const batchResponses = await Promise.all(batchRequests);
    const embeddings = [];
    for (let i3 = 0; i3 < batchResponses.length; i3 += 1) {
      const batch = batches[i3];
      const batchResponse = batchResponses[i3] || [];
      for (let j3 = 0; j3 < batch.length; j3 += 1) {
        embeddings.push(batchResponse[j3]);
      }
    }
    return embeddings;
  }
  async embedQuery(input) {
    const params = this.getParams(this.doStripNewLines([input]), true);
    const embeddings = await this.embeddingWithRetry(params) || [[]];
    return embeddings[0];
  }
  getParams(input, query) {
    return {
      model: this.model,
      input,
      dimensions: this.dimensions,
      task: query ? "retrieval.query" : "retrieval.passage",
      normalized: this.normalized
    };
  }
  async embeddingWithRetry(body) {
    const response = await fetch(this.baseUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.apiKey}`
      },
      body: JSON.stringify(body)
    });
    const embeddingData = await response.json();
    if ("detail" in embeddingData && embeddingData.detail) {
      throw new Error(`${embeddingData.detail}`);
    }
    return embeddingData.data.map(({ embedding }) => embedding);
  }
};

// src/LLMProviders/CustomJinaEmbeddings.ts
var CustomJinaEmbeddings = class extends JinaEmbeddings {
  constructor(fields) {
    super(fields);
    if (fields?.baseUrl) {
      this.baseUrl = fields.baseUrl;
    }
  }
};

// src/LLMProviders/embeddingManager.ts
var EMBEDDING_PROVIDER_CONSTRUCTORS = {
  ["copilot-plus" /* COPILOT_PLUS */]: OpenAIEmbeddings,
  ["copilot-plus-jina" /* COPILOT_PLUS_JINA */]: CustomJinaEmbeddings,
  ["openai" /* OPENAI */]: OpenAIEmbeddings,
  ["cohereai" /* COHEREAI */]: CohereEmbeddings,
  ["google" /* GOOGLE */]: GoogleGenerativeAIEmbeddings,
  ["azure openai" /* AZURE_OPENAI */]: OpenAIEmbeddings,
  ["ollama" /* OLLAMA */]: OllamaEmbeddings,
  ["lm-studio" /* LM_STUDIO */]: OpenAIEmbeddings,
  ["3rd party (openai-format)" /* OPENAI_FORMAT */]: OpenAIEmbeddings
};
var EmbeddingManager = class {
  constructor() {
    this.providerApiKeyMap = {
      ["copilot-plus" /* COPILOT_PLUS */]: () => getSettings().plusLicenseKey,
      ["copilot-plus-jina" /* COPILOT_PLUS_JINA */]: () => getSettings().plusLicenseKey,
      ["openai" /* OPENAI */]: () => getSettings().openAIApiKey,
      ["cohereai" /* COHEREAI */]: () => getSettings().cohereApiKey,
      ["google" /* GOOGLE */]: () => getSettings().googleApiKey,
      ["azure openai" /* AZURE_OPENAI */]: () => getSettings().azureOpenAIApiKey,
      ["ollama" /* OLLAMA */]: () => "default-key",
      ["lm-studio" /* LM_STUDIO */]: () => "default-key",
      ["3rd party (openai-format)" /* OPENAI_FORMAT */]: () => ""
    };
    this.initialize();
    subscribeToSettingsChange(() => this.initialize());
  }
  initialize() {
    const activeEmbeddingModels = getSettings().activeEmbeddingModels;
    this.activeEmbeddingModels = activeEmbeddingModels;
    this.buildModelMap(activeEmbeddingModels);
  }
  static getInstance() {
    if (!EmbeddingManager.instance) {
      EmbeddingManager.instance = new EmbeddingManager();
    }
    return EmbeddingManager.instance;
  }
  getProviderConstructor(model) {
    const constructor = EMBEDDING_PROVIDER_CONSTRUCTORS[model.provider];
    if (!constructor) {
      console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`);
      throw new Error(`Unknown provider: ${model.provider} for model: ${model.name}`);
    }
    return constructor;
  }
  // Build a map of modelKey to model config
  buildModelMap(activeEmbeddingModels) {
    EmbeddingManager.modelMap = {};
    const modelMap = EmbeddingManager.modelMap;
    activeEmbeddingModels.forEach((model) => {
      if (model.enabled) {
        if (!Object.values(EmbeddingModelProviders).contains(
          model.provider
        )) {
          console.warn(`Unknown provider: ${model.provider} for embedding model: ${model.name}`);
          return;
        }
        const constructor = this.getProviderConstructor(model);
        const apiKey = model.apiKey || this.providerApiKeyMap[model.provider]();
        const modelKey = getModelKeyFromModel(model);
        modelMap[modelKey] = {
          hasApiKey: Boolean(apiKey),
          EmbeddingConstructor: constructor,
          vendor: model.provider
        };
      }
    });
  }
  static getModelName(embeddingsInstance) {
    const emb = embeddingsInstance;
    if ("model" in emb && emb.model) {
      return emb.model;
    } else if ("modelName" in emb && emb.modelName) {
      return emb.modelName;
    } else {
      throw new Error(
        `Embeddings instance missing model or modelName properties: ${embeddingsInstance}`
      );
    }
  }
  // Get the custom model that matches the name and provider from the model key
  getCustomModel(modelKey) {
    return this.activeEmbeddingModels.filter((model) => {
      const key = getModelKeyFromModel(model);
      return modelKey === key;
    })[0];
  }
  async getEmbeddingsAPI() {
    const { embeddingModelKey } = getSettings();
    if (!EmbeddingManager.modelMap.hasOwnProperty(embeddingModelKey)) {
      throw new CustomError(`No embedding model found for: ${embeddingModelKey}`);
    }
    const selectedModel = EmbeddingManager.modelMap[embeddingModelKey];
    if (!selectedModel.hasApiKey) {
      throw new CustomError(
        `API key is not provided for the embedding model: ${embeddingModelKey}`
      );
    }
    const customModel = this.getCustomModel(embeddingModelKey);
    const config = await this.getEmbeddingConfig(customModel);
    try {
      EmbeddingManager.embeddingModel = new selectedModel.EmbeddingConstructor(config);
      return EmbeddingManager.embeddingModel;
    } catch (error) {
      throw new CustomError(
        `Error creating embedding model: ${embeddingModelKey}. ${error.message}`
      );
    }
  }
  async getEmbeddingConfig(customModel) {
    const settings = getSettings();
    const modelName = customModel.name;
    const baseConfig = {
      maxRetries: 3,
      maxConcurrency: 3
    };
    const providerConfig = {
      ["copilot-plus" /* COPILOT_PLUS */]: {
        modelName,
        apiKey: await getDecryptedKey(settings.plusLicenseKey),
        timeout: 1e4,
        batchSize: EMBEDDING_BATCH_SIZE,
        configuration: {
          baseURL: BREVILABS_API_BASE_URL,
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["copilot-plus-jina" /* COPILOT_PLUS_JINA */]: {
        model: modelName,
        apiKey: await getDecryptedKey(settings.plusLicenseKey),
        timeout: 1e4,
        batchSize: 128,
        dimensions: 512,
        // Don't change this, it's the default for Copilot Plus Jina
        baseUrl: BREVILABS_API_BASE_URL + "/embeddings",
        configuration: {
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["openai" /* OPENAI */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || settings.openAIApiKey),
        timeout: 1e4,
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["cohereai" /* COHEREAI */]: {
        model: modelName,
        apiKey: await getDecryptedKey(customModel.apiKey || settings.cohereApiKey)
      },
      ["google" /* GOOGLE */]: {
        modelName,
        apiKey: await getDecryptedKey(settings.googleApiKey)
      },
      ["azure openai" /* AZURE_OPENAI */]: {
        azureOpenAIApiKey: await getDecryptedKey(customModel.apiKey || settings.azureOpenAIApiKey),
        azureOpenAIApiInstanceName: customModel.azureOpenAIApiInstanceName || settings.azureOpenAIApiInstanceName,
        azureOpenAIApiDeploymentName: customModel.azureOpenAIApiEmbeddingDeploymentName || settings.azureOpenAIApiEmbeddingDeploymentName,
        azureOpenAIApiVersion: customModel.azureOpenAIApiVersion || settings.azureOpenAIApiVersion,
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["ollama" /* OLLAMA */]: {
        baseUrl: customModel.baseUrl || "http://localhost:11434",
        model: modelName,
        truncate: true
      },
      ["lm-studio" /* LM_STUDIO */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || "default-key"),
        configuration: {
          baseURL: customModel.baseUrl || "http://localhost:1234/v1",
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["3rd party (openai-format)" /* OPENAI_FORMAT */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || ""),
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0,
          dangerouslyAllowBrowser: true
        }
      }
    };
    const selectedProviderConfig = providerConfig[customModel.provider] || {};
    return { ...baseConfig, ...selectedProviderConfig };
  }
  async ping(model) {
    const tryPing = async (enableCors) => {
      const modelToTest = { ...model, enableCors };
      const config = await this.getEmbeddingConfig(modelToTest);
      const testModel = new (this.getProviderConstructor(modelToTest))(config);
      await testModel.embedQuery("test");
    };
    try {
      await tryPing(false);
      return true;
    } catch (firstError) {
      console.log("First ping attempt failed, trying with CORS...");
      try {
        await tryPing(true);
        new import_obsidian4.Notice(
          "Connection successful, but requires CORS to be enabled. Please enable CORS for this model once you add it above."
        );
        return true;
      } catch (error) {
        const msg = "\nwithout CORS Error: " + err2String(firstError) + "\nwith CORS Error: " + err2String(error);
        throw new Error(msg);
      }
    }
  }
};

// src/search/vectorStoreManager.ts
var import_obsidian9 = require("obsidian");

// node_modules/@orama/orama/dist/browser/components/tokenizer/languages.js
var STEMMERS = {
  arabic: "ar",
  armenian: "am",
  bulgarian: "bg",
  danish: "dk",
  dutch: "nl",
  english: "en",
  finnish: "fi",
  french: "fr",
  german: "de",
  greek: "gr",
  hungarian: "hu",
  indian: "in",
  indonesian: "id",
  irish: "ie",
  italian: "it",
  lithuanian: "lt",
  nepali: "np",
  norwegian: "no",
  portuguese: "pt",
  romanian: "ro",
  russian: "ru",
  serbian: "rs",
  slovenian: "ru",
  spanish: "es",
  swedish: "se",
  tamil: "ta",
  turkish: "tr",
  ukrainian: "uk",
  sanskrit: "sk"
};
var SPLITTERS = {
  dutch: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  english: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  french: /[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,
  italian: /[^A-Za-zàèéìòóù0-9_'-]+/gim,
  norwegian: /[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,
  portuguese: /[^a-z0-9à-úÀ-Ú]/gim,
  russian: /[^a-z0-9а-яА-ЯёЁ]+/gim,
  spanish: /[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,
  swedish: /[^a-z0-9_åÅäÄöÖüÜ-]+/gim,
  german: /[^a-z0-9A-ZäöüÄÖÜß]+/gim,
  finnish: /[^a-z0-9äöÄÖ]+/gim,
  danish: /[^a-z0-9æøåÆØÅ]+/gim,
  hungarian: /[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,
  romanian: /[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,
  serbian: /[^a-z0-9čćžšđČĆŽŠĐ]+/gim,
  turkish: /[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,
  lithuanian: /[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,
  arabic: /[^a-z0-9أ-ي]+/gim,
  nepali: /[^a-z0-9अ-ह]+/gim,
  irish: /[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,
  indian: /[^a-z0-9अ-ह]+/gim,
  armenian: /[^a-z0-9ա-ֆ]+/gim,
  greek: /[^a-z0-9α-ωά-ώ]+/gim,
  indonesian: /[^a-z0-9]+/gim,
  ukrainian: /[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,
  slovenian: /[^a-z0-9čžšČŽŠ]+/gim,
  bulgarian: /[^a-z0-9а-яА-Я]+/gim,
  tamil: /[^a-z0-9அ-ஹ]+/gim,
  sanskrit: /[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim
};
var SUPPORTED_LANGUAGES = Object.keys(STEMMERS);
function getLocale(language) {
  return language !== void 0 && SUPPORTED_LANGUAGES.includes(language) ? STEMMERS[language] : void 0;
}

// node_modules/@orama/orama/dist/browser/utils.js
var baseId = Date.now().toString().slice(5);
var lastId = 0;
var nano = BigInt(1e3);
var milli = BigInt(1e6);
var second = BigInt(1e9);
var MAX_ARGUMENT_FOR_STACK = 65535;
function safeArrayPush(arr2, newArr) {
  if (newArr.length < MAX_ARGUMENT_FOR_STACK) {
    Array.prototype.push.apply(arr2, newArr);
  } else {
    const newArrLength = newArr.length;
    for (let i3 = 0; i3 < newArrLength; i3 += MAX_ARGUMENT_FOR_STACK) {
      Array.prototype.push.apply(arr2, newArr.slice(i3, i3 + MAX_ARGUMENT_FOR_STACK));
    }
  }
}
function sprintf(template, ...args) {
  return template.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g, function(...replaceArgs) {
    const groups = replaceArgs[replaceArgs.length - 1];
    const { width: rawWidth, type, position } = groups;
    const replacement = position ? args[Number.parseInt(position) - 1] : args.shift();
    const width = rawWidth === "" ? 0 : Number.parseInt(rawWidth);
    switch (type) {
      case "d":
        return replacement.toString().padStart(width, "0");
      case "f": {
        let value = replacement;
        const [padding, precision] = rawWidth.split(".").map((w2) => Number.parseFloat(w2));
        if (typeof precision === "number" && precision >= 0) {
          value = value.toFixed(precision);
        }
        return typeof padding === "number" && padding >= 0 ? value.toString().padStart(width, "0") : value.toString();
      }
      case "s":
        return width < 0 ? replacement.toString().padEnd(-width, " ") : replacement.toString().padStart(width, " ");
      default:
        return replacement;
    }
  });
}
function isInsideWebWorker() {
  return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
}
function isInsideNode() {
  return typeof process !== "undefined" && process.release && process.release.name === "node";
}
function getNanosecondTimeViaPerformance() {
  return BigInt(Math.floor(performance.now() * 1e6));
}
function formatNanoseconds(value) {
  if (typeof value === "number") {
    value = BigInt(value);
  }
  if (value < nano) {
    return `${value}ns`;
  } else if (value < milli) {
    return `${value / nano}\u03BCs`;
  } else if (value < second) {
    return `${value / milli}ms`;
  }
  return `${value / second}s`;
}
function getNanosecondsTime() {
  if (isInsideWebWorker()) {
    return getNanosecondTimeViaPerformance();
  }
  if (isInsideNode()) {
    return process.hrtime.bigint();
  }
  if (typeof process !== "undefined" && typeof process?.hrtime?.bigint === "function") {
    return process.hrtime.bigint();
  }
  if (typeof performance !== "undefined") {
    return getNanosecondTimeViaPerformance();
  }
  return BigInt(0);
}
function uniqueId() {
  return `${baseId}-${lastId++}`;
}
function getOwnProperty(object, property) {
  if (Object.hasOwn === void 0) {
    return Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0;
  }
  return Object.hasOwn(object, property) ? object[property] : void 0;
}
function sortTokenScorePredicate(a3, b3) {
  if (b3[1] === a3[1]) {
    return a3[0] - b3[0];
  }
  return b3[1] - a3[1];
}
function intersect(arrays) {
  if (arrays.length === 0) {
    return [];
  } else if (arrays.length === 1) {
    return arrays[0];
  }
  for (let i3 = 1; i3 < arrays.length; i3++) {
    if (arrays[i3].length < arrays[0].length) {
      const tmp = arrays[0];
      arrays[0] = arrays[i3];
      arrays[i3] = tmp;
    }
  }
  const set = /* @__PURE__ */ new Map();
  for (const elem of arrays[0]) {
    set.set(elem, 1);
  }
  for (let i3 = 1; i3 < arrays.length; i3++) {
    let found = 0;
    for (const elem of arrays[i3]) {
      const count5 = set.get(elem);
      if (count5 === i3) {
        set.set(elem, count5 + 1);
        found++;
      }
    }
    if (found === 0)
      return [];
  }
  return arrays[0].filter((e3) => {
    const count5 = set.get(e3);
    if (count5 !== void 0)
      set.set(e3, 0);
    return count5 === arrays.length;
  });
}
function getDocumentProperties(doc, paths) {
  const properties = {};
  const pathsLength = paths.length;
  for (let i3 = 0; i3 < pathsLength; i3++) {
    const path = paths[i3];
    const pathTokens = path.split(".");
    let current = doc;
    const pathTokensLength = pathTokens.length;
    for (let j3 = 0; j3 < pathTokensLength; j3++) {
      current = current[pathTokens[j3]];
      if (typeof current === "object") {
        if (current !== null && "lat" in current && "lon" in current && typeof current.lat === "number" && typeof current.lon === "number") {
          current = properties[path] = current;
          break;
        } else if (!Array.isArray(current) && current !== null && j3 === pathTokensLength - 1) {
          current = void 0;
          break;
        }
      } else if ((current === null || typeof current !== "object") && j3 < pathTokensLength - 1) {
        current = void 0;
        break;
      }
    }
    if (typeof current !== "undefined") {
      properties[path] = current;
    }
  }
  return properties;
}
function getNested(obj, path) {
  const props = getDocumentProperties(obj, [path]);
  return props[path];
}
var mapDistanceToMeters = {
  cm: 0.01,
  m: 1,
  km: 1e3,
  ft: 0.3048,
  yd: 0.9144,
  mi: 1609.344
};
function convertDistanceToMeters(distance, unit) {
  const ratio = mapDistanceToMeters[unit];
  if (ratio === void 0) {
    throw new Error(createError("INVALID_DISTANCE_SUFFIX", distance).message);
  }
  return distance * ratio;
}
function removeVectorsFromHits(searchResult, vectorProperties) {
  searchResult.hits = searchResult.hits.map((result) => ({
    ...result,
    document: {
      ...result.document,
      // Remove embeddings from the result
      ...vectorProperties.reduce((acc, prop) => {
        const path = prop.split(".");
        const lastKey = path.pop();
        let obj = acc;
        for (const key of path) {
          obj[key] = obj[key] ?? {};
          obj = obj[key];
        }
        obj[lastKey] = null;
        return acc;
      }, result.document)
    }
  }));
}
function isAsyncFunction(func) {
  return func?.constructor?.name === "AsyncFunction";
}

// node_modules/@orama/orama/dist/browser/errors.js
var allLanguages = SUPPORTED_LANGUAGES.join("\n - ");
var errors = {
  NO_LANGUAGE_WITH_CUSTOM_TOKENIZER: "Do not pass the language option to create when using a custom tokenizer.",
  LANGUAGE_NOT_SUPPORTED: `Language "%s" is not supported.
Supported languages are:
 - ${allLanguages}`,
  INVALID_STEMMER_FUNCTION_TYPE: `config.stemmer property must be a function.`,
  MISSING_STEMMER: `As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.`,
  CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY: "Custom stop words array must only contain strings.",
  UNSUPPORTED_COMPONENT: `Unsupported component "%s".`,
  COMPONENT_MUST_BE_FUNCTION: `The component "%s" must be a function.`,
  COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS: `The component "%s" must be a function or an array of functions.`,
  INVALID_SCHEMA_TYPE: `Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.`,
  DOCUMENT_ID_MUST_BE_STRING: `Document id must be of type "string". Got "%s" instead.`,
  DOCUMENT_ALREADY_EXISTS: `A document with id "%s" already exists.`,
  DOCUMENT_DOES_NOT_EXIST: `A document with id "%s" does not exists.`,
  MISSING_DOCUMENT_PROPERTY: `Missing searchable property "%s".`,
  INVALID_DOCUMENT_PROPERTY: `Invalid document property "%s": expected "%s", got "%s"`,
  UNKNOWN_INDEX: `Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s`,
  INVALID_BOOST_VALUE: `Boost value must be a number greater than, or less than 0.`,
  INVALID_FILTER_OPERATION: `You can only use one operation per filter, you requested %d.`,
  SCHEMA_VALIDATION_FAILURE: `Cannot insert document due schema validation failure on "%s" property.`,
  INVALID_SORT_SCHEMA_TYPE: `Unsupported sort schema type "%s" at "%s". Expected "string" or "number".`,
  CANNOT_SORT_BY_ARRAY: `Cannot configure sort for "%s" because it is an array (%s).`,
  UNABLE_TO_SORT_ON_UNKNOWN_FIELD: `Unable to sort on unknown field "%s". Allowed fields: %s`,
  SORT_DISABLED: `Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.`,
  UNKNOWN_GROUP_BY_PROPERTY: `Unknown groupBy property "%s".`,
  INVALID_GROUP_BY_PROPERTY: `Invalid groupBy property "%s". Allowed types: "%s", but given "%s".`,
  UNKNOWN_FILTER_PROPERTY: `Unknown filter property "%s".`,
  INVALID_VECTOR_SIZE: `Vector size must be a number greater than 0. Got "%s" instead.`,
  INVALID_VECTOR_VALUE: `Vector value must be a number greater than 0. Got "%s" instead.`,
  INVALID_INPUT_VECTOR: `Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,
  WRONG_SEARCH_PROPERTY_TYPE: `Property "%s" is not searchable. Only "string" properties are searchable.`,
  FACET_NOT_SUPPORTED: `Facet doens't support the type "%s".`,
  INVALID_DISTANCE_SUFFIX: `Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.`,
  INVALID_SEARCH_MODE: `Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".`,
  MISSING_VECTOR_AND_SECURE_PROXY: `No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.`,
  MISSING_TERM: `"term" is a required parameter when performing hybrid search. Please provide a search term.`,
  INVALID_VECTOR_INPUT: `Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.`,
  PLUGIN_CRASHED: `A plugin crashed during initialization. Please check the error message for more information:`,
  PLUGIN_SECURE_PROXY_NOT_FOUND: `Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,
  PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL: `Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,
  ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT: `The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`
};
function createError(code, ...args) {
  const error = new Error(sprintf(errors[code] ?? `Unsupported Orama Error code: ${code}`, ...args));
  error.code = code;
  if ("captureStackTrace" in Error.prototype) {
    Error.captureStackTrace(error);
  }
  return error;
}

// node_modules/@orama/orama/dist/browser/components/defaults.js
function formatElapsedTime(n4) {
  return {
    raw: Number(n4),
    formatted: formatNanoseconds(n4)
  };
}
function getDocumentIndexId(doc) {
  if (doc.id) {
    if (typeof doc.id !== "string") {
      throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof doc.id);
    }
    return doc.id;
  }
  return uniqueId();
}
function validateSchema(doc, schema) {
  for (const [prop, type] of Object.entries(schema)) {
    const value = doc[prop];
    if (typeof value === "undefined") {
      continue;
    }
    if (type === "geopoint" && typeof value === "object" && typeof value.lon === "number" && typeof value.lat === "number") {
      continue;
    }
    if (type === "enum" && (typeof value === "string" || typeof value === "number")) {
      continue;
    }
    if (type === "enum[]" && Array.isArray(value)) {
      const valueLength = value.length;
      for (let i3 = 0; i3 < valueLength; i3++) {
        if (typeof value[i3] !== "string" && typeof value[i3] !== "number") {
          return prop + "." + i3;
        }
      }
      continue;
    }
    if (isVectorType(type)) {
      const vectorSize = getVectorSize(type);
      if (!Array.isArray(value) || value.length !== vectorSize) {
        throw createError("INVALID_INPUT_VECTOR", prop, vectorSize, value.length);
      }
      continue;
    }
    if (isArrayType(type)) {
      if (!Array.isArray(value)) {
        return prop;
      }
      const expectedType = getInnerType(type);
      const valueLength = value.length;
      for (let i3 = 0; i3 < valueLength; i3++) {
        if (typeof value[i3] !== expectedType) {
          return prop + "." + i3;
        }
      }
      continue;
    }
    if (typeof type === "object") {
      if (!value || typeof value !== "object") {
        return prop;
      }
      const subProp = validateSchema(value, type);
      if (subProp) {
        return prop + "." + subProp;
      }
      continue;
    }
    if (typeof value !== type) {
      return prop;
    }
  }
  return void 0;
}
var IS_ARRAY_TYPE = {
  string: false,
  number: false,
  boolean: false,
  enum: false,
  geopoint: false,
  "string[]": true,
  "number[]": true,
  "boolean[]": true,
  "enum[]": true
};
var INNER_TYPE = {
  "string[]": "string",
  "number[]": "number",
  "boolean[]": "boolean",
  "enum[]": "enum"
};
function isGeoPointType(type) {
  return type === "geopoint";
}
function isVectorType(type) {
  return typeof type === "string" && /^vector\[\d+\]$/.test(type);
}
function isArrayType(type) {
  return typeof type === "string" && IS_ARRAY_TYPE[type];
}
function getInnerType(type) {
  return INNER_TYPE[type];
}
function getVectorSize(type) {
  const size4 = Number(type.slice(7, -1));
  switch (true) {
    case isNaN(size4):
      throw createError("INVALID_VECTOR_VALUE", type);
    case size4 <= 0:
      throw createError("INVALID_VECTOR_SIZE", type);
    default:
      return size4;
  }
}

// node_modules/@orama/orama/dist/browser/components/internal-document-id-store.js
function createInternalDocumentIDStore() {
  return {
    idToInternalId: /* @__PURE__ */ new Map(),
    internalIdToId: [],
    save,
    load
  };
}
function save(store2) {
  return {
    internalIdToId: store2.internalIdToId
  };
}
function load(orama, raw) {
  const { internalIdToId } = raw;
  orama.internalDocumentIDStore.idToInternalId.clear();
  orama.internalDocumentIDStore.internalIdToId = [];
  const internalIdToIdLength = internalIdToId.length;
  for (let i3 = 0; i3 < internalIdToIdLength; i3++) {
    const internalIdItem = internalIdToId[i3];
    orama.internalDocumentIDStore.idToInternalId.set(internalIdItem, i3 + 1);
    orama.internalDocumentIDStore.internalIdToId.push(internalIdItem);
  }
}
function getInternalDocumentId(store2, id) {
  if (typeof id === "string") {
    const internalId = store2.idToInternalId.get(id);
    if (internalId) {
      return internalId;
    }
    const currentId = store2.idToInternalId.size + 1;
    store2.idToInternalId.set(id, currentId);
    store2.internalIdToId.push(id);
    return currentId;
  }
  if (id > store2.internalIdToId.length) {
    return getInternalDocumentId(store2, id.toString());
  }
  return id;
}
function getDocumentIdFromInternalId(store2, internalId) {
  if (store2.internalIdToId.length < internalId) {
    throw new Error(`Invalid internalId ${internalId}`);
  }
  return store2.internalIdToId[internalId - 1];
}

// node_modules/@orama/orama/dist/browser/components/documents-store.js
function create(_2, sharedInternalDocumentStore) {
  return {
    sharedInternalDocumentStore,
    docs: {},
    count: 0
  };
}
function get3(store2, id) {
  const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, id);
  return store2.docs[internalId];
}
function getMultiple(store2, ids) {
  const idsLength = ids.length;
  const found = Array.from({ length: idsLength });
  for (let i3 = 0; i3 < idsLength; i3++) {
    const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, ids[i3]);
    found[i3] = store2.docs[internalId];
  }
  return found;
}
function getAll(store2) {
  return store2.docs;
}
function store(store2, id, doc) {
  const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, id);
  if (typeof store2.docs[internalId] !== "undefined") {
    return false;
  }
  store2.docs[internalId] = doc;
  store2.count++;
  return true;
}
function remove(store2, id) {
  const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, id);
  if (typeof store2.docs[internalId] === "undefined") {
    return false;
  }
  delete store2.docs[internalId];
  store2.count--;
  return true;
}
function count(store2) {
  return store2.count;
}
function load2(sharedInternalDocumentStore, raw) {
  const rawDocument = raw;
  return {
    docs: rawDocument.docs,
    count: rawDocument.count,
    sharedInternalDocumentStore
  };
}
function save2(store2) {
  return {
    docs: store2.docs,
    count: store2.count
  };
}
function createDocumentsStore() {
  return {
    create,
    get: get3,
    getMultiple,
    getAll,
    store,
    remove,
    count,
    load: load2,
    save: save2
  };
}

// node_modules/@orama/orama/dist/browser/components/plugins.js
var AVAILABLE_PLUGIN_HOOKS = [
  "beforeInsert",
  "afterInsert",
  "beforeRemove",
  "afterRemove",
  "beforeUpdate",
  "afterUpdate",
  "beforeSearch",
  "afterSearch",
  "beforeInsertMultiple",
  "afterInsertMultiple",
  "beforeRemoveMultiple",
  "afterRemoveMultiple",
  "beforeUpdateMultiple",
  "afterUpdateMultiple",
  "beforeLoad",
  "afterLoad",
  "afterCreate"
];
function getAllPluginsByHook(orama, hook) {
  const pluginsToRun = [];
  const pluginsLength = orama.plugins?.length;
  if (!pluginsLength) {
    return pluginsToRun;
  }
  for (let i3 = 0; i3 < pluginsLength; i3++) {
    try {
      const plugin = orama.plugins[i3];
      if (typeof plugin[hook] === "function") {
        pluginsToRun.push(plugin[hook]);
      }
    } catch (error) {
      console.error("Caught error in getAllPluginsByHook:", error);
      throw createError("PLUGIN_CRASHED");
    }
  }
  return pluginsToRun;
}

// node_modules/@orama/orama/dist/browser/components/hooks.js
var OBJECT_COMPONENTS = ["tokenizer", "index", "documentsStore", "sorter"];
var FUNCTION_COMPONENTS = [
  "validateSchema",
  "getDocumentIndexId",
  "getDocumentProperties",
  "formatElapsedTime"
];
function runSingleHook(hooks, orama, id, doc) {
  const needAsync = hooks.some(isAsyncFunction);
  if (needAsync) {
    return (async () => {
      for (const hook of hooks) {
        await hook(orama, id, doc);
      }
    })();
  } else {
    for (const hook of hooks) {
      hook(orama, id, doc);
    }
  }
}
function runMultipleHook(hooks, orama, docsOrIds) {
  const needAsync = hooks.some(isAsyncFunction);
  if (needAsync) {
    return (async () => {
      for (const hook of hooks) {
        await hook(orama, docsOrIds);
      }
    })();
  } else {
    for (const hook of hooks) {
      hook(orama, docsOrIds);
    }
  }
}
function runAfterSearch(hooks, db, params, language, results) {
  const needAsync = hooks.some(isAsyncFunction);
  if (needAsync) {
    return (async () => {
      for (const hook of hooks) {
        await hook(db, params, language, results);
      }
    })();
  } else {
    for (const hook of hooks) {
      hook(db, params, language, results);
    }
  }
}
function runBeforeSearch(hooks, db, params, language) {
  const needAsync = hooks.some(isAsyncFunction);
  if (needAsync) {
    return (async () => {
      for (const hook of hooks) {
        await hook(db, params, language);
      }
    })();
  } else {
    for (const hook of hooks) {
      hook(db, params, language);
    }
  }
}
function runAfterCreate(hooks, db) {
  const needAsync = hooks.some(isAsyncFunction);
  if (needAsync) {
    return (async () => {
      for (const hook of hooks) {
        await hook(db);
      }
    })();
  } else {
    for (const hook of hooks) {
      hook(db);
    }
  }
}

// node_modules/@orama/orama/dist/browser/trees/avl.js
function rotateLeft(node) {
  const right = node.r;
  node.r = right.l;
  right.l = node;
  node.h = Math.max(getHeight(node.l), getHeight(node.r)) + 1;
  right.h = Math.max(getHeight(right.l), getHeight(right.r)) + 1;
  return right;
}
function rotateRight(node) {
  const left = node.l;
  node.l = left.r;
  left.r = node;
  node.h = Math.max(getHeight(node.l), getHeight(node.r)) + 1;
  left.h = Math.max(getHeight(left.l), getHeight(left.r)) + 1;
  return left;
}
function rangeSearch(node, min2, max2) {
  const result = [];
  function traverse(node2) {
    if (node2 === null) {
      return;
    }
    if (min2 < node2.k) {
      traverse(node2.l);
    }
    if (node2.k >= min2 && node2.k <= max2) {
      safeArrayPush(result, node2.v);
    }
    if (max2 > node2.k) {
      traverse(node2.r);
    }
  }
  traverse(node.root);
  return result;
}
function greaterThan(node, key, inclusive = false) {
  const result = [];
  if (node === null)
    return result;
  const stack = [node.root];
  while (stack.length > 0) {
    const node2 = stack.pop();
    if (!node2) {
      continue;
    }
    if (inclusive && node2.k >= key) {
      safeArrayPush(result, node2.v);
    }
    if (!inclusive && node2.k > key) {
      safeArrayPush(result, node2.v);
    }
    stack.push(node2.r);
    stack.push(node2.l);
  }
  return result;
}
function lessThan(node, key, inclusive = false) {
  const result = [];
  if (node === null)
    return result;
  const stack = [node.root];
  while (stack.length > 0) {
    const node2 = stack.pop();
    if (!node2) {
      continue;
    }
    if (inclusive && node2.k <= key) {
      safeArrayPush(result, node2.v);
    }
    if (!inclusive && node2.k < key) {
      safeArrayPush(result, node2.v);
    }
    stack.push(node2.r);
    stack.push(node2.l);
  }
  return result;
}
function getNodeByKey(node, key) {
  while (node !== null) {
    if (key < node.k) {
      node = node.l;
    } else if (key > node.k) {
      node = node.r;
    } else {
      return node;
    }
  }
  return null;
}
function create2(key, value) {
  return {
    root: {
      k: key,
      v: value,
      l: null,
      r: null,
      h: 0
    }
  };
}
var insertCount = 0;
function insert(rootNode, key, newValue, rebalanceThreshold = 500) {
  function insertNode(node, key2, newValue2) {
    if (node === null) {
      insertCount++;
      return {
        k: key2,
        v: newValue2,
        l: null,
        r: null,
        h: 0
      };
    }
    if (key2 < node.k) {
      node.l = insertNode(node.l, key2, newValue2);
    } else if (key2 > node.k) {
      node.r = insertNode(node.r, key2, newValue2);
    } else {
      node.v.push(...newValue2);
      return node;
    }
    if (insertCount % rebalanceThreshold === 0) {
      return rebalanceNode(node, key2);
    }
    return node;
  }
  rootNode.root = insertNode(rootNode.root, key, newValue);
}
function rebalanceNode(node, key) {
  node.h = 1 + Math.max(getHeight(node.l), getHeight(node.r));
  const balanceFactor = getHeight(node.l) - getHeight(node.r);
  if (balanceFactor > 1 && key < node.l.k) {
    return rotateRight(node);
  }
  if (balanceFactor < -1 && key > node.r.k) {
    return rotateLeft(node);
  }
  if (balanceFactor > 1 && key > node.l.k) {
    node.l = rotateLeft(node.l);
    return rotateRight(node);
  }
  if (balanceFactor < -1 && key < node.r.k) {
    node.r = rotateRight(node.r);
    return rotateLeft(node);
  }
  return node;
}
function getHeight(node) {
  return node !== null ? node.h : -1;
}
function find(root2, key) {
  const node = getNodeByKey(root2.root, key);
  if (node === null) {
    return null;
  }
  return node.v;
}
function remove2(rootNode, key) {
  if (rootNode === null || rootNode.root === null) {
    return;
  }
  let node = rootNode.root;
  let parentNode = null;
  while (node != null && node.k !== key) {
    parentNode = node;
    if (key < node.k) {
      node = node.l;
    } else {
      node = node.r;
    }
  }
  if (node === null) {
    return;
  }
  const deleteNode = () => {
    if (node.l === null && node.r === null) {
      if (parentNode === null) {
        rootNode.root = null;
      } else {
        if (parentNode.l === node) {
          parentNode.l = null;
        } else {
          parentNode.r = null;
        }
      }
    } else if (node.l != null && node.r != null) {
      let minValueNode = node.r;
      let minValueParent = node;
      while (minValueNode.l != null) {
        minValueParent = minValueNode;
        minValueNode = minValueNode.l;
      }
      node.k = minValueNode.k;
      if (minValueParent === node) {
        minValueParent.r = minValueNode.r;
      } else {
        minValueParent.l = minValueNode.r;
      }
    } else {
      const childNode = node.l != null ? node.l : node.r;
      if (parentNode === null) {
        rootNode.root = childNode;
      } else {
        if (parentNode.l === node) {
          parentNode.l = childNode;
        } else {
          parentNode.r = childNode;
        }
      }
    }
  };
  deleteNode();
}
function removeDocument(root2, id, key) {
  const node = getNodeByKey(root2.root, key);
  if (!node) {
    return;
  }
  if (node.v.length === 1) {
    remove2(root2, key);
    return;
  }
  node.v.splice(node.v.indexOf(id), 1);
}

// node_modules/@orama/orama/dist/browser/trees/flat.js
function create3() {
  return {
    numberToDocumentId: /* @__PURE__ */ new Map()
  };
}
function insert2(root2, key, value) {
  if (root2.numberToDocumentId.has(key)) {
    root2.numberToDocumentId.get(key).push(value);
    return root2;
  }
  root2.numberToDocumentId.set(key, [value]);
  return root2;
}
function removeDocument2(root2, id, key) {
  root2?.numberToDocumentId.set(key, root2?.numberToDocumentId.get(key)?.filter((v5) => v5 !== id) ?? []);
  if (root2?.numberToDocumentId.get(key)?.length === 0) {
    root2?.numberToDocumentId.delete(key);
  }
}
function filter(root2, operation) {
  const operationKeys = Object.keys(operation);
  if (operationKeys.length !== 1) {
    throw new Error("Invalid operation");
  }
  const operationType = operationKeys[0];
  switch (operationType) {
    case "eq": {
      const value = operation[operationType];
      return root2.numberToDocumentId.get(value) ?? [];
    }
    case "in": {
      const value = operation[operationType];
      const result = [];
      for (const v5 of value) {
        const ids = root2.numberToDocumentId.get(v5);
        if (ids != null) {
          safeArrayPush(result, ids);
        }
      }
      return result;
    }
    case "nin": {
      const value = operation[operationType];
      const result = [];
      const keys = root2.numberToDocumentId.keys();
      for (const key of keys) {
        if (value.includes(key)) {
          continue;
        }
        const ids = root2.numberToDocumentId.get(key);
        if (ids != null) {
          safeArrayPush(result, ids);
        }
      }
      return result;
    }
  }
  throw new Error("Invalid operation");
}
function filterArr(root2, operation) {
  const operationKeys = Object.keys(operation);
  if (operationKeys.length !== 1) {
    throw new Error("Invalid operation");
  }
  const operationType = operationKeys[0];
  switch (operationType) {
    case "containsAll": {
      const values = operation[operationType];
      const ids = values.map((value) => root2.numberToDocumentId.get(value) ?? []);
      return intersect(ids);
    }
  }
  throw new Error("Invalid operation");
}

// node_modules/@orama/orama/dist/browser/components/levenshtein.js
function _boundedLevenshtein(a3, b3, tolerance) {
  if (tolerance < 0)
    return -1;
  if (a3 === b3)
    return 0;
  const m3 = a3.length;
  const n4 = b3.length;
  if (m3 === 0)
    return n4 <= tolerance ? n4 : -1;
  if (n4 === 0)
    return m3 <= tolerance ? m3 : -1;
  a3 = a3.toLowerCase();
  b3 = b3.toLowerCase();
  if (b3.startsWith(a3) || a3.startsWith(b3))
    return 0;
  if (Math.abs(m3 - n4) > tolerance)
    return -1;
  const matrix = [];
  for (let i3 = 0; i3 <= m3; i3++) {
    matrix[i3] = [i3];
    for (let j3 = 1; j3 <= n4; j3++) {
      matrix[i3][j3] = i3 === 0 ? j3 : 0;
    }
  }
  for (let i3 = 1; i3 <= m3; i3++) {
    let rowMin = Infinity;
    for (let j3 = 1; j3 <= n4; j3++) {
      if (a3[i3 - 1] === b3[j3 - 1]) {
        matrix[i3][j3] = matrix[i3 - 1][j3 - 1];
      } else {
        matrix[i3][j3] = Math.min(
          matrix[i3 - 1][j3] + 1,
          // deletion
          matrix[i3][j3 - 1] + 1,
          // insertion
          matrix[i3 - 1][j3 - 1] + 1
          // substitution
        );
      }
      rowMin = Math.min(rowMin, matrix[i3][j3]);
    }
    if (rowMin > tolerance) {
      return -1;
    }
  }
  return matrix[m3][n4] <= tolerance ? matrix[m3][n4] : -1;
}
function syncBoundedLevenshtein(a3, b3, tolerance) {
  const distance = _boundedLevenshtein(a3, b3, tolerance);
  return {
    distance,
    isBounded: distance >= 0
  };
}

// node_modules/@orama/orama/dist/browser/trees/radix.js
var Node2 = class {
  constructor(key, subWord, end) {
    // Node key
    __publicField(this, "k");
    // Node subword
    __publicField(this, "s");
    // Node children
    __publicField(this, "c", {});
    // Node documents
    __publicField(this, "d", []);
    // Node end
    __publicField(this, "e");
    // Node word
    __publicField(this, "w", "");
    this.k = key;
    this.s = subWord;
    this.e = end;
  }
  toJSON() {
    return {
      w: this.w,
      s: this.s,
      c: this.c,
      d: this.d,
      e: this.e
    };
  }
};
function updateParent(node, parent) {
  node.w = parent.w + node.s;
}
function addDocument(node, docID) {
  node.d.push(docID);
}
function removeDocument3(node, docID) {
  const index2 = node.d.indexOf(docID);
  if (index2 === -1) {
    return false;
  }
  node.d.splice(index2, 1);
  return true;
}
function findAllWords(node, output, term, exact, tolerance) {
  if (node.e) {
    const { w: w2, d: docIDs } = node;
    if (exact && w2 !== term) {
      return {};
    }
    if (getOwnProperty(output, w2) == null) {
      if (tolerance) {
        const difference = Math.abs(term.length - w2.length);
        if (difference <= tolerance && syncBoundedLevenshtein(term, w2, tolerance).isBounded) {
          output[w2] = [];
        }
      } else {
        output[w2] = [];
      }
    }
    if (getOwnProperty(output, w2) != null && docIDs.length > 0) {
      const docs = new Set(output[w2]);
      const docIDsLength = docIDs.length;
      for (let i3 = 0; i3 < docIDsLength; i3++) {
        docs.add(docIDs[i3]);
      }
      output[w2] = Array.from(docs);
    }
  }
  for (const character of Object.keys(node.c)) {
    findAllWords(node.c[character], output, term, exact, tolerance);
  }
  return output;
}
function getCommonPrefix(a3, b3) {
  let commonPrefix = "";
  const len = Math.min(a3.length, b3.length);
  for (let i3 = 0; i3 < len; i3++) {
    if (a3[i3] !== b3[i3]) {
      return commonPrefix;
    }
    commonPrefix += a3[i3];
  }
  return commonPrefix;
}
function create4(end = false, subWord = "", key = "") {
  return new Node2(key, subWord, end);
}
function insert3(root2, word, docId) {
  const wordLength = word.length;
  for (let i3 = 0; i3 < wordLength; i3++) {
    const currentCharacter = word[i3];
    const wordAtIndex = word.substring(i3);
    const rootChildCurrentChar = root2.c[currentCharacter];
    if (rootChildCurrentChar) {
      const edgeLabel = rootChildCurrentChar.s;
      const edgeLabelLength = edgeLabel.length;
      const commonPrefix = getCommonPrefix(edgeLabel, wordAtIndex);
      const commonPrefixLength = commonPrefix.length;
      if (edgeLabel === wordAtIndex) {
        addDocument(rootChildCurrentChar, docId);
        rootChildCurrentChar.e = true;
        return;
      }
      const edgeLabelAtCommonPrefix = edgeLabel[commonPrefixLength];
      if (commonPrefixLength < edgeLabelLength && commonPrefixLength === wordAtIndex.length) {
        const newNode = create4(true, wordAtIndex, currentCharacter);
        newNode.c[edgeLabelAtCommonPrefix] = rootChildCurrentChar;
        const newNodeChild = newNode.c[edgeLabelAtCommonPrefix];
        newNodeChild.s = edgeLabel.substring(commonPrefixLength);
        newNodeChild.k = edgeLabelAtCommonPrefix;
        root2.c[currentCharacter] = newNode;
        updateParent(newNode, root2);
        updateParent(newNodeChild, newNode);
        addDocument(newNode, docId);
        return;
      }
      if (commonPrefixLength < edgeLabelLength && commonPrefixLength < wordAtIndex.length) {
        const inbetweenNode = create4(false, commonPrefix, currentCharacter);
        inbetweenNode.c[edgeLabelAtCommonPrefix] = rootChildCurrentChar;
        root2.c[currentCharacter] = inbetweenNode;
        const inbetweenNodeChild = inbetweenNode.c[edgeLabelAtCommonPrefix];
        inbetweenNodeChild.s = edgeLabel.substring(commonPrefixLength);
        inbetweenNodeChild.k = edgeLabelAtCommonPrefix;
        const wordAtCommonPrefix = wordAtIndex[commonPrefixLength];
        const newNode = create4(true, word.substring(i3 + commonPrefixLength), wordAtCommonPrefix);
        addDocument(newNode, docId);
        inbetweenNode.c[wordAtCommonPrefix] = newNode;
        updateParent(inbetweenNode, root2);
        updateParent(newNode, inbetweenNode);
        updateParent(inbetweenNodeChild, inbetweenNode);
        return;
      }
      i3 += edgeLabelLength - 1;
      root2 = rootChildCurrentChar;
    } else {
      const newNode = create4(true, wordAtIndex, currentCharacter);
      addDocument(newNode, docId);
      root2.c[currentCharacter] = newNode;
      updateParent(newNode, root2);
      return;
    }
  }
}
function _findLevenshtein(node, term, index2, tolerance, originalTolerance, output) {
  if (tolerance < 0) {
    return;
  }
  if (node.w.startsWith(term)) {
    findAllWords(node, output, term, false, 0);
    return;
  }
  if (node.e) {
    const { w: w2, d: docIDs } = node;
    if (w2) {
      if (syncBoundedLevenshtein(term, w2, originalTolerance).isBounded) {
        output[w2] = [];
      }
      if (getOwnProperty(output, w2) != null && docIDs.length > 0) {
        const docs = new Set(output[w2]);
        const docIDsLength = docIDs.length;
        for (let i3 = 0; i3 < docIDsLength; i3++) {
          docs.add(docIDs[i3]);
        }
        output[w2] = Array.from(docs);
      }
    }
  }
  if (index2 >= term.length) {
    return;
  }
  if (term[index2] in node.c) {
    _findLevenshtein(node.c[term[index2]], term, index2 + 1, tolerance, originalTolerance, output);
  }
  _findLevenshtein(node, term, index2 + 1, tolerance - 1, originalTolerance, output);
  for (const character in node.c) {
    _findLevenshtein(node.c[character], term, index2, tolerance - 1, originalTolerance, output);
  }
  for (const character in node.c) {
    if (character !== term[index2]) {
      _findLevenshtein(node.c[character], term, index2 + 1, tolerance - 1, originalTolerance, output);
    }
  }
}
function find2(root2, { term, exact, tolerance }) {
  if (tolerance && !exact) {
    const output = {};
    tolerance = tolerance || 0;
    _findLevenshtein(root2, term, 0, tolerance || 0, tolerance, output);
    return output;
  } else {
    const termLength = term.length;
    for (let i3 = 0; i3 < termLength; i3++) {
      const character = term[i3];
      if (character in root2.c) {
        const rootChildCurrentChar = root2.c[character];
        const edgeLabel = rootChildCurrentChar.s;
        const termSubstring = term.substring(i3);
        const commonPrefix = getCommonPrefix(edgeLabel, termSubstring);
        const commonPrefixLength = commonPrefix.length;
        if (commonPrefixLength !== edgeLabel.length && commonPrefixLength !== termSubstring.length) {
          if (tolerance)
            break;
          return {};
        }
        i3 += rootChildCurrentChar.s.length - 1;
        root2 = rootChildCurrentChar;
      } else {
        return {};
      }
    }
    const output = {};
    findAllWords(root2, output, term, exact, tolerance);
    return output;
  }
}
function removeDocumentByWord(root2, term, docID, exact = true) {
  if (!term) {
    return true;
  }
  const termLength = term.length;
  for (let i3 = 0; i3 < termLength; i3++) {
    const character = term[i3];
    if (character in root2.c) {
      const rootChildCurrentChar = root2.c[character];
      i3 += rootChildCurrentChar.s.length - 1;
      root2 = rootChildCurrentChar;
      if (exact && root2.w !== term) {
      } else {
        removeDocument3(root2, docID);
      }
    } else {
      return false;
    }
  }
  return true;
}

// node_modules/@orama/orama/dist/browser/trees/bkd.js
var K = 2;
var EARTH_RADIUS = 6371e3;
function create5() {
  return { root: null };
}
function insert4(tree, point, docIDs) {
  const newNode = { point, docIDs };
  if (tree.root == null) {
    tree.root = newNode;
    return;
  }
  let node = tree.root;
  let depth = 0;
  while (node !== null) {
    if (node.point.lon === point.lon && node.point.lat === point.lat) {
      const newDocIDs = node.docIDs ?? [];
      node.docIDs = Array.from(/* @__PURE__ */ new Set([...newDocIDs, ...docIDs || []]));
      return;
    }
    const axis = depth % K;
    if (axis === 0) {
      if (point.lon < node.point.lon) {
        if (node.left == null) {
          node.left = newNode;
          return;
        }
        node = node.left;
      } else {
        if (node.right == null) {
          node.right = newNode;
          return;
        }
        node = node.right;
      }
    } else {
      if (point.lat < node.point.lat) {
        if (node.left == null) {
          node.left = newNode;
          return;
        }
        node = node.left;
      } else {
        if (node.right == null) {
          node.right = newNode;
          return;
        }
        node = node.right;
      }
    }
    depth++;
  }
}
function removeDocByID(tree, point, docID) {
  let node = tree.root;
  let depth = 0;
  let parentNode = null;
  let direction = null;
  while (node !== null) {
    if (node?.point.lon === point.lon && node.point.lat === point.lat) {
      const index2 = node.docIDs?.indexOf(docID);
      if (index2 !== void 0 && index2 > -1) {
        node.docIDs?.splice(index2, 1);
        if (node.docIDs == null || node.docIDs.length === 0) {
          if (parentNode != null) {
            if (direction === "left") {
              parentNode.left = node.left !== null ? node.left : node.right;
            } else if (direction === "right") {
              parentNode.right = node.right !== null ? node.right : node.left;
            }
          } else {
            tree.root = node.left !== null ? node.left : node.right;
          }
        }
        return;
      }
    }
    const axis = depth % K;
    parentNode = node;
    if (axis === 0) {
      if (point.lon < node.point.lon) {
        node = node?.left;
        direction = "left";
      } else {
        node = node?.right;
        direction = "right";
      }
    } else {
      if (point.lat < node.point.lat) {
        node = node?.left;
        direction = "left";
      } else {
        node = node?.right;
        direction = "right";
      }
    }
    depth++;
  }
}
function searchByRadius(node, center, radius, inclusive = true, sort = "asc", highPrecision = false) {
  const distanceFn = highPrecision ? vincentyDistance : haversineDistance;
  const stack = [{ node, depth: 0 }];
  const result = [];
  while (stack.length > 0) {
    const { node: node2, depth } = stack.pop();
    if (node2 === null)
      continue;
    const dist = distanceFn(center, node2.point);
    if (inclusive ? dist <= radius : dist > radius) {
      result.push({ point: node2.point, docIDs: node2.docIDs ?? [] });
    }
    if (node2.left != null) {
      stack.push({ node: node2.left, depth: depth + 1 });
    }
    if (node2.right != null) {
      stack.push({ node: node2.right, depth: depth + 1 });
    }
  }
  if (sort) {
    result.sort((a3, b3) => {
      const distA = distanceFn(center, a3.point);
      const distB = distanceFn(center, b3.point);
      return sort.toLowerCase() === "asc" ? distA - distB : distB - distA;
    });
  }
  return result;
}
function searchByPolygon(root2, polygon, inclusive = true, sort = null, highPrecision = false) {
  const stack = [{ node: root2, depth: 0 }];
  const result = [];
  while (stack.length > 0) {
    const task = stack.pop();
    if (task == null || task.node == null)
      continue;
    const { node, depth } = task;
    const nextDepth = depth + 1;
    if (node.left != null) {
      stack.push({ node: node.left, depth: nextDepth });
    }
    if (node.right != null) {
      stack.push({ node: node.right, depth: nextDepth });
    }
    const isInsidePolygon = isPointInPolygon(polygon, node.point);
    if (isInsidePolygon && inclusive) {
      result.push({ point: node.point, docIDs: node.docIDs ?? [] });
    } else if (!isInsidePolygon && !inclusive) {
      result.push({ point: node.point, docIDs: node.docIDs ?? [] });
    }
  }
  const centroid = calculatePolygonCentroid(polygon);
  if (sort) {
    const sortFn = highPrecision ? vincentyDistance : haversineDistance;
    result.sort((a3, b3) => {
      const distA = sortFn(centroid, a3.point);
      const distB = sortFn(centroid, b3.point);
      return sort.toLowerCase() === "asc" ? distA - distB : distB - distA;
    });
  }
  return result;
}
function calculatePolygonCentroid(polygon) {
  let totalArea = 0;
  let centroidX = 0;
  let centroidY = 0;
  const polygonLength = polygon.length;
  for (let i3 = 0, j3 = polygonLength - 1; i3 < polygonLength; j3 = i3++) {
    const xi = polygon[i3].lon;
    const yi = polygon[i3].lat;
    const xj = polygon[j3].lon;
    const yj = polygon[j3].lat;
    const areaSegment = xi * yj - xj * yi;
    totalArea += areaSegment;
    centroidX += (xi + xj) * areaSegment;
    centroidY += (yi + yj) * areaSegment;
  }
  totalArea /= 2;
  const centroidCoordinate = 6 * totalArea;
  centroidX /= centroidCoordinate;
  centroidY /= centroidCoordinate;
  return { lon: centroidX, lat: centroidY };
}
function isPointInPolygon(polygon, point) {
  let isInside = false;
  const x2 = point.lon;
  const y2 = point.lat;
  const polygonLength = polygon.length;
  for (let i3 = 0, j3 = polygonLength - 1; i3 < polygonLength; j3 = i3++) {
    const xi = polygon[i3].lon;
    const yi = polygon[i3].lat;
    const xj = polygon[j3].lon;
    const yj = polygon[j3].lat;
    const intersect2 = yi > y2 !== yj > y2 && x2 < (xj - xi) * (y2 - yi) / (yj - yi) + xi;
    if (intersect2)
      isInside = !isInside;
  }
  return isInside;
}
function haversineDistance(coord1, coord2) {
  const P = Math.PI / 180;
  const lat1 = coord1.lat * P;
  const lat2 = coord2.lat * P;
  const deltaLat = (coord2.lat - coord1.lat) * P;
  const deltaLon = (coord2.lon - coord1.lon) * P;
  const a3 = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
  const c4 = 2 * Math.atan2(Math.sqrt(a3), Math.sqrt(1 - a3));
  return EARTH_RADIUS * c4;
}
function vincentyDistance(coord1, coord2) {
  const a3 = 6378137;
  const f3 = 1 / 298.257223563;
  const b3 = (1 - f3) * a3;
  const P = Math.PI / 180;
  const lat1 = coord1.lat * P;
  const lat2 = coord2.lat * P;
  const deltaLon = (coord2.lon - coord1.lon) * P;
  const U1 = Math.atan((1 - f3) * Math.tan(lat1));
  const U2 = Math.atan((1 - f3) * Math.tan(lat2));
  const sinU1 = Math.sin(U1);
  const cosU1 = Math.cos(U1);
  const sinU2 = Math.sin(U2);
  const cosU2 = Math.cos(U2);
  let lambda = deltaLon;
  let prevLambda;
  let iterationLimit = 1e3;
  let sinAlpha;
  let cos2Alpha;
  let sinSigma;
  let cosSigma;
  let sigma;
  do {
    const sinLambda = Math.sin(lambda);
    const cosLambda = Math.cos(lambda);
    sinSigma = Math.sqrt(cosU2 * sinLambda * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
    cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
    sigma = Math.atan2(sinSigma, cosSigma);
    sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
    cos2Alpha = 1 - sinAlpha * sinAlpha;
    const cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cos2Alpha;
    const C3 = f3 / 16 * cos2Alpha * (4 + f3 * (4 - 3 * cos2Alpha));
    prevLambda = lambda;
    lambda = deltaLon + (1 - C3) * f3 * sinAlpha * (sigma + C3 * sinSigma * (cos2SigmaM + C3 * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
  } while (Math.abs(lambda - prevLambda) > 1e-12 && --iterationLimit > 0);
  const u22 = cos2Alpha * (a3 * a3 - b3 * b3) / (b3 * b3);
  const A2 = 1 + u22 / 16384 * (4096 + u22 * (-768 + u22 * (320 - 175 * u22)));
  const B2 = u22 / 1024 * (256 + u22 * (-128 + u22 * (74 - 47 * u22)));
  const deltaSigma = B2 * sinSigma * (cosSigma - 2 * sinU1 * sinU2 / cos2Alpha + B2 / 4 * (cosSigma * (-1 + 2 * sinSigma * sinSigma) - B2 / 6 * sigma * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * sigma * sigma)));
  const s4 = b3 * A2 * (sigma - deltaSigma);
  return s4;
}

// node_modules/@orama/orama/dist/browser/components/algorithms.js
function prioritizeTokenScores(arrays, boost, threshold = 0, keywordsCount) {
  if (boost === 0) {
    throw createError("INVALID_BOOST_VALUE");
  }
  const tokenScoresMap = /* @__PURE__ */ new Map();
  const mapsLength = arrays.length;
  for (let i3 = 0; i3 < mapsLength; i3++) {
    const arr2 = arrays[i3];
    const entriesLength = arr2.length;
    for (let j3 = 0; j3 < entriesLength; j3++) {
      const [token, score] = arr2[j3];
      const boostScore = score * boost;
      const oldScore = tokenScoresMap.get(token)?.[0];
      if (oldScore !== void 0) {
        tokenScoresMap.set(token, [oldScore * 1.5 + boostScore, (tokenScoresMap?.get(token)?.[1] || 0) + 1]);
      } else {
        tokenScoresMap.set(token, [boostScore, 1]);
      }
    }
  }
  const tokenScores = [];
  for (const tokenScoreEntry of tokenScoresMap.entries()) {
    tokenScores.push([tokenScoreEntry[0], tokenScoreEntry[1][0]]);
  }
  const results = tokenScores.sort((a3, b3) => b3[1] - a3[1]);
  if (threshold === 1) {
    return results;
  }
  const allResults = results.length;
  const tokenScoreWithKeywordsCount = [];
  for (const tokenScoreEntry of tokenScoresMap.entries()) {
    tokenScoreWithKeywordsCount.push([tokenScoreEntry[0], tokenScoreEntry[1][0], tokenScoreEntry[1][1]]);
  }
  const keywordsPerToken = tokenScoreWithKeywordsCount.sort((a3, b3) => {
    if (a3[2] > b3[2])
      return -1;
    if (a3[2] < b3[2])
      return 1;
    if (a3[1] > b3[1])
      return -1;
    if (a3[1] < b3[1])
      return 1;
    return 0;
  });
  let lastTokenWithAllKeywords = void 0;
  for (let i3 = 0; i3 < allResults; i3++) {
    if (keywordsPerToken[i3][2] === keywordsCount) {
      lastTokenWithAllKeywords = i3;
    } else {
      break;
    }
  }
  if (typeof lastTokenWithAllKeywords === "undefined") {
    if (threshold === 0) {
      return [];
    }
    lastTokenWithAllKeywords = 0;
  }
  const keywordsPerTokenLength = keywordsPerToken.length;
  const resultsWithIdAndScore = new Array(keywordsPerTokenLength);
  for (let i3 = 0; i3 < keywordsPerTokenLength; i3++) {
    resultsWithIdAndScore[i3] = [keywordsPerToken[i3][0], keywordsPerToken[i3][1]];
  }
  if (threshold === 0) {
    return resultsWithIdAndScore.slice(0, lastTokenWithAllKeywords + 1);
  }
  const thresholdLength = lastTokenWithAllKeywords + Math.ceil(threshold * 100 * (allResults - lastTokenWithAllKeywords) / 100);
  return resultsWithIdAndScore.slice(0, allResults + thresholdLength);
}
function BM25(tf, matchingCount, docsCount, fieldLength, averageFieldLength, { k: k3, b: b3, d: d3 }) {
  const idf = Math.log(1 + (docsCount - matchingCount + 0.5) / (matchingCount + 0.5));
  return idf * (d3 + tf * (k3 + 1)) / (tf + k3 * (1 - b3 + b3 * fieldLength / averageFieldLength));
}

// node_modules/@orama/orama/dist/browser/components/cosine-similarity.js
function getMagnitude(vector, vectorLength) {
  let magnitude = 0;
  for (let i3 = 0; i3 < vectorLength; i3++) {
    magnitude += vector[i3] * vector[i3];
  }
  return Math.sqrt(magnitude);
}
function findSimilarVectors(targetVector, vectors, length, threshold = 0.8) {
  const targetMagnitude = getMagnitude(targetVector, length);
  const similarVectors = [];
  for (const [vectorId, [magnitude, vector]] of Object.entries(vectors)) {
    let dotProduct = 0;
    for (let i3 = 0; i3 < length; i3++) {
      dotProduct += targetVector[i3] * vector[i3];
    }
    const similarity = dotProduct / (targetMagnitude * magnitude);
    if (similarity >= threshold) {
      similarVectors.push([vectorId, similarity]);
    }
  }
  return similarVectors.sort((a3, b3) => b3[1] - a3[1]);
}

// node_modules/@orama/orama/dist/browser/components/index.js
function insertDocumentScoreParameters(index2, prop, id, tokens, docsCount) {
  const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id);
  index2.avgFieldLength[prop] = ((index2.avgFieldLength[prop] ?? 0) * (docsCount - 1) + tokens.length) / docsCount;
  index2.fieldLengths[prop][internalId] = tokens.length;
  index2.frequencies[prop][internalId] = {};
}
function insertTokenScoreParameters(index2, prop, id, tokens, token) {
  let tokenFrequency = 0;
  for (const t3 of tokens) {
    if (t3 === token) {
      tokenFrequency++;
    }
  }
  const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id);
  const tf = tokenFrequency / tokens.length;
  index2.frequencies[prop][internalId][token] = tf;
  if (!(token in index2.tokenOccurrences[prop])) {
    index2.tokenOccurrences[prop][token] = 0;
  }
  index2.tokenOccurrences[prop][token] = (index2.tokenOccurrences[prop][token] ?? 0) + 1;
}
function removeDocumentScoreParameters(index2, prop, id, docsCount) {
  const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id);
  if (docsCount > 1) {
    index2.avgFieldLength[prop] = (index2.avgFieldLength[prop] * docsCount - index2.fieldLengths[prop][internalId]) / (docsCount - 1);
  } else {
    index2.avgFieldLength[prop] = void 0;
  }
  index2.fieldLengths[prop][internalId] = void 0;
  index2.frequencies[prop][internalId] = void 0;
}
function removeTokenScoreParameters(index2, prop, token) {
  index2.tokenOccurrences[prop][token]--;
}
function calculateResultScores(context, index2, prop, term, ids) {
  const documentIDs = Array.from(ids);
  const avgFieldLength = index2.avgFieldLength[prop];
  const fieldLengths = index2.fieldLengths[prop];
  const oramaOccurrences = index2.tokenOccurrences[prop];
  const oramaFrequencies = index2.frequencies[prop];
  const termOccurrences = typeof oramaOccurrences[term] === "number" ? oramaOccurrences[term] ?? 0 : 0;
  const scoreList = [];
  const documentIDsLength = documentIDs.length;
  for (let k3 = 0; k3 < documentIDsLength; k3++) {
    const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, documentIDs[k3]);
    const tf = oramaFrequencies?.[internalId]?.[term] ?? 0;
    const bm25 = BM25(tf, termOccurrences, context.docsCount, fieldLengths[internalId], avgFieldLength, context.params.relevance);
    scoreList.push([internalId, bm25]);
  }
  return scoreList;
}
function create6(orama, sharedInternalDocumentStore, schema, index2, prefix = "") {
  if (!index2) {
    index2 = {
      sharedInternalDocumentStore,
      indexes: {},
      vectorIndexes: {},
      searchableProperties: [],
      searchablePropertiesWithTypes: {},
      frequencies: {},
      tokenOccurrences: {},
      avgFieldLength: {},
      fieldLengths: {}
    };
  }
  for (const [prop, type] of Object.entries(schema)) {
    const path = `${prefix}${prefix ? "." : ""}${prop}`;
    if (typeof type === "object" && !Array.isArray(type)) {
      create6(orama, sharedInternalDocumentStore, type, index2, path);
      continue;
    }
    if (isVectorType(type)) {
      index2.searchableProperties.push(path);
      index2.searchablePropertiesWithTypes[path] = type;
      index2.vectorIndexes[path] = {
        size: getVectorSize(type),
        vectors: {}
      };
    } else {
      const isArray2 = /\[/.test(type);
      switch (type) {
        case "boolean":
        case "boolean[]":
          index2.indexes[path] = { type: "Bool", node: { true: [], false: [] }, isArray: isArray2 };
          break;
        case "number":
        case "number[]":
          index2.indexes[path] = { type: "AVL", node: create2(0, []), isArray: isArray2 };
          break;
        case "string":
        case "string[]":
          index2.indexes[path] = { type: "Radix", node: create4(), isArray: isArray2 };
          index2.avgFieldLength[path] = 0;
          index2.frequencies[path] = {};
          index2.tokenOccurrences[path] = {};
          index2.fieldLengths[path] = {};
          break;
        case "enum":
        case "enum[]":
          index2.indexes[path] = { type: "Flat", node: create3(), isArray: isArray2 };
          break;
        case "geopoint":
          index2.indexes[path] = { type: "BKD", node: create5(), isArray: isArray2 };
          break;
        default:
          throw createError("INVALID_SCHEMA_TYPE", Array.isArray(type) ? "array" : type, path);
      }
      index2.searchableProperties.push(path);
      index2.searchablePropertiesWithTypes[path] = type;
    }
  }
  return index2;
}
function insertScalarBuilder(implementation, index2, prop, id, language, tokenizer, docsCount, options) {
  return (value) => {
    const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id);
    const { type, node } = index2.indexes[prop];
    switch (type) {
      case "Bool": {
        node[value ? "true" : "false"].push(internalId);
        break;
      }
      case "AVL": {
        const avlRebalanceThreshold = options?.avlRebalanceThreshold ?? 1;
        insert(node, value, [internalId], avlRebalanceThreshold);
        break;
      }
      case "Radix": {
        const tokens = tokenizer.tokenize(value, language, prop);
        implementation.insertDocumentScoreParameters(index2, prop, internalId, tokens, docsCount);
        for (const token of tokens) {
          implementation.insertTokenScoreParameters(index2, prop, internalId, tokens, token);
          insert3(node, token, internalId);
        }
        break;
      }
      case "Flat": {
        insert2(node, value, internalId);
        break;
      }
      case "BKD": {
        insert4(node, value, [internalId]);
        break;
      }
    }
  };
}
function insert5(implementation, index2, prop, id, value, schemaType, language, tokenizer, docsCount, options) {
  if (isVectorType(schemaType)) {
    return insertVector(index2, prop, value, id);
  }
  const insertScalar = insertScalarBuilder(implementation, index2, prop, id, language, tokenizer, docsCount, options);
  if (!isArrayType(schemaType)) {
    return insertScalar(value);
  }
  const elements = value;
  const elementsLength = elements.length;
  for (let i3 = 0; i3 < elementsLength; i3++) {
    insertScalar(elements[i3]);
  }
}
function insertVector(index2, prop, value, id) {
  if (!(value instanceof Float32Array)) {
    value = new Float32Array(value);
  }
  const size4 = index2.vectorIndexes[prop].size;
  const magnitude = getMagnitude(value, size4);
  index2.vectorIndexes[prop].vectors[id] = [magnitude, value];
}
function removeScalar(implementation, index2, prop, id, value, schemaType, language, tokenizer, docsCount) {
  const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id);
  if (isVectorType(schemaType)) {
    delete index2.vectorIndexes[prop].vectors[id];
    return true;
  }
  const { type, node } = index2.indexes[prop];
  switch (type) {
    case "AVL": {
      removeDocument(node, internalId, value);
      return true;
    }
    case "Bool": {
      const booleanKey = value ? "true" : "false";
      const position = node[booleanKey].indexOf(internalId);
      node[value ? "true" : "false"].splice(position, 1);
      return true;
    }
    case "Radix": {
      const tokens = tokenizer.tokenize(value, language, prop);
      implementation.removeDocumentScoreParameters(index2, prop, id, docsCount);
      for (const token of tokens) {
        implementation.removeTokenScoreParameters(index2, prop, token);
        removeDocumentByWord(node, token, internalId);
      }
      return true;
    }
    case "Flat": {
      removeDocument2(node, internalId, value);
      return true;
    }
    case "BKD": {
      removeDocByID(node, value, internalId);
      return false;
    }
  }
}
function remove3(implementation, index2, prop, id, value, schemaType, language, tokenizer, docsCount) {
  if (!isArrayType(schemaType)) {
    return removeScalar(implementation, index2, prop, id, value, schemaType, language, tokenizer, docsCount);
  }
  const innerSchemaType = getInnerType(schemaType);
  const elements = value;
  const elementsLength = elements.length;
  for (let i3 = 0; i3 < elementsLength; i3++) {
    removeScalar(implementation, index2, prop, id, elements[i3], innerSchemaType, language, tokenizer, docsCount);
  }
  return true;
}
function search(context, index2, prop, term) {
  if (!(prop in index2.tokenOccurrences)) {
    return [];
  }
  const { node, type } = index2.indexes[prop];
  if (type !== "Radix") {
    throw createError("WRONG_SEARCH_PROPERTY_TYPE", prop);
  }
  const { exact, tolerance } = context.params;
  const searchResult = find2(node, { term, exact, tolerance });
  const ids = /* @__PURE__ */ new Set();
  for (const key in searchResult) {
    const ownProperty = getOwnProperty(searchResult, key);
    if (!ownProperty)
      continue;
    for (const id of searchResult[key]) {
      ids.add(id);
    }
  }
  return context.index.calculateResultScores(context, index2, prop, term, Array.from(ids));
}
function searchByWhereClause(context, index2, filters) {
  const filterKeys = Object.keys(filters);
  const filtersMap = filterKeys.reduce((acc, key) => ({
    [key]: [],
    ...acc
  }), {});
  for (const param of filterKeys) {
    const operation = filters[param];
    if (typeof index2.indexes[param] === "undefined") {
      throw createError("UNKNOWN_FILTER_PROPERTY", param);
    }
    const { node, type, isArray: isArray2 } = index2.indexes[param];
    if (type === "Bool") {
      const idx = node;
      const filteredIDs = idx[operation.toString()];
      safeArrayPush(filtersMap[param], filteredIDs);
      continue;
    }
    if (type === "BKD") {
      let reqOperation;
      if ("radius" in operation) {
        reqOperation = "radius";
      } else if ("polygon" in operation) {
        reqOperation = "polygon";
      } else {
        throw new Error(`Invalid operation ${operation}`);
      }
      if (reqOperation === "radius") {
        const { value, coordinates, unit = "m", inside = true, highPrecision = false } = operation[reqOperation];
        const distanceInMeters = convertDistanceToMeters(value, unit);
        const ids = searchByRadius(node.root, coordinates, distanceInMeters, inside, void 0, highPrecision);
        safeArrayPush(filtersMap[param], ids.flatMap(({ docIDs }) => docIDs));
      } else {
        const { coordinates, inside = true, highPrecision = false } = operation[reqOperation];
        const ids = searchByPolygon(node.root, coordinates, inside, void 0, highPrecision);
        safeArrayPush(filtersMap[param], ids.flatMap(({ docIDs }) => docIDs));
      }
      continue;
    }
    if (type === "Radix" && (typeof operation === "string" || Array.isArray(operation))) {
      for (const raw of [operation].flat()) {
        const term = context.tokenizer.tokenize(raw, context.language, param);
        for (const t3 of term) {
          const filteredIDsResults = find2(node, { term: t3, exact: true });
          safeArrayPush(filtersMap[param], Object.values(filteredIDsResults).flat());
        }
      }
      continue;
    }
    const operationKeys = Object.keys(operation);
    if (operationKeys.length > 1) {
      throw createError("INVALID_FILTER_OPERATION", operationKeys.length);
    }
    if (type === "Flat") {
      const flatOperation = isArray2 ? filterArr : filter;
      safeArrayPush(filtersMap[param], flatOperation(node, operation));
      continue;
    }
    if (type === "AVL") {
      const operationOpt = operationKeys[0];
      const operationValue = operation[operationOpt];
      let filteredIDs = [];
      switch (operationOpt) {
        case "gt": {
          filteredIDs = greaterThan(node, operationValue, false);
          break;
        }
        case "gte": {
          filteredIDs = greaterThan(node, operationValue, true);
          break;
        }
        case "lt": {
          filteredIDs = lessThan(node, operationValue, false);
          break;
        }
        case "lte": {
          filteredIDs = lessThan(node, operationValue, true);
          break;
        }
        case "eq": {
          filteredIDs = find(node, operationValue) ?? [];
          break;
        }
        case "between": {
          const [min2, max2] = operationValue;
          filteredIDs = rangeSearch(node, min2, max2);
          break;
        }
      }
      safeArrayPush(filtersMap[param], filteredIDs);
    }
  }
  return intersect(Object.values(filtersMap));
}
function getSearchableProperties(index2) {
  return index2.searchableProperties;
}
function getSearchablePropertiesWithTypes(index2) {
  return index2.searchablePropertiesWithTypes;
}
function loadRadixNode(node) {
  const convertedNode = create4(node.e, node.s, node.k);
  convertedNode.d = node.d;
  convertedNode.w = node.w;
  for (const childrenKey of Object.keys(node.c)) {
    convertedNode.c[childrenKey] = loadRadixNode(node.c[childrenKey]);
  }
  return convertedNode;
}
function loadFlatNode(node) {
  return {
    numberToDocumentId: new Map(node)
  };
}
function saveFlatNode(node) {
  return Array.from(node.numberToDocumentId.entries());
}
function load3(sharedInternalDocumentStore, raw) {
  const { indexes: rawIndexes, vectorIndexes: rawVectorIndexes, searchableProperties, searchablePropertiesWithTypes, frequencies, tokenOccurrences, avgFieldLength, fieldLengths } = raw;
  const indexes = {};
  const vectorIndexes = {};
  for (const prop of Object.keys(rawIndexes)) {
    const { node, type, isArray: isArray2 } = rawIndexes[prop];
    switch (type) {
      case "Radix":
        indexes[prop] = {
          type: "Radix",
          node: loadRadixNode(node),
          isArray: isArray2
        };
        break;
      case "Flat":
        indexes[prop] = {
          type: "Flat",
          node: loadFlatNode(node),
          isArray: isArray2
        };
        break;
      default:
        indexes[prop] = rawIndexes[prop];
    }
  }
  for (const idx of Object.keys(rawVectorIndexes)) {
    const vectors = rawVectorIndexes[idx].vectors;
    for (const vec in vectors) {
      vectors[vec] = [vectors[vec][0], new Float32Array(vectors[vec][1])];
    }
    vectorIndexes[idx] = {
      size: rawVectorIndexes[idx].size,
      vectors
    };
  }
  return {
    sharedInternalDocumentStore,
    indexes,
    vectorIndexes,
    searchableProperties,
    searchablePropertiesWithTypes,
    frequencies,
    tokenOccurrences,
    avgFieldLength,
    fieldLengths
  };
}
function save3(index2) {
  const { indexes, vectorIndexes, searchableProperties, searchablePropertiesWithTypes, frequencies, tokenOccurrences, avgFieldLength, fieldLengths } = index2;
  const vectorIndexesAsArrays = {};
  for (const idx of Object.keys(vectorIndexes)) {
    const vectors = vectorIndexes[idx].vectors;
    for (const vec in vectors) {
      vectors[vec] = [vectors[vec][0], Array.from(vectors[vec][1])];
    }
    vectorIndexesAsArrays[idx] = {
      size: vectorIndexes[idx].size,
      vectors
    };
  }
  const savedIndexes = {};
  for (const name of Object.keys(indexes)) {
    const { type, node, isArray: isArray2 } = indexes[name];
    if (type !== "Flat") {
      savedIndexes[name] = indexes[name];
      continue;
    }
    savedIndexes[name] = {
      type: "Flat",
      node: saveFlatNode(node),
      isArray: isArray2
    };
  }
  return {
    indexes: savedIndexes,
    vectorIndexes: vectorIndexesAsArrays,
    searchableProperties,
    searchablePropertiesWithTypes,
    frequencies,
    tokenOccurrences,
    avgFieldLength,
    fieldLengths
  };
}
function createIndex() {
  return {
    create: create6,
    insert: insert5,
    remove: remove3,
    insertDocumentScoreParameters,
    insertTokenScoreParameters,
    removeDocumentScoreParameters,
    removeTokenScoreParameters,
    calculateResultScores,
    search,
    searchByWhereClause,
    getSearchableProperties,
    getSearchablePropertiesWithTypes,
    load: load3,
    save: save3
  };
}

// node_modules/@orama/orama/dist/browser/components/sorter.js
function innerCreate(orama, sharedInternalDocumentStore, schema, sortableDeniedProperties, prefix) {
  const sorter = {
    language: orama.tokenizer.language,
    sharedInternalDocumentStore,
    enabled: true,
    isSorted: true,
    sortableProperties: [],
    sortablePropertiesWithTypes: {},
    sorts: {}
  };
  for (const [prop, type] of Object.entries(schema)) {
    const path = `${prefix}${prefix ? "." : ""}${prop}`;
    if (sortableDeniedProperties.includes(path)) {
      continue;
    }
    if (typeof type === "object" && !Array.isArray(type)) {
      const ret = innerCreate(orama, sharedInternalDocumentStore, type, sortableDeniedProperties, path);
      safeArrayPush(sorter.sortableProperties, ret.sortableProperties);
      sorter.sorts = {
        ...sorter.sorts,
        ...ret.sorts
      };
      sorter.sortablePropertiesWithTypes = {
        ...sorter.sortablePropertiesWithTypes,
        ...ret.sortablePropertiesWithTypes
      };
      continue;
    }
    if (!isVectorType(type)) {
      switch (type) {
        case "boolean":
        case "number":
        case "string":
          sorter.sortableProperties.push(path);
          sorter.sortablePropertiesWithTypes[path] = type;
          sorter.sorts[path] = {
            docs: /* @__PURE__ */ new Map(),
            orderedDocsToRemove: /* @__PURE__ */ new Map(),
            orderedDocs: [],
            type
          };
          break;
        case "geopoint":
        case "enum":
          continue;
        case "enum[]":
        case "boolean[]":
        case "number[]":
        case "string[]":
          continue;
        default:
          throw createError("INVALID_SORT_SCHEMA_TYPE", Array.isArray(type) ? "array" : type, path);
      }
    }
  }
  return sorter;
}
function create7(orama, sharedInternalDocumentStore, schema, config) {
  const isSortEnabled = config?.enabled !== false;
  if (!isSortEnabled) {
    return {
      disabled: true
    };
  }
  return innerCreate(orama, sharedInternalDocumentStore, schema, (config || {}).unsortableProperties || [], "");
}
function insert6(sorter, prop, id, value) {
  if (!sorter.enabled) {
    return;
  }
  sorter.isSorted = false;
  const internalId = getInternalDocumentId(sorter.sharedInternalDocumentStore, id);
  const s4 = sorter.sorts[prop];
  if (s4.orderedDocsToRemove.has(internalId)) {
    ensureOrderedDocsAreDeletedByProperty(sorter, prop);
  }
  s4.docs.set(internalId, s4.orderedDocs.length);
  s4.orderedDocs.push([internalId, value]);
}
function ensureIsSorted(sorter) {
  if (sorter.isSorted || !sorter.enabled) {
    return;
  }
  const properties = Object.keys(sorter.sorts);
  for (const prop of properties) {
    ensurePropertyIsSorted(sorter, prop);
  }
  sorter.isSorted = true;
}
function stringSort(language, value, d3) {
  return value[1].localeCompare(d3[1], getLocale(language));
}
function numberSort(value, d3) {
  return value[1] - d3[1];
}
function booleanSort(value, d3) {
  return d3[1] ? -1 : 1;
}
function ensurePropertyIsSorted(sorter, prop) {
  const s4 = sorter.sorts[prop];
  let predicate;
  switch (s4.type) {
    case "string":
      predicate = stringSort.bind(null, sorter.language);
      break;
    case "number":
      predicate = numberSort.bind(null);
      break;
    case "boolean":
      predicate = booleanSort.bind(null);
      break;
  }
  s4.orderedDocs.sort(predicate);
  const orderedDocsLength = s4.orderedDocs.length;
  for (let i3 = 0; i3 < orderedDocsLength; i3++) {
    const docId = s4.orderedDocs[i3][0];
    s4.docs.set(docId, i3);
  }
}
function ensureOrderedDocsAreDeleted(sorter) {
  const properties = Object.keys(sorter.sorts);
  for (const prop of properties) {
    ensureOrderedDocsAreDeletedByProperty(sorter, prop);
  }
}
function ensureOrderedDocsAreDeletedByProperty(sorter, prop) {
  const s4 = sorter.sorts[prop];
  if (!s4.orderedDocsToRemove.size)
    return;
  s4.orderedDocs = s4.orderedDocs.filter((doc) => !s4.orderedDocsToRemove.has(doc[0]));
  s4.orderedDocsToRemove.clear();
}
function remove4(sorter, prop, id) {
  if (!sorter.enabled) {
    return;
  }
  const s4 = sorter.sorts[prop];
  const internalId = getInternalDocumentId(sorter.sharedInternalDocumentStore, id);
  const index2 = s4.docs.get(internalId);
  if (!index2)
    return;
  s4.docs.delete(internalId);
  s4.orderedDocsToRemove.set(internalId, true);
}
function sortBy(sorter, docIds, by) {
  if (!sorter.enabled) {
    throw createError("SORT_DISABLED");
  }
  const property = by.property;
  const isDesc = by.order === "DESC";
  const s4 = sorter.sorts[property];
  if (!s4) {
    throw createError("UNABLE_TO_SORT_ON_UNKNOWN_FIELD", property, sorter.sortableProperties.join(", "));
  }
  ensureOrderedDocsAreDeletedByProperty(sorter, property);
  ensureIsSorted(sorter);
  docIds.sort((a3, b3) => {
    const indexOfA = s4.docs.get(getInternalDocumentId(sorter.sharedInternalDocumentStore, a3[0]));
    const indexOfB = s4.docs.get(getInternalDocumentId(sorter.sharedInternalDocumentStore, b3[0]));
    const isAIndexed = typeof indexOfA !== "undefined";
    const isBIndexed = typeof indexOfB !== "undefined";
    if (!isAIndexed && !isBIndexed) {
      return 0;
    }
    if (!isAIndexed) {
      return 1;
    }
    if (!isBIndexed) {
      return -1;
    }
    return isDesc ? indexOfB - indexOfA : indexOfA - indexOfB;
  });
  return docIds;
}
function getSortableProperties(sorter) {
  if (!sorter.enabled) {
    return [];
  }
  return sorter.sortableProperties;
}
function getSortablePropertiesWithTypes(sorter) {
  if (!sorter.enabled) {
    return {};
  }
  return sorter.sortablePropertiesWithTypes;
}
function load4(sharedInternalDocumentStore, raw) {
  const rawDocument = raw;
  if (!rawDocument.enabled) {
    return {
      enabled: false
    };
  }
  const sorts = Object.keys(rawDocument.sorts).reduce((acc, prop) => {
    const { docs, orderedDocs, type } = rawDocument.sorts[prop];
    acc[prop] = {
      docs: new Map(Object.entries(docs).map(([k3, v5]) => [+k3, v5])),
      orderedDocsToRemove: /* @__PURE__ */ new Map(),
      orderedDocs,
      type
    };
    return acc;
  }, {});
  return {
    sharedInternalDocumentStore,
    language: rawDocument.language,
    sortableProperties: rawDocument.sortableProperties,
    sortablePropertiesWithTypes: rawDocument.sortablePropertiesWithTypes,
    sorts,
    enabled: true,
    isSorted: rawDocument.isSorted
  };
}
function save4(sorter) {
  if (!sorter.enabled) {
    return {
      enabled: false
    };
  }
  ensureOrderedDocsAreDeleted(sorter);
  ensureIsSorted(sorter);
  const sorts = Object.keys(sorter.sorts).reduce((acc, prop) => {
    const { docs, orderedDocs, type } = sorter.sorts[prop];
    acc[prop] = {
      docs: Object.fromEntries(docs.entries()),
      orderedDocs,
      type
    };
    return acc;
  }, {});
  return {
    language: sorter.language,
    sortableProperties: sorter.sortableProperties,
    sortablePropertiesWithTypes: sorter.sortablePropertiesWithTypes,
    sorts,
    enabled: sorter.enabled,
    isSorted: sorter.isSorted
  };
}
function createSorter() {
  return {
    create: create7,
    insert: insert6,
    remove: remove4,
    save: save4,
    load: load4,
    sortBy,
    getSortableProperties,
    getSortablePropertiesWithTypes
  };
}

// node_modules/@orama/orama/dist/browser/components/tokenizer/diacritics.js
var DIACRITICS_CHARCODE_START = 192;
var DIACRITICS_CHARCODE_END = 383;
var CHARCODE_REPLACE_MAPPING = [
  65,
  65,
  65,
  65,
  65,
  65,
  65,
  67,
  69,
  69,
  69,
  69,
  73,
  73,
  73,
  73,
  69,
  78,
  79,
  79,
  79,
  79,
  79,
  null,
  79,
  85,
  85,
  85,
  85,
  89,
  80,
  115,
  97,
  97,
  97,
  97,
  97,
  97,
  97,
  99,
  101,
  101,
  101,
  101,
  105,
  105,
  105,
  105,
  101,
  110,
  111,
  111,
  111,
  111,
  111,
  null,
  111,
  117,
  117,
  117,
  117,
  121,
  112,
  121,
  65,
  97,
  65,
  97,
  65,
  97,
  67,
  99,
  67,
  99,
  67,
  99,
  67,
  99,
  68,
  100,
  68,
  100,
  69,
  101,
  69,
  101,
  69,
  101,
  69,
  101,
  69,
  101,
  71,
  103,
  71,
  103,
  71,
  103,
  71,
  103,
  72,
  104,
  72,
  104,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  73,
  105,
  74,
  106,
  75,
  107,
  107,
  76,
  108,
  76,
  108,
  76,
  108,
  76,
  108,
  76,
  108,
  78,
  110,
  78,
  110,
  78,
  110,
  110,
  78,
  110,
  79,
  111,
  79,
  111,
  79,
  111,
  79,
  111,
  82,
  114,
  82,
  114,
  82,
  114,
  83,
  115,
  83,
  115,
  83,
  115,
  83,
  115,
  84,
  116,
  84,
  116,
  84,
  116,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  85,
  117,
  87,
  119,
  89,
  121,
  89,
  90,
  122,
  90,
  122,
  90,
  122,
  115
];
function replaceChar(charCode) {
  if (charCode < DIACRITICS_CHARCODE_START || charCode > DIACRITICS_CHARCODE_END)
    return charCode;
  return CHARCODE_REPLACE_MAPPING[charCode - DIACRITICS_CHARCODE_START] || charCode;
}
function replaceDiacritics(str2) {
  const stringCharCode = [];
  for (let idx = 0; idx < str2.length; idx++) {
    stringCharCode[idx] = replaceChar(str2.charCodeAt(idx));
  }
  return String.fromCharCode(...stringCharCode);
}

// node_modules/@orama/orama/dist/browser/components/tokenizer/english-stemmer.js
var step2List = {
  ational: "ate",
  tional: "tion",
  enci: "ence",
  anci: "ance",
  izer: "ize",
  bli: "ble",
  alli: "al",
  entli: "ent",
  eli: "e",
  ousli: "ous",
  ization: "ize",
  ation: "ate",
  ator: "ate",
  alism: "al",
  iveness: "ive",
  fulness: "ful",
  ousness: "ous",
  aliti: "al",
  iviti: "ive",
  biliti: "ble",
  logi: "log"
};
var step3List = {
  icate: "ic",
  ative: "",
  alize: "al",
  iciti: "ic",
  ical: "ic",
  ful: "",
  ness: ""
};
var c3 = "[^aeiou]";
var v3 = "[aeiouy]";
var C2 = c3 + "[^aeiouy]*";
var V = v3 + "[aeiou]*";
var mgr0 = "^(" + C2 + ")?" + V + C2;
var meq1 = "^(" + C2 + ")?" + V + C2 + "(" + V + ")?$";
var mgr1 = "^(" + C2 + ")?" + V + C2 + V + C2;
var s_v = "^(" + C2 + ")?" + v3;
function stemmer(w2) {
  let stem;
  let suffix;
  let re;
  let re2;
  let re3;
  let re4;
  if (w2.length < 3) {
    return w2;
  }
  const firstch = w2.substring(0, 1);
  if (firstch == "y") {
    w2 = firstch.toUpperCase() + w2.substring(1);
  }
  re = /^(.+?)(ss|i)es$/;
  re2 = /^(.+?)([^s])s$/;
  if (re.test(w2)) {
    w2 = w2.replace(re, "$1$2");
  } else if (re2.test(w2)) {
    w2 = w2.replace(re2, "$1$2");
  }
  re = /^(.+?)eed$/;
  re2 = /^(.+?)(ed|ing)$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    re = new RegExp(mgr0);
    if (re.test(fp[1])) {
      re = /.$/;
      w2 = w2.replace(re, "");
    }
  } else if (re2.test(w2)) {
    const fp = re2.exec(w2);
    stem = fp[1];
    re2 = new RegExp(s_v);
    if (re2.test(stem)) {
      w2 = stem;
      re2 = /(at|bl|iz)$/;
      re3 = new RegExp("([^aeiouylsz])\\1$");
      re4 = new RegExp("^" + C2 + v3 + "[^aeiouwxy]$");
      if (re2.test(w2)) {
        w2 = w2 + "e";
      } else if (re3.test(w2)) {
        re = /.$/;
        w2 = w2.replace(re, "");
      } else if (re4.test(w2)) {
        w2 = w2 + "e";
      }
    }
  }
  re = /^(.+?)y$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    stem = fp?.[1];
    re = new RegExp(s_v);
    if (stem && re.test(stem)) {
      w2 = stem + "i";
    }
  }
  re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    stem = fp?.[1];
    suffix = fp?.[2];
    re = new RegExp(mgr0);
    if (stem && re.test(stem)) {
      w2 = stem + step2List[suffix];
    }
  }
  re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    stem = fp?.[1];
    suffix = fp?.[2];
    re = new RegExp(mgr0);
    if (stem && re.test(stem)) {
      w2 = stem + step3List[suffix];
    }
  }
  re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
  re2 = /^(.+?)(s|t)(ion)$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    stem = fp?.[1];
    re = new RegExp(mgr1);
    if (stem && re.test(stem)) {
      w2 = stem;
    }
  } else if (re2.test(w2)) {
    const fp = re2.exec(w2);
    stem = fp?.[1] ?? "" + fp?.[2] ?? "";
    re2 = new RegExp(mgr1);
    if (re2.test(stem)) {
      w2 = stem;
    }
  }
  re = /^(.+?)e$/;
  if (re.test(w2)) {
    const fp = re.exec(w2);
    stem = fp?.[1];
    re = new RegExp(mgr1);
    re2 = new RegExp(meq1);
    re3 = new RegExp("^" + C2 + v3 + "[^aeiouwxy]$");
    if (stem && (re.test(stem) || re2.test(stem) && !re3.test(stem))) {
      w2 = stem;
    }
  }
  re = /ll$/;
  re2 = new RegExp(mgr1);
  if (re.test(w2) && re2.test(w2)) {
    re = /.$/;
    w2 = w2.replace(re, "");
  }
  if (firstch == "y") {
    w2 = firstch.toLowerCase() + w2.substring(1);
  }
  return w2;
}

// node_modules/@orama/orama/dist/browser/components/tokenizer/index.js
function normalizeToken(prop, token) {
  const key = `${this.language}:${prop}:${token}`;
  if (this.normalizationCache.has(key)) {
    return this.normalizationCache.get(key);
  }
  if (this.stopWords?.includes(token)) {
    this.normalizationCache.set(key, "");
    return "";
  }
  if (this.stemmer && !this.stemmerSkipProperties.has(prop)) {
    token = this.stemmer(token);
  }
  token = replaceDiacritics(token);
  this.normalizationCache.set(key, token);
  return token;
}
function trim(text) {
  while (text[text.length - 1] === "") {
    text.pop();
  }
  while (text[0] === "") {
    text.shift();
  }
  return text;
}
function tokenize(input, language, prop) {
  if (language && language !== this.language) {
    throw createError("LANGUAGE_NOT_SUPPORTED", language);
  }
  if (typeof input !== "string") {
    return [input];
  }
  let tokens;
  if (prop && this.tokenizeSkipProperties.has(prop)) {
    tokens = [this.normalizeToken.bind(this, prop ?? "")(input)];
  } else {
    const splitRule = SPLITTERS[this.language];
    tokens = input.toLowerCase().split(splitRule).map(this.normalizeToken.bind(this, prop ?? "")).filter(Boolean);
  }
  const trimTokens = trim(tokens);
  if (!this.allowDuplicates) {
    return Array.from(new Set(trimTokens));
  }
  return trimTokens;
}
function createTokenizer(config = {}) {
  if (!config.language) {
    config.language = "english";
  } else if (!SUPPORTED_LANGUAGES.includes(config.language)) {
    throw createError("LANGUAGE_NOT_SUPPORTED", config.language);
  }
  let stemmer2;
  if (config.stemming || config.stemmer && !("stemming" in config)) {
    if (config.stemmer) {
      if (typeof config.stemmer !== "function") {
        throw createError("INVALID_STEMMER_FUNCTION_TYPE");
      }
      stemmer2 = config.stemmer;
    } else {
      if (config.language === "english") {
        stemmer2 = stemmer;
      } else {
        throw createError("MISSING_STEMMER", config.language);
      }
    }
  }
  let stopWords;
  if (config.stopWords !== false) {
    stopWords = [];
    if (Array.isArray(config.stopWords)) {
      stopWords = config.stopWords;
    } else if (typeof config.stopWords === "function") {
      stopWords = config.stopWords(stopWords);
    } else if (config.stopWords) {
      throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
    }
    if (!Array.isArray(stopWords)) {
      throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
    }
    for (const s4 of stopWords) {
      if (typeof s4 !== "string") {
        throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");
      }
    }
  }
  const tokenizer = {
    tokenize,
    language: config.language,
    stemmer: stemmer2,
    stemmerSkipProperties: new Set(config.stemmerSkipProperties ? [config.stemmerSkipProperties].flat() : []),
    tokenizeSkipProperties: new Set(config.tokenizeSkipProperties ? [config.tokenizeSkipProperties].flat() : []),
    stopWords,
    allowDuplicates: Boolean(config.allowDuplicates),
    normalizeToken,
    normalizationCache: /* @__PURE__ */ new Map()
  };
  tokenizer.tokenize = tokenize.bind(tokenizer);
  tokenizer.normalizeToken = normalizeToken;
  return tokenizer;
}

// node_modules/@orama/orama/dist/browser/methods/create.js
function validateComponents(components2) {
  const defaultComponents = {
    formatElapsedTime,
    getDocumentIndexId,
    getDocumentProperties,
    validateSchema
  };
  for (const rawKey of FUNCTION_COMPONENTS) {
    const key = rawKey;
    if (components2[key]) {
      if (typeof components2[key] !== "function") {
        throw createError("COMPONENT_MUST_BE_FUNCTION", key);
      }
    } else {
      components2[key] = defaultComponents[key];
    }
  }
  for (const rawKey of Object.keys(components2)) {
    if (!OBJECT_COMPONENTS.includes(rawKey) && !FUNCTION_COMPONENTS.includes(rawKey)) {
      throw createError("UNSUPPORTED_COMPONENT", rawKey);
    }
  }
}
function create8({ schema, sort, language, components: components2, id, plugins }) {
  if (!components2) {
    components2 = {};
  }
  if (!id) {
    id = uniqueId();
  }
  let tokenizer = components2.tokenizer;
  let index2 = components2.index;
  let documentsStore = components2.documentsStore;
  let sorter = components2.sorter;
  if (!tokenizer) {
    tokenizer = createTokenizer({ language: language ?? "english" });
  } else if (!tokenizer.tokenize) {
    tokenizer = createTokenizer(tokenizer);
  } else {
    const customTokenizer = tokenizer;
    tokenizer = customTokenizer;
  }
  if (components2.tokenizer && language) {
    throw createError("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");
  }
  const internalDocumentStore = createInternalDocumentIDStore();
  index2 || (index2 = createIndex());
  sorter || (sorter = createSorter());
  documentsStore || (documentsStore = createDocumentsStore());
  validateComponents(components2);
  const { getDocumentProperties: getDocumentProperties2, getDocumentIndexId: getDocumentIndexId2, validateSchema: validateSchema2, formatElapsedTime: formatElapsedTime2 } = components2;
  const orama = {
    data: {},
    caches: {},
    schema,
    tokenizer,
    index: index2,
    sorter,
    documentsStore,
    internalDocumentIDStore: internalDocumentStore,
    getDocumentProperties: getDocumentProperties2,
    getDocumentIndexId: getDocumentIndexId2,
    validateSchema: validateSchema2,
    beforeInsert: [],
    afterInsert: [],
    beforeRemove: [],
    afterRemove: [],
    beforeUpdate: [],
    afterUpdate: [],
    beforeSearch: [],
    afterSearch: [],
    beforeInsertMultiple: [],
    afterInsertMultiple: [],
    beforeRemoveMultiple: [],
    afterRemoveMultiple: [],
    afterUpdateMultiple: [],
    beforeUpdateMultiple: [],
    afterCreate: [],
    formatElapsedTime: formatElapsedTime2,
    id,
    plugins,
    version: getVersion()
  };
  orama.data = {
    index: orama.index.create(orama, internalDocumentStore, schema),
    docs: orama.documentsStore.create(orama, internalDocumentStore),
    sorting: orama.sorter.create(orama, internalDocumentStore, schema, sort)
  };
  for (const hook of AVAILABLE_PLUGIN_HOOKS) {
    orama[hook] = (orama[hook] ?? []).concat(getAllPluginsByHook(orama, hook));
  }
  const afterCreate = orama["afterCreate"];
  if (afterCreate) {
    runAfterCreate(afterCreate, orama);
  }
  return orama;
}
function getVersion() {
  return "{{VERSION}}";
}

// node_modules/@orama/orama/dist/browser/constants.js
var MODE_FULLTEXT_SEARCH = "fulltext";
var MODE_HYBRID_SEARCH = "hybrid";
var MODE_VECTOR_SEARCH = "vector";

// node_modules/@orama/orama/dist/browser/types.js
var kInsertions = Symbol("orama.insertions");
var kRemovals = Symbol("orama.removals");

// node_modules/@orama/orama/dist/browser/components/sync-blocking-checker.js
var warn = globalThis.process?.emitWarning ?? function emitWarning(message, options) {
  console.warn(`[WARNING] [${options.code}] ${message}`);
};
function trackInsertion(orama) {
  if (typeof orama[kInsertions] !== "number") {
    queueMicrotask(() => {
      orama[kInsertions] = void 0;
    });
    orama[kInsertions] = 0;
  }
  if (orama[kInsertions] > 1e3) {
    warn("Orama's insert operation is synchronous. Please avoid inserting a large number of document in a single operation in order not to block the main thread or, in alternative, please use insertMultiple.", { code: "ORAMA0001" });
    orama[kInsertions] = -1;
  } else if (orama[kInsertions] >= 0) {
    orama[kInsertions]++;
  }
}
function trackRemoval(orama) {
  if (typeof orama[kRemovals] !== "number") {
    queueMicrotask(() => {
      orama[kRemovals] = void 0;
    });
    orama[kRemovals] = 0;
  }
  if (orama[kRemovals] > 1e3) {
    warn("Orama's remove operation is synchronous. Please avoid removing a large number of document in a single operation in order not to block the main thread, in alternative, please use updateMultiple.", { code: "ORAMA0002" });
    orama[kRemovals] = -1;
  } else if (orama[kRemovals] >= 0) {
    orama[kRemovals]++;
  }
}

// node_modules/@orama/orama/dist/browser/methods/insert.js
function insert7(orama, doc, language, skipHooks, options) {
  const errorProperty = orama.validateSchema(doc, orama.schema);
  if (errorProperty) {
    throw createError("SCHEMA_VALIDATION_FAILURE", errorProperty);
  }
  const asyncNeeded = isAsyncFunction(orama.index.beforeInsert) || isAsyncFunction(orama.index.insert) || isAsyncFunction(orama.index.afterInsert);
  if (asyncNeeded) {
    return innerInsertAsync(orama, doc, language, skipHooks, options);
  }
  return innerInsertSync(orama, doc, language, skipHooks, options);
}
var ENUM_TYPE = /* @__PURE__ */ new Set(["enum", "enum[]"]);
var STRING_NUMBER_TYPE = /* @__PURE__ */ new Set(["string", "number"]);
async function innerInsertAsync(orama, doc, language, skipHooks, options) {
  const { index: index2, docs } = orama.data;
  const id = orama.getDocumentIndexId(doc);
  if (typeof id !== "string") {
    throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof id);
  }
  if (!orama.documentsStore.store(docs, id, doc)) {
    throw createError("DOCUMENT_ALREADY_EXISTS", id);
  }
  const docsCount = orama.documentsStore.count(docs);
  if (!skipHooks) {
    await runSingleHook(orama.beforeInsert, orama, id, doc);
  }
  const indexableProperties = orama.index.getSearchableProperties(index2);
  const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
  const indexableValues = orama.getDocumentProperties(doc, indexableProperties);
  for (const [key, value] of Object.entries(indexableValues)) {
    if (typeof value === "undefined")
      continue;
    const actualType = typeof value;
    const expectedType = indexablePropertiesWithTypes[key];
    validateDocumentProperty(actualType, expectedType, key, value);
  }
  await indexAndSortDocument(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options);
  if (!skipHooks) {
    await runSingleHook(orama.afterInsert, orama, id, doc);
  }
  trackInsertion(orama);
  return id;
}
function innerInsertSync(orama, doc, language, skipHooks, options) {
  const { index: index2, docs } = orama.data;
  const id = orama.getDocumentIndexId(doc);
  if (typeof id !== "string") {
    throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof id);
  }
  if (!orama.documentsStore.store(docs, id, doc)) {
    throw createError("DOCUMENT_ALREADY_EXISTS", id);
  }
  const docsCount = orama.documentsStore.count(docs);
  if (!skipHooks) {
    runSingleHook(orama.beforeInsert, orama, id, doc);
  }
  const indexableProperties = orama.index.getSearchableProperties(index2);
  const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
  const indexableValues = orama.getDocumentProperties(doc, indexableProperties);
  for (const [key, value] of Object.entries(indexableValues)) {
    if (typeof value === "undefined")
      continue;
    const actualType = typeof value;
    const expectedType = indexablePropertiesWithTypes[key];
    validateDocumentProperty(actualType, expectedType, key, value);
  }
  indexAndSortDocumentSync(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options);
  if (!skipHooks) {
    runSingleHook(orama.afterInsert, orama, id, doc);
  }
  trackInsertion(orama);
  return id;
}
function validateDocumentProperty(actualType, expectedType, key, value) {
  if (isGeoPointType(expectedType) && typeof value === "object" && typeof value.lon === "number" && typeof value.lat === "number") {
    return;
  }
  if (isVectorType(expectedType) && Array.isArray(value))
    return;
  if (isArrayType(expectedType) && Array.isArray(value))
    return;
  if (ENUM_TYPE.has(expectedType) && STRING_NUMBER_TYPE.has(actualType))
    return;
  if (actualType !== expectedType) {
    throw createError("INVALID_DOCUMENT_PROPERTY", key, expectedType, actualType);
  }
}
async function indexAndSortDocument(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options) {
  for (const prop of indexableProperties) {
    const value = indexableValues[prop];
    if (typeof value === "undefined")
      continue;
    const expectedType = orama.index.getSearchablePropertiesWithTypes(orama.data.index)[prop];
    await orama.index.beforeInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount);
    await orama.index.insert(orama.index, orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount, options);
    await orama.index.afterInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount);
  }
  const sortableProperties = orama.sorter.getSortableProperties(orama.data.sorting);
  const sortableValues = orama.getDocumentProperties(doc, sortableProperties);
  for (const prop of sortableProperties) {
    const value = sortableValues[prop];
    if (typeof value === "undefined")
      continue;
    const expectedType = orama.sorter.getSortablePropertiesWithTypes(orama.data.sorting)[prop];
    orama.sorter.insert(orama.data.sorting, prop, id, value, expectedType, language);
  }
}
function indexAndSortDocumentSync(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options) {
  for (const prop of indexableProperties) {
    const value = indexableValues[prop];
    if (typeof value === "undefined")
      continue;
    const expectedType = orama.index.getSearchablePropertiesWithTypes(orama.data.index)[prop];
    orama.index.beforeInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount);
    orama.index.insert(orama.index, orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount, options);
    orama.index.afterInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount);
  }
  const sortableProperties = orama.sorter.getSortableProperties(orama.data.sorting);
  const sortableValues = orama.getDocumentProperties(doc, sortableProperties);
  for (const prop of sortableProperties) {
    const value = sortableValues[prop];
    if (typeof value === "undefined")
      continue;
    const expectedType = orama.sorter.getSortablePropertiesWithTypes(orama.data.sorting)[prop];
    orama.sorter.insert(orama.data.sorting, prop, id, value, expectedType, language);
  }
}

// node_modules/@orama/orama/dist/browser/methods/remove.js
function remove5(orama, id, language, skipHooks) {
  const asyncNeeded = isAsyncFunction(orama.index.beforeRemove) || isAsyncFunction(orama.index.remove) || isAsyncFunction(orama.index.afterRemove);
  if (asyncNeeded) {
    return removeAsync(orama, id, language, skipHooks);
  }
  return removeSync(orama, id, language, skipHooks);
}
async function removeAsync(orama, id, language, skipHooks) {
  let result = true;
  const { index: index2, docs } = orama.data;
  const doc = orama.documentsStore.get(docs, id);
  if (!doc) {
    return false;
  }
  const docId = getDocumentIdFromInternalId(orama.internalDocumentIDStore, getInternalDocumentId(orama.internalDocumentIDStore, id));
  const docsCount = orama.documentsStore.count(docs);
  if (!skipHooks) {
    await runSingleHook(orama.beforeRemove, orama, docId);
  }
  const indexableProperties = orama.index.getSearchableProperties(index2);
  const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
  const values = orama.getDocumentProperties(doc, indexableProperties);
  for (const prop of indexableProperties) {
    const value = values[prop];
    if (typeof value === "undefined") {
      continue;
    }
    const schemaType = indexablePropertiesWithTypes[prop];
    await orama.index.beforeRemove?.(orama.data.index, prop, docId, value, schemaType, language, orama.tokenizer, docsCount);
    if (!await orama.index.remove(orama.index, orama.data.index, prop, id, value, schemaType, language, orama.tokenizer, docsCount)) {
      result = false;
    }
    await orama.index.afterRemove?.(orama.data.index, prop, docId, value, schemaType, language, orama.tokenizer, docsCount);
  }
  const sortableProperties = await orama.sorter.getSortableProperties(orama.data.sorting);
  const sortableValues = await orama.getDocumentProperties(doc, sortableProperties);
  for (const prop of sortableProperties) {
    if (typeof sortableValues[prop] === "undefined") {
      continue;
    }
    orama.sorter.remove(orama.data.sorting, prop, id);
  }
  if (!skipHooks) {
    await runSingleHook(orama.afterRemove, orama, docId);
  }
  orama.documentsStore.remove(orama.data.docs, id);
  trackRemoval(orama);
  return result;
}
function removeSync(orama, id, language, skipHooks) {
  let result = true;
  const { index: index2, docs } = orama.data;
  const doc = orama.documentsStore.get(docs, id);
  if (!doc) {
    return false;
  }
  const docId = getDocumentIdFromInternalId(orama.internalDocumentIDStore, getInternalDocumentId(orama.internalDocumentIDStore, id));
  const docsCount = orama.documentsStore.count(docs);
  if (!skipHooks) {
    runSingleHook(orama.beforeRemove, orama, docId);
  }
  const indexableProperties = orama.index.getSearchableProperties(index2);
  const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
  const values = orama.getDocumentProperties(doc, indexableProperties);
  for (const prop of indexableProperties) {
    const value = values[prop];
    if (typeof value === "undefined") {
      continue;
    }
    const schemaType = indexablePropertiesWithTypes[prop];
    orama.index.beforeRemove?.(orama.data.index, prop, docId, value, schemaType, language, orama.tokenizer, docsCount);
    if (!orama.index.remove(orama.index, orama.data.index, prop, id, value, schemaType, language, orama.tokenizer, docsCount)) {
      result = false;
    }
    orama.index.afterRemove?.(orama.data.index, prop, docId, value, schemaType, language, orama.tokenizer, docsCount);
  }
  const sortableProperties = orama.sorter.getSortableProperties(orama.data.sorting);
  const sortableValues = orama.getDocumentProperties(doc, sortableProperties);
  for (const prop of sortableProperties) {
    if (typeof sortableValues[prop] === "undefined") {
      continue;
    }
    orama.sorter.remove(orama.data.sorting, prop, id);
  }
  if (!skipHooks) {
    runSingleHook(orama.afterRemove, orama, docId);
  }
  orama.documentsStore.remove(orama.data.docs, id);
  trackRemoval(orama);
  return result;
}
function removeMultiple(orama, ids, batchSize, language, skipHooks) {
  const asyncNeeded = isAsyncFunction(orama.index.beforeRemove) || isAsyncFunction(orama.index.remove) || isAsyncFunction(orama.index.afterRemove) || isAsyncFunction(orama.beforeRemoveMultiple) || isAsyncFunction(orama.afterRemoveMultiple);
  if (asyncNeeded) {
    return removeMultipleAsync(orama, ids, batchSize, language, skipHooks);
  }
  return removeMultipleSync(orama, ids, batchSize, language, skipHooks);
}
async function removeMultipleAsync(orama, ids, batchSize, language, skipHooks) {
  let result = 0;
  if (!batchSize) {
    batchSize = 1e3;
  }
  const docIdsForHooks = skipHooks ? [] : ids.map((id) => getDocumentIdFromInternalId(orama.internalDocumentIDStore, getInternalDocumentId(orama.internalDocumentIDStore, id)));
  if (!skipHooks) {
    await runMultipleHook(orama.beforeRemoveMultiple, orama, docIdsForHooks);
  }
  await new Promise((resolve, reject) => {
    let i3 = 0;
    async function _removeMultiple() {
      const batch = ids.slice(i3 * batchSize, ++i3 * batchSize);
      if (!batch.length) {
        return resolve();
      }
      for (const doc of batch) {
        try {
          if (await remove5(orama, doc, language, skipHooks)) {
            result++;
          }
        } catch (err) {
          reject(err);
        }
      }
      setTimeout(_removeMultiple, 0);
    }
    setTimeout(_removeMultiple, 0);
  });
  if (!skipHooks) {
    await runMultipleHook(orama.afterRemoveMultiple, orama, docIdsForHooks);
  }
  return result;
}
function removeMultipleSync(orama, ids, batchSize, language, skipHooks) {
  let result = 0;
  if (!batchSize) {
    batchSize = 1e3;
  }
  const docIdsForHooks = skipHooks ? [] : ids.map((id) => getDocumentIdFromInternalId(orama.internalDocumentIDStore, getInternalDocumentId(orama.internalDocumentIDStore, id)));
  if (!skipHooks) {
    runMultipleHook(orama.beforeRemoveMultiple, orama, docIdsForHooks);
  }
  let i3 = 0;
  function _removeMultipleSync() {
    const batch = ids.slice(i3 * batchSize, ++i3 * batchSize);
    if (!batch.length)
      return;
    for (const doc of batch) {
      if (remove5(orama, doc, language, skipHooks)) {
        result++;
      }
    }
    setTimeout(_removeMultipleSync, 0);
  }
  _removeMultipleSync();
  if (!skipHooks) {
    runMultipleHook(orama.afterRemoveMultiple, orama, docIdsForHooks);
  }
  return result;
}

// node_modules/@orama/orama/dist/browser/components/facets.js
function sortAsc(a3, b3) {
  return a3[1] - b3[1];
}
function sortDesc(a3, b3) {
  return b3[1] - a3[1];
}
function sortingPredicateBuilder(order = "desc") {
  return order.toLowerCase() === "asc" ? sortAsc : sortDesc;
}
function getFacets(orama, results, facetsConfig) {
  const facets = {};
  const allIDs = results.map(([id]) => id);
  const allDocs = orama.documentsStore.getMultiple(orama.data.docs, allIDs);
  const facetKeys = Object.keys(facetsConfig);
  const properties = orama.index.getSearchablePropertiesWithTypes(orama.data.index);
  for (const facet of facetKeys) {
    let values;
    if (properties[facet] === "number") {
      const { ranges } = facetsConfig[facet];
      const rangesLength = ranges.length;
      const tmp = Array.from({ length: rangesLength });
      for (let i3 = 0; i3 < rangesLength; i3++) {
        const range = ranges[i3];
        tmp[i3] = [`${range.from}-${range.to}`, 0];
      }
      values = Object.fromEntries(tmp);
    }
    facets[facet] = {
      count: 0,
      values: values ?? {}
    };
  }
  const allDocsLength = allDocs.length;
  for (let i3 = 0; i3 < allDocsLength; i3++) {
    const doc = allDocs[i3];
    for (const facet of facetKeys) {
      const facetValue = facet.includes(".") ? getNested(doc, facet) : doc[facet];
      const propertyType = properties[facet];
      const facetValues = facets[facet].values;
      switch (propertyType) {
        case "number": {
          const ranges = facetsConfig[facet].ranges;
          calculateNumberFacetBuilder(ranges, facetValues)(facetValue);
          break;
        }
        case "number[]": {
          const alreadyInsertedValues = /* @__PURE__ */ new Set();
          const ranges = facetsConfig[facet].ranges;
          const calculateNumberFacet = calculateNumberFacetBuilder(ranges, facetValues, alreadyInsertedValues);
          for (const v5 of facetValue) {
            calculateNumberFacet(v5);
          }
          break;
        }
        case "boolean":
        case "enum":
        case "string": {
          calculateBooleanStringOrEnumFacetBuilder(facetValues, propertyType)(facetValue);
          break;
        }
        case "boolean[]":
        case "enum[]":
        case "string[]": {
          const alreadyInsertedValues = /* @__PURE__ */ new Set();
          const innerType = propertyType === "boolean[]" ? "boolean" : "string";
          const calculateBooleanStringOrEnumFacet = calculateBooleanStringOrEnumFacetBuilder(facetValues, innerType, alreadyInsertedValues);
          for (const v5 of facetValue) {
            calculateBooleanStringOrEnumFacet(v5);
          }
          break;
        }
        default:
          throw createError("FACET_NOT_SUPPORTED", propertyType);
      }
    }
  }
  for (const facet of facetKeys) {
    const currentFacet = facets[facet];
    currentFacet.count = Object.keys(currentFacet.values).length;
    if (properties[facet] === "string") {
      const stringFacetDefinition = facetsConfig[facet];
      const sortingPredicate = sortingPredicateBuilder(stringFacetDefinition.sort);
      currentFacet.values = Object.fromEntries(Object.entries(currentFacet.values).sort(sortingPredicate).slice(stringFacetDefinition.offset ?? 0, stringFacetDefinition.limit ?? 10));
    }
  }
  return facets;
}
function calculateNumberFacetBuilder(ranges, values, alreadyInsertedValues) {
  return (facetValue) => {
    for (const range of ranges) {
      const value = `${range.from}-${range.to}`;
      if (alreadyInsertedValues?.has(value)) {
        continue;
      }
      if (facetValue >= range.from && facetValue <= range.to) {
        if (values[value] === void 0) {
          values[value] = 1;
        } else {
          values[value]++;
          alreadyInsertedValues?.add(value);
        }
      }
    }
  };
}
function calculateBooleanStringOrEnumFacetBuilder(values, propertyType, alreadyInsertedValues) {
  const defaultValue = propertyType === "boolean" ? "false" : "";
  return (facetValue) => {
    const value = facetValue?.toString() ?? defaultValue;
    if (alreadyInsertedValues?.has(value)) {
      return;
    }
    values[value] = (values[value] ?? 0) + 1;
    alreadyInsertedValues?.add(value);
  };
}

// node_modules/@orama/orama/dist/browser/components/filters.js
function intersectFilteredIDs(filtered, lookedUp) {
  const map = /* @__PURE__ */ new Map();
  const result = [];
  for (const id of filtered) {
    map.set(id, true);
  }
  for (const looked of lookedUp) {
    const [id] = looked;
    if (map.has(id)) {
      result.push(looked);
      map.delete(id);
    }
  }
  return result;
}

// node_modules/@orama/orama/dist/browser/components/groups.js
var DEFAULT_REDUCE = {
  reducer: (_2, acc, res, index2) => {
    acc[index2] = res;
    return acc;
  },
  getInitialValue: (length) => Array.from({ length })
};
var ALLOWED_TYPES = ["string", "number", "boolean"];
function getGroups(orama, results, groupBy) {
  const properties = groupBy.properties;
  const propertiesLength = properties.length;
  const schemaProperties = orama.index.getSearchablePropertiesWithTypes(orama.data.index);
  for (let i3 = 0; i3 < propertiesLength; i3++) {
    const property = properties[i3];
    if (typeof schemaProperties[property] === "undefined") {
      throw createError("UNKNOWN_GROUP_BY_PROPERTY", property);
    }
    if (!ALLOWED_TYPES.includes(schemaProperties[property])) {
      throw createError("INVALID_GROUP_BY_PROPERTY", property, ALLOWED_TYPES.join(", "), schemaProperties[property]);
    }
  }
  const allIDs = results.map(([id]) => getDocumentIdFromInternalId(orama.internalDocumentIDStore, id));
  const allDocs = orama.documentsStore.getMultiple(orama.data.docs, allIDs);
  const allDocsLength = allDocs.length;
  const returnedCount = groupBy.maxResult || Number.MAX_SAFE_INTEGER;
  const listOfValues = [];
  const g4 = {};
  for (let i3 = 0; i3 < propertiesLength; i3++) {
    const groupByKey = properties[i3];
    const group = {
      property: groupByKey,
      perValue: {}
    };
    const values = /* @__PURE__ */ new Set();
    for (let j3 = 0; j3 < allDocsLength; j3++) {
      const doc = allDocs[j3];
      const value = getNested(doc, groupByKey);
      if (typeof value === "undefined") {
        continue;
      }
      const keyValue = typeof value !== "boolean" ? value : "" + value;
      const perValue = group.perValue[keyValue] ?? {
        indexes: [],
        count: 0
      };
      if (perValue.count >= returnedCount) {
        continue;
      }
      perValue.indexes.push(j3);
      perValue.count++;
      group.perValue[keyValue] = perValue;
      values.add(value);
    }
    listOfValues.push(Array.from(values));
    g4[groupByKey] = group;
  }
  const combinations = calculateCombination(listOfValues);
  const combinationsLength = combinations.length;
  const groups = [];
  for (let i3 = 0; i3 < combinationsLength; i3++) {
    const combination = combinations[i3];
    const combinationLength = combination.length;
    const group = {
      values: [],
      indexes: []
    };
    const indexes = [];
    for (let j3 = 0; j3 < combinationLength; j3++) {
      const value = combination[j3];
      const property = properties[j3];
      indexes.push(g4[property].perValue[typeof value !== "boolean" ? value : "" + value].indexes);
      group.values.push(value);
    }
    group.indexes = intersect(indexes).sort((a3, b3) => a3 - b3);
    if (group.indexes.length === 0) {
      continue;
    }
    groups.push(group);
  }
  const groupsLength = groups.length;
  const res = Array.from({ length: groupsLength });
  for (let i3 = 0; i3 < groupsLength; i3++) {
    const group = groups[i3];
    const reduce = groupBy.reduce || DEFAULT_REDUCE;
    const docs = group.indexes.map((index2) => {
      return {
        id: allIDs[index2],
        score: results[index2][1],
        document: allDocs[index2]
      };
    });
    const func = reduce.reducer.bind(null, group.values);
    const initialValue = reduce.getInitialValue(group.indexes.length);
    const aggregationValue = docs.reduce(func, initialValue);
    res[i3] = {
      values: group.values,
      result: aggregationValue
    };
  }
  return res;
}
function calculateCombination(arrs, index2 = 0) {
  if (index2 + 1 === arrs.length)
    return arrs[index2].map((item) => [item]);
  const head = arrs[index2];
  const c4 = calculateCombination(arrs, index2 + 1);
  const combinations = [];
  for (const value of head) {
    for (const combination of c4) {
      const result = [value];
      safeArrayPush(result, combination);
      combinations.push(result);
    }
  }
  return combinations;
}

// node_modules/@orama/orama/dist/browser/methods/search-fulltext.js
function fullTextSearch(orama, params, language) {
  const timeStart = getNanosecondsTime();
  const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length;
  function performSearchLogic() {
    params.relevance = Object.assign(defaultBM25Params, params.relevance ?? {});
    const vectorProperties = Object.keys(orama.data.index.vectorIndexes);
    const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0;
    const { limit: limit2 = 10, offset: offset5 = 0, term, properties, threshold = 0, distinctOn, includeVectors = false } = params;
    const isPreflight = params.preflight === true;
    const { index: index2, docs } = orama.data;
    const tokens = orama.tokenizer.tokenize(term ?? "", language);
    let propertiesToSearch = orama.caches["propertiesToSearch"];
    if (!propertiesToSearch) {
      const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
      propertiesToSearch = orama.index.getSearchableProperties(index2);
      propertiesToSearch = propertiesToSearch.filter((prop) => propertiesToSearchWithTypes[prop].startsWith("string"));
      orama.caches["propertiesToSearch"] = propertiesToSearch;
    }
    if (properties && properties !== "*") {
      for (const prop of properties) {
        if (!propertiesToSearch.includes(prop)) {
          throw createError("UNKNOWN_INDEX", prop, propertiesToSearch.join(", "));
        }
      }
      propertiesToSearch = propertiesToSearch.filter((prop) => properties.includes(prop));
    }
    const context = createSearchContext(orama.tokenizer, orama.index, orama.documentsStore, language, params, propertiesToSearch, tokens, orama.documentsStore.count(docs), timeStart);
    const hasFilters = Object.keys(params.where ?? {}).length > 0;
    let whereFiltersIDs = [];
    if (hasFilters) {
      whereFiltersIDs = orama.index.searchByWhereClause(context, index2, params.where);
    }
    const tokensLength = tokens.length;
    if (tokensLength || properties?.length) {
      const indexesLength = propertiesToSearch.length;
      for (let i3 = 0; i3 < indexesLength; i3++) {
        const prop = propertiesToSearch[i3];
        const docIds = context.indexMap[prop];
        if (tokensLength !== 0) {
          for (let j3 = 0; j3 < tokensLength; j3++) {
            const term2 = tokens[j3];
            const scoreList = orama.index.search(context, index2, prop, term2);
            safeArrayPush(docIds[term2], scoreList);
          }
        } else {
          docIds[""] = [];
          const scoreList = orama.index.search(context, index2, prop, "");
          safeArrayPush(docIds[""], scoreList);
        }
        const vals = Object.values(docIds);
        context.docsIntersection[prop] = prioritizeTokenScores(vals, params?.boost?.[prop] ?? 1, threshold, tokensLength);
        const uniqueDocs = context.docsIntersection[prop];
        const uniqueDocsLength = uniqueDocs.length;
        for (let i4 = 0; i4 < uniqueDocsLength; i4++) {
          const [id, score] = uniqueDocs[i4];
          const prevScore = context.uniqueDocsIDs[id];
          if (prevScore) {
            context.uniqueDocsIDs[id] = prevScore + score + 0.5;
          } else {
            context.uniqueDocsIDs[id] = score;
          }
        }
      }
    } else if (tokens.length === 0 && term) {
      context.uniqueDocsIDs = {};
    } else {
      context.uniqueDocsIDs = Object.fromEntries(Object.keys(orama.documentsStore.getAll(orama.data.docs)).map((k3) => [k3, 0]));
    }
    let uniqueDocsArray = Object.entries(context.uniqueDocsIDs).map(([id, score]) => [+id, score]);
    if (hasFilters) {
      uniqueDocsArray = intersectFilteredIDs(whereFiltersIDs, uniqueDocsArray);
    }
    if (params.sortBy) {
      if (typeof params.sortBy === "function") {
        const ids = uniqueDocsArray.map(([id]) => id);
        const docs2 = orama.documentsStore.getMultiple(orama.data.docs, ids);
        const docsWithIdAndScore = docs2.map((d3, i3) => [
          uniqueDocsArray[i3][0],
          uniqueDocsArray[i3][1],
          d3
        ]);
        docsWithIdAndScore.sort(params.sortBy);
        uniqueDocsArray = docsWithIdAndScore.map(([id, score]) => [id, score]);
      } else {
        uniqueDocsArray = orama.sorter.sortBy(orama.data.sorting, uniqueDocsArray, params.sortBy).map(([id, score]) => [getInternalDocumentId(orama.internalDocumentIDStore, id), score]);
      }
    } else {
      uniqueDocsArray = uniqueDocsArray.sort(sortTokenScorePredicate);
    }
    let results;
    if (!isPreflight) {
      results = distinctOn ? fetchDocumentsWithDistinct(orama, uniqueDocsArray, offset5, limit2, distinctOn) : fetchDocuments(orama, uniqueDocsArray, offset5, limit2);
    }
    const searchResult = {
      elapsed: {
        formatted: "",
        raw: 0
      },
      hits: [],
      count: uniqueDocsArray.length
    };
    if (typeof results !== "undefined") {
      searchResult.hits = results.filter(Boolean);
      if (!includeVectors) {
        removeVectorsFromHits(searchResult, vectorProperties);
      }
    }
    if (shouldCalculateFacets) {
      const facets = getFacets(orama, uniqueDocsArray, params.facets);
      searchResult.facets = facets;
    }
    if (params.groupBy) {
      searchResult.groups = getGroups(orama, uniqueDocsArray, params.groupBy);
    }
    searchResult.elapsed = orama.formatElapsedTime(getNanosecondsTime() - context.timeStart);
    return searchResult;
  }
  async function executeSearchAsync() {
    if (orama.beforeSearch) {
      await runBeforeSearch(orama.beforeSearch, orama, params, language);
    }
    const searchResult = performSearchLogic();
    if (orama.afterSearch) {
      await runAfterSearch(orama.afterSearch, orama, params, language, searchResult);
    }
    return searchResult;
  }
  if (asyncNeeded) {
    return executeSearchAsync();
  }
  return performSearchLogic();
}

// node_modules/@orama/orama/dist/browser/methods/search-vector.js
function searchVector(orama, params, language = "english") {
  const timeStart = getNanosecondsTime();
  const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length;
  function performSearchLogic() {
    const { vector } = params;
    if (vector && (!("value" in vector) || !("property" in vector))) {
      throw createError("INVALID_VECTOR_INPUT", Object.keys(vector).join(", "));
    }
    const { limit: limit2 = 10, offset: offset5 = 0, includeVectors = false } = params;
    const vectorIndex = orama.data.index.vectorIndexes[vector.property];
    const vectorSize = vectorIndex.size;
    const vectors = vectorIndex.vectors;
    const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0;
    const hasFilters = Object.keys(params.where ?? {}).length > 0;
    const { index: index2, docs: oramaDocs } = orama.data;
    if (vector?.value.length !== vectorSize) {
      if (vector?.property === void 0 || vector?.value.length === void 0) {
        throw createError("INVALID_INPUT_VECTOR", "undefined", vectorSize, "undefined");
      }
      throw createError("INVALID_INPUT_VECTOR", vector.property, vectorSize, vector.value.length);
    }
    if (!(vector instanceof Float32Array)) {
      vector.value = new Float32Array(vector.value);
    }
    let results = findSimilarVectors(vector.value, vectors, vectorSize, params.similarity).map(([id, score]) => [getInternalDocumentId(orama.internalDocumentIDStore, id), score]);
    let propertiesToSearch = orama.caches["propertiesToSearch"];
    if (!propertiesToSearch) {
      const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
      propertiesToSearch = orama.index.getSearchableProperties(index2);
      propertiesToSearch = propertiesToSearch.filter((prop) => propertiesToSearchWithTypes[prop].startsWith("string"));
      orama.caches["propertiesToSearch"] = propertiesToSearch;
    }
    const tokens = [];
    const context = createSearchContext(orama.tokenizer, orama.index, orama.documentsStore, language, params, propertiesToSearch, tokens, orama.documentsStore.count(oramaDocs), timeStart);
    let whereFiltersIDs = [];
    if (hasFilters) {
      whereFiltersIDs = orama.index.searchByWhereClause(context, index2, params.where);
      results = intersectFilteredIDs(whereFiltersIDs, results);
    }
    let facetsResults = [];
    if (shouldCalculateFacets) {
      const facets = getFacets(orama, results, params.facets);
      facetsResults = facets;
    }
    const docs = Array.from({ length: limit2 });
    for (let i3 = 0; i3 < limit2; i3++) {
      const result = results[i3 + offset5];
      if (!result) {
        break;
      }
      const doc = orama.data.docs.docs[result[0]];
      if (doc) {
        if (!includeVectors) {
          doc[vector.property] = null;
        }
        const newDoc = {
          id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, result[0]),
          score: result[1],
          document: doc
        };
        docs[i3] = newDoc;
      }
    }
    let groups = [];
    if (params.groupBy) {
      groups = getGroups(orama, results, params.groupBy);
    }
    const timeEnd = getNanosecondsTime();
    const elapsedTime = timeEnd - timeStart;
    return {
      count: results.length,
      hits: docs.filter(Boolean),
      elapsed: {
        raw: Number(elapsedTime),
        formatted: formatNanoseconds(elapsedTime)
      },
      ...facetsResults ? { facets: facetsResults } : {},
      ...groups ? { groups } : {}
    };
  }
  async function executeSearchAsync() {
    if (orama.beforeSearch) {
      await runBeforeSearch(orama.beforeSearch, orama, params, language);
    }
    const results = performSearchLogic();
    if (orama.afterSearch) {
      await runAfterSearch(orama.afterSearch, orama, params, language, results);
    }
    return results;
  }
  if (asyncNeeded) {
    return executeSearchAsync();
  }
  return performSearchLogic();
}

// node_modules/@orama/orama/dist/browser/methods/search-hybrid.js
function hybridSearch(orama, params, language) {
  const timeStart = getNanosecondsTime();
  const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length;
  function performSearchLogic() {
    const { offset: offset5 = 0, limit: limit2 = 10, includeVectors = false } = params;
    const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0;
    const fullTextIDs = getFullTextSearchIDs(orama, params, language);
    const vectorIDs = getVectorSearchIDs(orama, params);
    const { index: index2, docs } = orama.data;
    const hybridWeights = params.hybridWeights;
    let uniqueTokenScores = mergeAndRankResults(fullTextIDs, vectorIDs, params.term ?? "", hybridWeights);
    const tokens = orama.tokenizer.tokenize(params.term ?? "", language);
    let propertiesToSearch = orama.caches["propertiesToSearch"];
    if (!propertiesToSearch) {
      const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
      propertiesToSearch = orama.index.getSearchableProperties(index2);
      propertiesToSearch = propertiesToSearch.filter((prop) => propertiesToSearchWithTypes[prop].startsWith("string"));
      orama.caches["propertiesToSearch"] = propertiesToSearch;
    }
    if (params.properties && params.properties !== "*") {
      for (const prop of params.properties) {
        if (!propertiesToSearch.includes(prop)) {
          throw createError("UNKNOWN_INDEX", prop, propertiesToSearch.join(", "));
        }
      }
      propertiesToSearch = propertiesToSearch.filter((prop) => params.properties.includes(prop));
    }
    const context = createSearchContext(orama.tokenizer, orama.index, orama.documentsStore, language, params, propertiesToSearch, tokens, orama.documentsStore.count(docs), timeStart);
    const hasFilters = Object.keys(params.where ?? {}).length > 0;
    let whereFiltersIDs = [];
    if (hasFilters) {
      whereFiltersIDs = orama.index.searchByWhereClause(context, index2, params.where);
      uniqueTokenScores = intersectFilteredIDs(whereFiltersIDs, uniqueTokenScores);
    }
    let facetsResults;
    if (shouldCalculateFacets) {
      facetsResults = getFacets(orama, uniqueTokenScores, params.facets);
    }
    let groups;
    if (params.groupBy) {
      groups = getGroups(orama, uniqueTokenScores, params.groupBy);
    }
    const results = fetchDocuments(orama, uniqueTokenScores, offset5, limit2).filter(Boolean);
    const timeEnd = getNanosecondsTime();
    const returningResults = {
      count: uniqueTokenScores.length,
      elapsed: {
        raw: Number(timeEnd - timeStart),
        formatted: formatNanoseconds(timeEnd - timeStart)
      },
      hits: results,
      ...facetsResults ? { facets: facetsResults } : {},
      ...groups ? { groups } : {}
    };
    if (!includeVectors) {
      const vectorProperties = Object.keys(orama.data.index.vectorIndexes);
      removeVectorsFromHits(returningResults, vectorProperties);
    }
    return returningResults;
  }
  async function executeSearchAsync() {
    if (orama.beforeSearch) {
      await runBeforeSearch(orama.beforeSearch, orama, params, language);
    }
    const results = performSearchLogic();
    if (orama.afterSearch) {
      await runAfterSearch(orama.afterSearch, orama, params, language, results);
    }
    return results;
  }
  if (asyncNeeded) {
    return executeSearchAsync();
  }
  return performSearchLogic();
}
function getFullTextSearchIDs(orama, params, language) {
  const timeStart = getNanosecondsTime();
  params.relevance = Object.assign(defaultBM25Params, params.relevance ?? {});
  const { term = "", properties, threshold = 0 } = params;
  const { index: index2, docs } = orama.data;
  const tokens = orama.tokenizer.tokenize(term, language);
  let propertiesToSearch = orama.caches["propertiesToSearch"];
  if (!propertiesToSearch) {
    const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index2);
    propertiesToSearch = orama.index.getSearchableProperties(index2);
    propertiesToSearch = propertiesToSearch.filter((prop) => propertiesToSearchWithTypes[prop].startsWith("string"));
    orama.caches["propertiesToSearch"] = propertiesToSearch;
  }
  if (properties && properties !== "*") {
    const propertiesToSearchSet = new Set(propertiesToSearch);
    const propertiesSet = new Set(properties);
    for (const prop of properties) {
      if (!propertiesToSearchSet.has(prop)) {
        throw createError("UNKNOWN_INDEX", prop, propertiesToSearch.join(", "));
      }
    }
    propertiesToSearch = propertiesToSearch.filter((prop) => propertiesSet.has(prop));
  }
  const context = createSearchContext(orama.tokenizer, orama.index, orama.documentsStore, language, params, propertiesToSearch, tokens, orama.documentsStore.count(docs), timeStart);
  const tokensLength = tokens.length;
  if (tokensLength || properties && properties.length > 0) {
    const indexesLength = propertiesToSearch.length;
    for (let i3 = 0; i3 < indexesLength; i3++) {
      const prop = propertiesToSearch[i3];
      if (tokensLength !== 0) {
        for (let j3 = 0; j3 < tokensLength; j3++) {
          const term2 = tokens[j3];
          const scoreList = orama.index.search(context, index2, prop, term2);
          safeArrayPush(context.indexMap[prop][term2], scoreList);
        }
      } else {
        const indexMapContent = [];
        context.indexMap[prop][""] = indexMapContent;
        const scoreList = orama.index.search(context, index2, prop, "");
        safeArrayPush(indexMapContent, scoreList);
      }
      const docIds = context.indexMap[prop];
      const vals = Object.values(docIds);
      context.docsIntersection[prop] = prioritizeTokenScores(vals, params?.boost?.[prop] ?? 1, threshold, tokensLength);
      const uniqueDocs = context.docsIntersection[prop];
      const uniqueDocsLength = uniqueDocs.length;
      for (let i4 = 0; i4 < uniqueDocsLength; i4++) {
        const [id, score] = uniqueDocs[i4];
        const prevScore = context.uniqueDocsIDs[id];
        context.uniqueDocsIDs[id] = prevScore ? prevScore + score + 0.5 : score;
      }
    }
  } else if (tokens.length === 0 && term) {
    context.uniqueDocsIDs = {};
  } else {
    context.uniqueDocsIDs = Object.fromEntries(Object.keys(orama.documentsStore.getAll(orama.data.docs)).map((k3) => [k3, 0]));
  }
  const uniqueIDs = Object.entries(context.uniqueDocsIDs).map(([id, score]) => [+id, score]).sort((a3, b3) => b3[1] - a3[1]);
  return minMaxScoreNormalization(uniqueIDs);
}
function getVectorSearchIDs(orama, params) {
  const vector = params.vector;
  const vectorIndex = orama.data.index.vectorIndexes[vector?.property];
  const vectorSize = vectorIndex.size;
  const vectors = vectorIndex.vectors;
  if (vector && (!vector.value || !vector.property)) {
    throw createError("INVALID_VECTOR_INPUT", Object.keys(vector).join(", "));
  }
  if (vector.value.length !== vectorSize) {
    throw createError("INVALID_INPUT_VECTOR", vector.property, vectorSize, vector.value.length);
  }
  if (!(vector instanceof Float32Array)) {
    vector.value = new Float32Array(vector.value);
  }
  const uniqueIDs = findSimilarVectors(vector.value, vectors, vectorSize, params.similarity).map(([id, score]) => [getInternalDocumentId(orama.internalDocumentIDStore, id), score]);
  return minMaxScoreNormalization(uniqueIDs);
}
function extractScore([, score]) {
  return score;
}
function minMaxScoreNormalization(results) {
  const maxScore = Math.max.apply(Math, results.map(extractScore));
  return results.map(([id, score]) => [id, score / maxScore]);
}
function normalizeScore(score, maxScore) {
  return score / maxScore;
}
function hybridScoreBuilder(textWeight, vectorWeight) {
  return (textScore, vectorScore) => textScore * textWeight + vectorScore * vectorWeight;
}
function mergeAndRankResults(textResults, vectorResults, query, hybridWeights) {
  const maxTextScore = Math.max.apply(Math, textResults.map(extractScore));
  const maxVectorScore = Math.max.apply(Math, vectorResults.map(extractScore));
  const hasHybridWeights = hybridWeights && hybridWeights.text && hybridWeights.vector;
  const { text: textWeight, vector: vectorWeight } = hasHybridWeights ? hybridWeights : getQueryWeights(query);
  const mergedResults = /* @__PURE__ */ new Map();
  const textResultsLength = textResults.length;
  const hybridScore = hybridScoreBuilder(textWeight, vectorWeight);
  for (let i3 = 0; i3 < textResultsLength; i3++) {
    const [id, score] = textResults[i3];
    const normalizedScore = normalizeScore(score, maxTextScore);
    const hybridScoreValue = hybridScore(normalizedScore, 0);
    mergedResults.set(id, hybridScoreValue);
  }
  const vectorResultsLength = vectorResults.length;
  for (let i3 = 0; i3 < vectorResultsLength; i3++) {
    const [resultId, score] = vectorResults[i3];
    const normalizedScore = normalizeScore(score, maxVectorScore);
    const existingRes = mergedResults.get(resultId) ?? 0;
    mergedResults.set(resultId, existingRes + hybridScore(0, normalizedScore));
  }
  return [...mergedResults].sort((a3, b3) => b3[1] - a3[1]);
}
function getQueryWeights(query) {
  return {
    text: 0.5,
    vector: 0.5
  };
}

// node_modules/@orama/orama/dist/browser/methods/search.js
var defaultBM25Params = {
  k: 1.2,
  b: 0.75,
  d: 0.5
};
function createSearchContext(tokenizer, index2, documentsStore, language, params, properties, tokens, docsCount, timeStart) {
  const indexMap = {};
  const docsIntersection = {};
  for (const prop of properties) {
    const tokensMap = {};
    for (const token of tokens) {
      tokensMap[token] = [];
    }
    indexMap[prop] = tokensMap;
    docsIntersection[prop] = [];
  }
  return {
    timeStart,
    tokenizer,
    index: index2,
    documentsStore,
    language,
    params,
    docsCount,
    uniqueDocsIDs: {},
    indexMap,
    docsIntersection
  };
}
function search2(orama, params, language) {
  const mode = params.mode ?? MODE_FULLTEXT_SEARCH;
  if (mode === MODE_FULLTEXT_SEARCH) {
    return fullTextSearch(orama, params, language);
  }
  if (mode === MODE_VECTOR_SEARCH) {
    return searchVector(orama, params);
  }
  if (mode === MODE_HYBRID_SEARCH) {
    return hybridSearch(orama, params);
  }
  throw createError("INVALID_SEARCH_MODE", mode);
}
function fetchDocumentsWithDistinct(orama, uniqueDocsArray, offset5, limit2, distinctOn) {
  const docs = orama.data.docs;
  const values = /* @__PURE__ */ new Map();
  const results = [];
  const resultIDs = /* @__PURE__ */ new Set();
  const uniqueDocsArrayLength = uniqueDocsArray.length;
  let count5 = 0;
  for (let i3 = 0; i3 < uniqueDocsArrayLength; i3++) {
    const idAndScore = uniqueDocsArray[i3];
    if (typeof idAndScore === "undefined") {
      continue;
    }
    const [id, score] = idAndScore;
    if (resultIDs.has(id)) {
      continue;
    }
    const doc = orama.documentsStore.get(docs, id);
    const value = getNested(doc, distinctOn);
    if (typeof value === "undefined" || values.has(value)) {
      continue;
    }
    values.set(value, true);
    count5++;
    if (count5 <= offset5) {
      continue;
    }
    results.push({ id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, id), score, document: doc });
    resultIDs.add(id);
    if (count5 >= offset5 + limit2) {
      break;
    }
  }
  return results;
}
function fetchDocuments(orama, uniqueDocsArray, offset5, limit2) {
  const docs = orama.data.docs;
  const results = Array.from({
    length: limit2
  });
  const resultIDs = /* @__PURE__ */ new Set();
  for (let i3 = offset5; i3 < limit2 + offset5; i3++) {
    const idAndScore = uniqueDocsArray[i3];
    if (typeof idAndScore === "undefined") {
      break;
    }
    const [id, score] = idAndScore;
    if (!resultIDs.has(id)) {
      const fullDoc = orama.documentsStore.get(docs, id);
      results[i3] = { id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, id), score, document: fullDoc };
      resultIDs.add(id);
    }
  }
  return results;
}

// node_modules/@orama/orama/dist/browser/methods/serialization.js
function load5(orama, raw) {
  orama.internalDocumentIDStore.load(orama, raw.internalDocumentIDStore);
  orama.data.index = orama.index.load(orama.internalDocumentIDStore, raw.index);
  orama.data.docs = orama.documentsStore.load(orama.internalDocumentIDStore, raw.docs);
  orama.data.sorting = orama.sorter.load(orama.internalDocumentIDStore, raw.sorting);
  orama.tokenizer.language = raw.language;
}
function save5(orama) {
  return {
    internalDocumentIDStore: orama.internalDocumentIDStore.save(orama.internalDocumentIDStore),
    index: orama.index.save(orama.data.index),
    docs: orama.documentsStore.save(orama.data.docs),
    sorting: orama.sorter.save(orama.data.sorting),
    language: orama.tokenizer.language
  };
}

// src/search/dbOperations.ts
var import_crypto_js = __toESM(require_crypto_js());
var import_obsidian6 = require("obsidian");

// src/search/chunkedStorage.ts
var CHUNK_PREFIX = "copilot-index-chunk-";
var LEGACY_INDEX_SUFFIX = ".json";
var ChunkedStorage = class {
  constructor(app2, baseDir, identifier) {
    this.app = app2;
    this.baseDir = baseDir;
    this.identifier = identifier;
  }
  getChunkPath(chunkIndex) {
    return `${this.baseDir}/${CHUNK_PREFIX}${this.identifier}-${chunkIndex}.json`;
  }
  getMetadataPath() {
    return `${this.baseDir}/${CHUNK_PREFIX}${this.identifier}-metadata.json`;
  }
  getLegacyPath() {
    return `${this.baseDir}/copilot-index-${this.identifier}${LEGACY_INDEX_SUFFIX}`;
  }
  assignDocumentToPartition(docId, totalPartitions) {
    const chars = Array.from(docId);
    const hash = chars.reduce((acc, char) => {
      return (acc << 5) - acc + char.charCodeAt(0);
    }, 0);
    return Math.abs(hash) % totalPartitions;
  }
  distributeDocumentsToPartitions(documents, numPartitions) {
    const partitions = /* @__PURE__ */ new Map();
    const documentPartitions = {};
    for (let i3 = 0; i3 < numPartitions; i3++) {
      partitions.set(i3, []);
    }
    if (getSettings().debug) {
      console.log(`Total documents to distribute: ${documents.length}`);
    }
    for (const doc of documents) {
      const partitionIndex = this.assignDocumentToPartition(doc.id, numPartitions);
      const partition5 = partitions.get(partitionIndex);
      if (!partition5) {
        throw new Error(`Invalid partition index: ${partitionIndex}`);
      }
      partition5.push(doc);
      documentPartitions[doc.id] = partitionIndex;
    }
    let totalDistributed = 0;
    partitions.forEach((docs, i3) => {
      totalDistributed += docs.length;
      if (getSettings().debug) {
        console.log(`Partition ${i3 + 1}: ${docs.length} documents`);
      }
    });
    if (getSettings().debug) {
      console.log(`Total documents distributed: ${totalDistributed}`);
      if (totalDistributed !== documents.length) {
        console.error(
          `Document count mismatch! Original: ${documents.length}, Distributed: ${totalDistributed}`
        );
      }
    }
    return partitions;
  }
  async ensureDirectoryExists(filePath) {
    const dir = filePath.substring(0, filePath.lastIndexOf("/"));
    if (!await this.app.vault.adapter.exists(dir)) {
      await this.app.vault.adapter.mkdir(dir);
    }
  }
  async saveDatabase(db) {
    try {
      const rawData = await save5(db);
      const numPartitions = getSettings().numPartitions;
      if (numPartitions === 1) {
        const legacyPath = this.getLegacyPath();
        await this.ensureDirectoryExists(legacyPath);
        await this.app.vault.adapter.write(
          legacyPath,
          JSON.stringify({
            ...rawData,
            schema: db.schema
          })
        );
        return;
      }
      const docsData = rawData.docs?.docs;
      const rawDocs = Array.isArray(docsData) ? docsData : Object.values(docsData || {});
      if (getSettings().debug) {
        console.log(`Starting save with ${rawDocs.length ?? 0} total documents`);
      }
      if (!rawDocs || rawDocs.length === 0) {
        const metadata2 = {
          numPartitions,
          vectorLength: db.schema.embedding.match(/\d+/)[0],
          schema: db.schema,
          lastModified: Date.now(),
          documentPartitions: {}
        };
        const metadataPath = this.getMetadataPath();
        await this.ensureDirectoryExists(metadataPath);
        await this.app.vault.adapter.write(metadataPath, JSON.stringify(metadata2));
        if (getSettings().debug) {
          console.log("Saved empty database state");
        }
        return;
      }
      const partitions = this.distributeDocumentsToPartitions(rawDocs, numPartitions);
      const metadata = {
        numPartitions,
        vectorLength: db.schema.embedding.match(/\d+/)[0],
        schema: db.schema,
        lastModified: Date.now(),
        documentPartitions: Object.fromEntries(
          rawDocs.map((doc) => [doc.id, this.assignDocumentToPartition(doc.id, numPartitions)])
        )
      };
      await this.saveMetadata(metadata);
      const globalData = {
        ...rawData,
        docs: { docs: {}, count: 0 },
        index: {
          ...rawData.index,
          vectorIndexes: void 0
        }
      };
      for (const [partitionIndex, docs] of partitions.entries()) {
        const partitionData = {
          index: {
            vectorIndexes: {
              embedding: {
                size: rawData.index.vectorIndexes.embedding.size,
                vectors: Object.fromEntries(
                  Object.entries(rawData.index.vectorIndexes.embedding.vectors).filter(
                    ([id]) => docs.some((doc) => doc.id === id)
                  )
                )
              }
            }
          },
          docs: {
            docs: Object.fromEntries(docs.map((doc, index2) => [(index2 + 1).toString(), doc])),
            count: docs.length
          }
        };
        const finalPartitionData = partitionIndex === 0 ? {
          ...globalData,
          docs: partitionData.docs,
          index: {
            ...globalData.index,
            vectorIndexes: partitionData.index.vectorIndexes
          }
        } : partitionData;
        const chunkPath = this.getChunkPath(partitionIndex);
        await this.ensureDirectoryExists(chunkPath);
        await this.app.vault.adapter.write(chunkPath, JSON.stringify(finalPartitionData));
        if (getSettings().debug) {
          console.log(`Saved partition ${partitionIndex + 1}/${numPartitions}`);
        }
      }
      if (getSettings().debug) {
        console.log("Saved all partitions");
      }
    } catch (error) {
      console.error(`Error saving database:`, error);
      throw new CustomError(`Failed to save database: ${error.message}`);
    }
  }
  async loadDatabase() {
    try {
      const legacyPath = this.getLegacyPath();
      if (await this.app.vault.adapter.exists(legacyPath)) {
        const legacyData = JSON.parse(await this.app.vault.adapter.read(legacyPath));
        if (!legacyData?.schema) {
          throw new CustomError("Invalid legacy database format");
        }
        const newDb2 = await create8({
          schema: legacyData.schema,
          components: {
            tokenizer: {
              stemmer: void 0,
              stopWords: void 0
            }
          }
        });
        await load5(newDb2, legacyData);
        return newDb2;
      }
      const metadata = await this.loadMetadata();
      const newDb = await create8({
        schema: metadata.schema,
        components: {
          tokenizer: {
            stemmer: void 0,
            stopWords: void 0
          }
        }
      });
      let mergedData = null;
      const allChunks = [];
      for (let i3 = 0; i3 < metadata.numPartitions; i3++) {
        const chunkPath = this.getChunkPath(i3);
        if (await this.app.vault.adapter.exists(chunkPath)) {
          const chunkData = JSON.parse(await this.app.vault.adapter.read(chunkPath));
          allChunks.push(chunkData);
          if (i3 === 0) {
            mergedData = chunkData;
          }
        }
      }
      if (!mergedData) {
        throw new CustomError("No data found in chunks");
      }
      const orderedDocs = {};
      let nextDocId = 1;
      for (const internalId of mergedData.internalDocumentIDStore.internalIdToId) {
        const doc = allChunks.flatMap((chunk) => Object.values(chunk.docs.docs)).find((doc2) => doc2.id === internalId);
        if (doc) {
          orderedDocs[nextDocId.toString()] = doc;
          nextDocId++;
        } else if (getSettings().debug) {
          console.warn(`Document ${internalId} not found in any chunk`);
        }
      }
      mergedData.docs.docs = orderedDocs;
      mergedData.docs.count = Object.keys(orderedDocs).length;
      mergedData.index.vectorIndexes.embedding.vectors = Object.assign(
        {},
        ...allChunks.map((chunk) => chunk.index?.vectorIndexes?.embedding?.vectors || {})
      );
      await load5(newDb, mergedData);
      return newDb;
    } catch (error) {
      console.error(`Error loading database:`, error);
      throw new CustomError(`Failed to load database: ${error.message}`);
    }
  }
  async clearStorage() {
    try {
      const legacyPath = this.getLegacyPath();
      if (await this.app.vault.adapter.exists(legacyPath)) {
        await this.app.vault.adapter.remove(legacyPath);
      }
      const files = await this.app.vault.adapter.list(this.baseDir);
      for (const file of files.files) {
        if (file.startsWith(`${this.baseDir}/${CHUNK_PREFIX}${this.identifier}`)) {
          await this.app.vault.adapter.remove(file);
        }
      }
    } catch (error) {
      console.error(`Error clearing storage:`, error);
      throw new CustomError(`Failed to clear storage: ${error.message}`);
    }
  }
  async exists() {
    const legacyPath = this.getLegacyPath();
    if (getSettings().numPartitions === 1) {
      return await this.app.vault.adapter.exists(legacyPath);
    }
    const metadataPath = this.getMetadataPath();
    return await this.app.vault.adapter.exists(metadataPath) || await this.app.vault.adapter.exists(legacyPath);
  }
  // Helper method to load metadata
  async loadMetadata() {
    const metadataPath = this.getMetadataPath();
    if (!await this.app.vault.adapter.exists(metadataPath)) {
      throw new CustomError("No existing database found");
    }
    const metadata = JSON.parse(await this.app.vault.adapter.read(metadataPath));
    if (!metadata?.schema) {
      throw new CustomError("Invalid metadata file: missing schema");
    }
    return metadata;
  }
  // Helper method to save metadata
  async saveMetadata(metadata) {
    const metadataPath = this.getMetadataPath();
    await this.ensureDirectoryExists(metadataPath);
    await this.app.vault.adapter.write(metadataPath, JSON.stringify(metadata));
  }
};

// src/search/searchUtils.ts
var import_obsidian5 = require("obsidian");
async function getVectorLength(embeddingInstance) {
  if (!embeddingInstance) {
    throw new CustomError("Embedding instance not found.");
  }
  try {
    const sampleText = "Sample text for embedding";
    const sampleEmbedding = await embeddingInstance.embedQuery(sampleText);
    if (!sampleEmbedding || sampleEmbedding.length === 0) {
      throw new CustomError("Failed to get valid embedding vector length");
    }
    console.log(
      `Detected vector length: ${sampleEmbedding.length} for model: ${EmbeddingManager.getModelName(embeddingInstance)}`
    );
    return sampleEmbedding.length;
  } catch (error) {
    console.error("Error getting vector length:", error);
    throw new CustomError(
      "Failed to determine embedding vector length. Please check your embedding model settings."
    );
  }
}
async function getAllQAMarkdownContent(app2) {
  let allContent = "";
  const { inclusions, exclusions } = getMatchingPatterns();
  const filteredFiles = app2.vault.getMarkdownFiles().filter((file) => {
    return shouldIndexFile(file, inclusions, exclusions);
  });
  await Promise.all(filteredFiles.map((file) => app2.vault.cachedRead(file))).then(
    (contents) => contents.map((c4) => allContent += c4 + " ")
  );
  return allContent;
}
function getExclusionPatterns() {
  if (!getSettings().qaExclusions) {
    return [];
  }
  const exclusions = [];
  exclusions.push(...extractAppIgnoreSettings(app));
  if (getSettings().qaExclusions) {
    exclusions.push(
      ...getSettings().qaExclusions.split(",").map((item) => item.trim())
    );
  }
  return exclusions;
}
function getInclusionPatterns() {
  if (!getSettings().qaInclusions) {
    return [];
  }
  const inclusions = [];
  inclusions.push(
    ...getSettings().qaInclusions.split(",").map((item) => item.trim())
  );
  return inclusions;
}
function getMatchingPatterns() {
  const inclusions = getInclusionPatterns();
  const exclusions = getExclusionPatterns();
  return { inclusions, exclusions };
}
function shouldIndexFile(file, inclusions, exclusions) {
  if (exclusions.length > 0 && matchFilePathWithPatterns(file.path, exclusions)) {
    return false;
  }
  if (inclusions.length > 0 && !matchFilePathWithPatterns(file.path, inclusions)) {
    return false;
  }
  return true;
}
function matchFilePathWithPatterns(filePath, patterns) {
  if (!patterns || patterns.length === 0)
    return false;
  const tagPatterns = [];
  const extensionPatterns = [];
  const pathPatterns = [];
  patterns.forEach((pattern) => {
    if (pattern.startsWith("#")) {
      tagPatterns.push(stripHash(pattern));
    } else if (pattern.startsWith("*")) {
      extensionPatterns.push(pattern.slice(1).toLowerCase());
    } else {
      pathPatterns.push(pattern);
    }
  });
  if (extensionPatterns.length > 0) {
    const fileExt = filePath.toLowerCase();
    if (extensionPatterns.some((ext) => fileExt.endsWith(ext))) {
      return true;
    }
  }
  if (pathPatterns.length > 0) {
    if (pathPatterns.some((pattern) => isPathInList(filePath, pattern))) {
      return true;
    }
  }
  const file = app.vault.getAbstractFileByPath(filePath);
  if (file instanceof import_obsidian5.TFile) {
    const tags = getTagsFromNote(file);
    if (tagPatterns.some((pattern) => tags.includes(pattern))) {
      return true;
    }
  }
  return false;
}
function extractAppIgnoreSettings(app2) {
  const appIgnoreFolders = [];
  try {
    const userIgnoreFilters = app2.vault.getConfig("userIgnoreFilters");
    if (!!userIgnoreFilters && Array.isArray(userIgnoreFilters)) {
      userIgnoreFilters.forEach((it) => {
        if (typeof it === "string") {
          appIgnoreFolders.push(it.endsWith("/") ? it.slice(0, -1) : it);
        }
      });
    }
  } catch (e3) {
    console.warn("Error getting userIgnoreFilters from Obsidian config", e3);
  }
  return appIgnoreFolders;
}

// src/search/dbOperations.ts
var DBOperations = class {
  constructor(app2) {
    this.app = app2;
    this.isInitialized = false;
    this.isIndexLoaded = false;
    this.hasUnsavedChanges = false;
    subscribeToSettingsChange(async () => {
      const settings = getSettings();
      if (import_obsidian6.Platform.isMobile && settings.disableIndexOnMobile) {
        this.isIndexLoaded = false;
        this.oramaDb = void 0;
      } else if (import_obsidian6.Platform.isMobile && !settings.disableIndexOnMobile && !this.oramaDb) {
        await this.initializeDB(await EmbeddingManager.getInstance().getEmbeddingsAPI());
      }
      const newPath = await this.getDbPath();
      if (this.dbPath && newPath !== this.dbPath) {
        console.log("Path change detected, reinitializing database...");
        this.dbPath = newPath;
        await this.initializeChunkedStorage();
        await this.initializeDB(await EmbeddingManager.getInstance().getEmbeddingsAPI());
        console.log("Database reinitialized with new path:", newPath);
      }
    });
  }
  async initializeChunkedStorage() {
    if (!this.app.vault.adapter) {
      throw new CustomError("Vault adapter not available. Please try again later.");
    }
    const baseDir = await this.getDbPath();
    this.chunkedStorage = new ChunkedStorage(this.app, baseDir, this.getVaultIdentifier());
    this.isInitialized = true;
  }
  async initializeDB(embeddingInstance) {
    try {
      if (!this.isInitialized) {
        this.dbPath = await this.getDbPath();
        await this.initializeChunkedStorage();
      }
      if (import_obsidian6.Platform.isMobile && getSettings().disableIndexOnMobile) {
        this.isIndexLoaded = false;
        this.oramaDb = void 0;
        return;
      }
      if (!this.chunkedStorage) {
        throw new CustomError("Storage not initialized properly");
      }
      try {
        if (await this.chunkedStorage.exists()) {
          this.oramaDb = await this.chunkedStorage.loadDatabase();
          console.log("Loaded existing chunked Orama database from disk.");
          return this.oramaDb;
        }
      } catch (error) {
        console.log("Failed to load existing database, creating new one:", error);
      }
      const newDb = await this.createNewDb(embeddingInstance);
      this.oramaDb = newDb;
      return newDb;
    } catch (error) {
      console.error(`Error initializing Orama database:`, error);
      new import_obsidian6.Notice("Failed to initialize Copilot database. Some features may be limited.");
      return void 0;
    }
  }
  async saveDB() {
    if (import_obsidian6.Platform.isMobile && getSettings().disableIndexOnMobile) {
      return;
    }
    if (!this.oramaDb || !this.chunkedStorage) {
      try {
        await this.initializeDB(await EmbeddingManager.getInstance().getEmbeddingsAPI());
        if (!this.oramaDb || !this.chunkedStorage) {
          throw new CustomError("Orama database not found.");
        }
      } catch (error) {
        console.error("Failed to initialize database during save:", error);
        throw new CustomError("Failed to initialize and save database.");
      }
    }
    try {
      await this.chunkedStorage.saveDatabase(this.oramaDb);
      this.hasUnsavedChanges = false;
      if (getSettings().debug) {
        console.log("Orama database saved successfully at:", this.dbPath);
      }
    } catch (error) {
      console.error(`Error saving Orama database:`, error);
      throw error;
    }
  }
  async clearIndex(embeddingInstance) {
    try {
      if (!this.oramaDb) {
        await this.initializeDB(embeddingInstance);
      }
      await this.chunkedStorage?.clearStorage();
      await new Promise((resolve) => setTimeout(resolve, 100));
      this.oramaDb = await this.createNewDb(embeddingInstance);
      await this.saveDB();
      new import_obsidian6.Notice("Local Copilot index cleared successfully.");
      console.log("Local Copilot index cleared successfully, new instance created.");
    } catch (err) {
      console.error("Error clearing the local Copilot index:", err);
      new import_obsidian6.Notice("An error occurred while clearing the local Copilot index.");
      throw err;
    }
  }
  async removeDocs(filePath) {
    if (!this.oramaDb) {
      throw new CustomError("Orama database not found.");
    }
    try {
      const searchResult = await search2(this.oramaDb, {
        term: filePath,
        properties: ["path"]
      });
      if (searchResult.hits.length > 0) {
        await removeMultiple(
          this.oramaDb,
          searchResult.hits.map((hit) => hit.id),
          500
        );
        if (getSettings().debug) {
          console.log(`Deleted document from local Copilot index: ${filePath}`);
        }
      }
      this.markUnsavedChanges();
    } catch (err) {
      console.error("Error deleting document from local Copilotindex:", err);
    }
  }
  getDb() {
    if (!this.oramaDb) {
      console.warn("Database not initialized. Some features may be limited.");
    }
    return this.oramaDb;
  }
  async getIsIndexLoaded() {
    return this.isIndexLoaded;
  }
  async waitForInitialization() {
    await this.initializationPromise;
  }
  onunload() {
    if (this.hasUnsavedChanges) {
      this.saveDB();
    }
  }
  getCurrentDbPath() {
    return this.dbPath;
  }
  // This is the path according to the setting's enableIndexSync
  async getDbPath() {
    const vaultRoot = this.app.vault.getRoot().path;
    let baseDir;
    if (getSettings().enableIndexSync) {
      baseDir = this.app.vault.configDir;
    } else {
      const effectiveRoot = vaultRoot === "/" ? "" : vaultRoot;
      const prefix = effectiveRoot === "" || effectiveRoot.startsWith("/") ? "" : "/";
      baseDir = `${prefix}${effectiveRoot}/.copilot-index`;
      if (!await this.app.vault.adapter.exists(baseDir)) {
        await this.app.vault.adapter.mkdir(baseDir);
        console.log("Created directory:", baseDir);
      }
    }
    return baseDir;
  }
  getVaultIdentifier() {
    const vaultName = this.app.vault.getName();
    return (0, import_crypto_js.MD5)(vaultName).toString();
  }
  markUnsavedChanges() {
    this.hasUnsavedChanges = true;
  }
  async createNewDb(embeddingInstance) {
    if (!embeddingInstance) {
      throw new CustomError("Embedding instance not found.");
    }
    const vectorLength = await getVectorLength(embeddingInstance);
    if (!vectorLength || vectorLength === 0) {
      throw new CustomError(
        "Invalid vector length detected. Please check if your embedding model is working."
      );
    }
    const schema = this.createDynamicSchema(vectorLength);
    const db = await create8({
      schema,
      components: {
        tokenizer: {
          stemmer: void 0,
          stopWords: void 0
        }
      }
    });
    console.log(
      `Created new Orama database for ${this.dbPath}. Embedding model: ${EmbeddingManager.getModelName(embeddingInstance)} with vector length ${vectorLength}.`
    );
    this.isIndexLoaded = true;
    return db;
  }
  static async getDocsByPath(db, path) {
    if (!db)
      throw new Error("DB not initialized");
    if (!path)
      return;
    const result = await search2(db, {
      term: path,
      properties: ["path"],
      exact: true,
      includeVectors: true
    });
    return result.hits;
  }
  static async getDocsByEmbedding(db, embedding, options) {
    const result = await search2(db, {
      mode: "vector",
      vector: { value: embedding, property: "embedding" },
      limit: options.limit,
      similarity: options.similarity,
      includeVectors: true
    });
    return result.hits;
  }
  static async getLatestFileMtime(db) {
    if (!db)
      throw new Error("DB not initialized");
    try {
      const result = await search2(db, {
        term: "",
        limit: 1,
        sortBy: {
          property: "mtime",
          order: "DESC"
        }
      });
      if (result.hits.length > 0) {
        const latestDoc = result.hits[0].document;
        return latestDoc.mtime;
      }
      return 0;
    } catch (err) {
      console.error("Error getting latest file mtime from VectorDB:", err);
      return 0;
    }
  }
  createDynamicSchema(vectorLength) {
    return {
      id: "string",
      title: "string",
      // basename of the TFile
      path: "string",
      // path of the TFile
      content: "string",
      embedding: `vector[${vectorLength}]`,
      embeddingModel: "string",
      created_at: "number",
      ctime: "number",
      mtime: "number",
      tags: "string[]",
      extension: "string"
    };
  }
  async upsert(docToSave) {
    if (!this.oramaDb)
      throw new Error("DB not initialized");
    try {
      const partition5 = this.chunkedStorage?.assignDocumentToPartition(
        docToSave.id,
        getSettings().numPartitions
      );
      const existingDoc = await search2(this.oramaDb, {
        term: docToSave.id,
        properties: ["id"],
        limit: 1
      });
      if (existingDoc.hits.length > 0) {
        await remove5(this.oramaDb, existingDoc.hits[0].id);
      }
      try {
        await insert7(this.oramaDb, docToSave);
        if (getSettings().debug) {
          console.log(
            `${existingDoc.hits.length > 0 ? "Updated" : "Inserted"} document ${docToSave.id} in partition ${partition5}`
          );
        }
        this.markUnsavedChanges();
        return docToSave;
      } catch (insertErr) {
        console.error(
          `Failed to ${existingDoc.hits.length > 0 ? "update" : "insert"} document ${docToSave.id}:`,
          insertErr
        );
        if (existingDoc.hits.length > 0) {
          try {
            await insert7(this.oramaDb, existingDoc.hits[0].document);
          } catch (restoreErr) {
            console.error("Failed to restore previous document version:", restoreErr);
          }
        }
        return void 0;
      }
    } catch (err) {
      console.error(`Error upserting document ${docToSave.id}:`, err);
      return void 0;
    }
  }
  async getLatestFileMtime() {
    if (!this.oramaDb)
      throw new Error("DB not initialized");
    try {
      const result = await search2(this.oramaDb, {
        term: "",
        limit: 1,
        sortBy: {
          property: "mtime",
          order: "DESC"
        }
      });
      if (result.hits.length > 0) {
        const latestDoc = result.hits[0].document;
        return latestDoc.mtime;
      }
      return 0;
    } catch (err) {
      console.error("Error getting latest file mtime from VectorDB:", err);
      return 0;
    }
  }
  async checkAndHandleEmbeddingModelChange(embeddingInstance) {
    if (!this.oramaDb) {
      console.error(
        "Orama database not found. Please make sure you have a working embedding model."
      );
      return false;
    }
    const singleDoc = await search2(this.oramaDb, {
      term: "",
      limit: 1
    });
    let prevEmbeddingModel;
    if (singleDoc.hits.length > 0) {
      const oramaDocSample = singleDoc.hits[0];
      if (typeof oramaDocSample === "object" && oramaDocSample !== null && "document" in oramaDocSample) {
        const document2 = oramaDocSample.document;
        prevEmbeddingModel = document2.embeddingModel;
      }
    }
    if (prevEmbeddingModel) {
      const currEmbeddingModel = EmbeddingManager.getModelName(embeddingInstance);
      if (!areEmbeddingModelsSame(prevEmbeddingModel, currEmbeddingModel)) {
        new import_obsidian6.Notice("New embedding model detected. Rebuilding Copilot index from scratch.");
        console.log("Detected change in embedding model. Rebuilding Copilot index from scratch.");
        this.oramaDb = await this.createNewDb(embeddingInstance);
        await this.saveDB();
        return true;
      }
    } else {
      console.log("No previous embedding model found in the database.");
    }
    return false;
  }
  static async getAllDocuments(db) {
    const result = await search2(db, {
      term: "",
      limit: 1e5,
      includeVectors: true
    });
    return result.hits.map((hit) => hit.document);
  }
  async garbageCollect() {
    if (!this.oramaDb) {
      throw new CustomError("Orama database not found.");
    }
    try {
      const files = this.app.vault.getMarkdownFiles();
      const filePaths = new Set(files.map((file) => file.path));
      const docs = await DBOperations.getAllDocuments(this.oramaDb);
      const docsToRemove = docs.filter((doc) => !filePaths.has(doc.path));
      if (docsToRemove.length === 0) {
        return 0;
      }
      console.log(
        "Copilot index: Docs to remove during garbage collection:",
        Array.from(new Set(docsToRemove.map((doc) => doc.path))).join(", ")
      );
      if (docsToRemove.length === 1) {
        await remove5(this.oramaDb, docsToRemove[0].id);
      } else {
        await removeMultiple(
          this.oramaDb,
          docsToRemove.map((hit) => hit.id),
          500
        );
      }
      await this.saveDB();
      return docsToRemove.length;
    } catch (err) {
      console.error("Error garbage collecting the Copilot index:", err);
      throw new CustomError("Failed to garbage collect the Copilot index.");
    }
  }
  async getIndexedFiles() {
    if (!this.oramaDb) {
      throw new CustomError("Orama database not found.");
    }
    try {
      const docs = await DBOperations.getAllDocuments(this.oramaDb);
      const uniquePaths = /* @__PURE__ */ new Set();
      docs.forEach((doc) => {
        uniquePaths.add(doc.path);
      });
      return Array.from(uniquePaths).sort();
    } catch (err) {
      console.error("Error getting indexed files:", err);
      throw new CustomError("Failed to retrieve indexed files.");
    }
  }
  async isIndexEmpty() {
    if (!this.oramaDb) {
      return true;
    }
    try {
      const result = await search2(this.oramaDb, {
        term: "",
        limit: 1
      });
      return result.hits.length === 0;
    } catch (err) {
      console.error("Error checking if database is empty:", err);
      throw new CustomError("Failed to check if database is empty.");
    }
  }
  async hasIndex(notePath) {
    if (!this.oramaDb) {
      return false;
    }
    const docs = await DBOperations.getDocsByPath(this.oramaDb, notePath);
    return docs !== void 0 && docs.length > 0;
  }
  async hasEmbeddings(notePath) {
    if (!this.oramaDb) {
      return false;
    }
    const docs = await DBOperations.getDocsByPath(this.oramaDb, notePath);
    if (!docs || docs.length === 0) {
      return false;
    }
    return docs.every((doc) => {
      return doc?.document?.embedding && Array.isArray(doc.document.embedding) && doc.document.embedding.length > 0;
    });
  }
  async getDocsJsonByPaths(paths) {
    if (!this.oramaDb) {
      throw new CustomError("Orama database not found.");
    }
    const result = {};
    for (const path of paths) {
      const docs = await DBOperations.getDocsByPath(this.oramaDb, path);
      if (docs && docs.length > 0) {
        result[path] = docs.map((hit) => ({
          id: hit.document.id,
          title: hit.document.title,
          path: hit.document.path,
          content: hit.document.content,
          metadata: hit.document.metadata,
          embedding: hit.document.embedding,
          embeddingModel: hit.document.embeddingModel,
          tags: hit.document.tags,
          extension: hit.document.extension,
          nchars: hit.document.nchars
        }));
      }
    }
    return result;
  }
};

// src/search/indexEventHandler.ts
var import_obsidian7 = require("obsidian");
var DEBOUNCE_DELAY = 1e4;
var IndexEventHandler = class {
  constructor(app2, indexOps, dbOps) {
    this.app = app2;
    this.indexOps = indexOps;
    this.dbOps = dbOps;
    this.debounceTimer = null;
    this.handleFileModify = async (file) => {
      if (import_obsidian7.Platform.isMobile && getSettings().disableIndexOnMobile) {
        return;
      }
      const currentChainType = getChainType();
      if (file instanceof import_obsidian7.TFile && file.extension === "md" && currentChainType === "copilot_plus" /* COPILOT_PLUS_CHAIN */) {
        const { inclusions, exclusions } = getMatchingPatterns();
        const shouldProcess = shouldIndexFile(file, inclusions, exclusions);
        if (shouldProcess) {
          this.debouncedReindexFile(file);
        }
      }
    };
    this.debouncedReindexFile = (file) => {
      if (this.debounceTimer !== null) {
        window.clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = window.setTimeout(() => {
        if (getSettings().debug) {
          console.log("Copilot Plus: Triggering reindex for file ", file.path);
        }
        this.indexOps.reindexFile(file);
        this.debounceTimer = null;
      }, DEBOUNCE_DELAY);
    };
    this.handleFileDelete = async (file) => {
      if (file instanceof import_obsidian7.TFile) {
        await this.dbOps.removeDocs(file.path);
      }
    };
    this.initializeEventListeners();
  }
  initializeEventListeners() {
    if (getSettings().debug) {
      console.log("Copilot Plus: Initializing event listeners");
    }
    this.app.vault.on("modify", this.handleFileModify);
    this.app.vault.on("delete", this.handleFileDelete);
  }
  cleanup() {
    if (this.debounceTimer !== null) {
      window.clearTimeout(this.debounceTimer);
    }
    this.app.vault.off("modify", this.handleFileModify);
    this.app.vault.off("delete", this.handleFileDelete);
  }
};

// src/rateLimiter.ts
var RateLimiter = class {
  constructor(requestsPerSecond) {
    this.queue = [];
    this.lastRequestTime = 0;
    this.processing = false;
    this.requestsPerSecond = requestsPerSecond;
  }
  setRequestsPerSecond(requestsPerSecond) {
    this.requestsPerSecond = requestsPerSecond;
  }
  getRequestsPerSecond() {
    return this.requestsPerSecond;
  }
  async wait() {
    return new Promise((resolve) => {
      this.queue.push(resolve);
      this.process();
    });
  }
  async process() {
    if (this.processing)
      return;
    this.processing = true;
    try {
      while (this.queue.length > 0) {
        const now3 = Date.now();
        const timeToWait = Math.max(0, this.lastRequestTime + 1e3 / this.requestsPerSecond - now3);
        if (timeToWait > 0) {
          await new Promise((resolve2) => setTimeout(resolve2, timeToWait));
        }
        const resolve = this.queue.shift();
        if (resolve) {
          this.lastRequestTime = Date.now();
          resolve();
        }
      }
    } finally {
      this.processing = false;
    }
  }
};

// src/search/indexOperations.ts
var import_crypto_js2 = __toESM(require_crypto_js());

// node_modules/@langchain/core/dist/documents/index.js
init_document();

// node_modules/@langchain/core/dist/documents/transformers.js
init_base4();
var BaseDocumentTransformer = class extends Runnable {
  constructor() {
    super(...arguments);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain_core", "documents", "transformers"]
    });
  }
  /**
   * Method to invoke the document transformation. This method calls the
   * transformDocuments method with the provided input.
   * @param input The input documents to be transformed.
   * @param _options Optional configuration object to customize the behavior of callbacks.
   * @returns A Promise that resolves to the transformed documents.
   */
  invoke(input, _options) {
    return this.transformDocuments(input);
  }
};

// node_modules/@langchain/core/utils/tiktoken.js
init_tiktoken();

// node_modules/@langchain/textsplitters/dist/text_splitter.js
var TextSplitter = class extends BaseDocumentTransformer {
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "document_transformers", "text_splitters"]
    });
    Object.defineProperty(this, "chunkSize", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1e3
    });
    Object.defineProperty(this, "chunkOverlap", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 200
    });
    Object.defineProperty(this, "keepSeparator", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "lengthFunction", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.chunkSize = fields?.chunkSize ?? this.chunkSize;
    this.chunkOverlap = fields?.chunkOverlap ?? this.chunkOverlap;
    this.keepSeparator = fields?.keepSeparator ?? this.keepSeparator;
    this.lengthFunction = fields?.lengthFunction ?? ((text) => text.length);
    if (this.chunkOverlap >= this.chunkSize) {
      throw new Error("Cannot have chunkOverlap >= chunkSize");
    }
  }
  async transformDocuments(documents, chunkHeaderOptions = {}) {
    return this.splitDocuments(documents, chunkHeaderOptions);
  }
  splitOnSeparator(text, separator) {
    let splits;
    if (separator) {
      if (this.keepSeparator) {
        const regexEscapedSeparator = separator.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&");
        splits = text.split(new RegExp(`(?=${regexEscapedSeparator})`));
      } else {
        splits = text.split(separator);
      }
    } else {
      splits = text.split("");
    }
    return splits.filter((s4) => s4 !== "");
  }
  async createDocuments(texts, metadatas = [], chunkHeaderOptions = {}) {
    const _metadatas = metadatas.length > 0 ? metadatas : [...Array(texts.length)].map(() => ({}));
    const { chunkHeader = "", chunkOverlapHeader = "(cont'd) ", appendChunkOverlapHeader = false } = chunkHeaderOptions;
    const documents = new Array();
    for (let i3 = 0; i3 < texts.length; i3 += 1) {
      const text = texts[i3];
      let lineCounterIndex = 1;
      let prevChunk = null;
      let indexPrevChunk = -1;
      for (const chunk of await this.splitText(text)) {
        let pageContent = chunkHeader;
        const indexChunk = text.indexOf(chunk, indexPrevChunk + 1);
        if (prevChunk === null) {
          const newLinesBeforeFirstChunk = this.numberOfNewLines(text, 0, indexChunk);
          lineCounterIndex += newLinesBeforeFirstChunk;
        } else {
          const indexEndPrevChunk = indexPrevChunk + await this.lengthFunction(prevChunk);
          if (indexEndPrevChunk < indexChunk) {
            const numberOfIntermediateNewLines = this.numberOfNewLines(text, indexEndPrevChunk, indexChunk);
            lineCounterIndex += numberOfIntermediateNewLines;
          } else if (indexEndPrevChunk > indexChunk) {
            const numberOfIntermediateNewLines = this.numberOfNewLines(text, indexChunk, indexEndPrevChunk);
            lineCounterIndex -= numberOfIntermediateNewLines;
          }
          if (appendChunkOverlapHeader) {
            pageContent += chunkOverlapHeader;
          }
        }
        const newLinesCount = this.numberOfNewLines(chunk);
        const loc = _metadatas[i3].loc && typeof _metadatas[i3].loc === "object" ? { ..._metadatas[i3].loc } : {};
        loc.lines = {
          from: lineCounterIndex,
          to: lineCounterIndex + newLinesCount
        };
        const metadataWithLinesNumber = {
          ..._metadatas[i3],
          loc
        };
        pageContent += chunk;
        documents.push(new Document2({
          pageContent,
          metadata: metadataWithLinesNumber
        }));
        lineCounterIndex += newLinesCount;
        prevChunk = chunk;
        indexPrevChunk = indexChunk;
      }
    }
    return documents;
  }
  numberOfNewLines(text, start, end) {
    const textSection = text.slice(start, end);
    return (textSection.match(/\n/g) || []).length;
  }
  async splitDocuments(documents, chunkHeaderOptions = {}) {
    const selectedDocuments = documents.filter((doc) => doc.pageContent !== void 0);
    const texts = selectedDocuments.map((doc) => doc.pageContent);
    const metadatas = selectedDocuments.map((doc) => doc.metadata);
    return this.createDocuments(texts, metadatas, chunkHeaderOptions);
  }
  joinDocs(docs, separator) {
    const text = docs.join(separator).trim();
    return text === "" ? null : text;
  }
  async mergeSplits(splits, separator) {
    const docs = [];
    const currentDoc = [];
    let total = 0;
    for (const d3 of splits) {
      const _len = await this.lengthFunction(d3);
      if (total + _len + currentDoc.length * separator.length > this.chunkSize) {
        if (total > this.chunkSize) {
          console.warn(`Created a chunk of size ${total}, +
which is longer than the specified ${this.chunkSize}`);
        }
        if (currentDoc.length > 0) {
          const doc2 = this.joinDocs(currentDoc, separator);
          if (doc2 !== null) {
            docs.push(doc2);
          }
          while (total > this.chunkOverlap || total + _len + currentDoc.length * separator.length > this.chunkSize && total > 0) {
            total -= await this.lengthFunction(currentDoc[0]);
            currentDoc.shift();
          }
        }
      }
      currentDoc.push(d3);
      total += _len;
    }
    const doc = this.joinDocs(currentDoc, separator);
    if (doc !== null) {
      docs.push(doc);
    }
    return docs;
  }
};
var RecursiveCharacterTextSplitter = class extends TextSplitter {
  static lc_name() {
    return "RecursiveCharacterTextSplitter";
  }
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "separators", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["\n\n", "\n", " ", ""]
    });
    this.separators = fields?.separators ?? this.separators;
    this.keepSeparator = fields?.keepSeparator ?? true;
  }
  async _splitText(text, separators) {
    const finalChunks = [];
    let separator = separators[separators.length - 1];
    let newSeparators;
    for (let i3 = 0; i3 < separators.length; i3 += 1) {
      const s4 = separators[i3];
      if (s4 === "") {
        separator = s4;
        break;
      }
      if (text.includes(s4)) {
        separator = s4;
        newSeparators = separators.slice(i3 + 1);
        break;
      }
    }
    const splits = this.splitOnSeparator(text, separator);
    let goodSplits = [];
    const _separator = this.keepSeparator ? "" : separator;
    for (const s4 of splits) {
      if (await this.lengthFunction(s4) < this.chunkSize) {
        goodSplits.push(s4);
      } else {
        if (goodSplits.length) {
          const mergedText = await this.mergeSplits(goodSplits, _separator);
          finalChunks.push(...mergedText);
          goodSplits = [];
        }
        if (!newSeparators) {
          finalChunks.push(s4);
        } else {
          const otherInfo = await this._splitText(s4, newSeparators);
          finalChunks.push(...otherInfo);
        }
      }
    }
    if (goodSplits.length) {
      const mergedText = await this.mergeSplits(goodSplits, _separator);
      finalChunks.push(...mergedText);
    }
    return finalChunks;
  }
  async splitText(text) {
    return this._splitText(text, this.separators);
  }
  static fromLanguage(language, options) {
    return new RecursiveCharacterTextSplitter({
      ...options,
      separators: RecursiveCharacterTextSplitter.getSeparatorsForLanguage(language)
    });
  }
  static getSeparatorsForLanguage(language) {
    if (language === "cpp") {
      return [
        // Split along class definitions
        "\nclass ",
        // Split along function definitions
        "\nvoid ",
        "\nint ",
        "\nfloat ",
        "\ndouble ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\nswitch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "go") {
      return [
        // Split along function definitions
        "\nfunc ",
        "\nvar ",
        "\nconst ",
        "\ntype ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nswitch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "java") {
      return [
        // Split along class definitions
        "\nclass ",
        // Split along method definitions
        "\npublic ",
        "\nprotected ",
        "\nprivate ",
        "\nstatic ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\nswitch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "js") {
      return [
        // Split along function definitions
        "\nfunction ",
        "\nconst ",
        "\nlet ",
        "\nvar ",
        "\nclass ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\nswitch ",
        "\ncase ",
        "\ndefault ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "php") {
      return [
        // Split along function definitions
        "\nfunction ",
        // Split along class definitions
        "\nclass ",
        // Split along control flow statements
        "\nif ",
        "\nforeach ",
        "\nwhile ",
        "\ndo ",
        "\nswitch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "proto") {
      return [
        // Split along message definitions
        "\nmessage ",
        // Split along service definitions
        "\nservice ",
        // Split along enum definitions
        "\nenum ",
        // Split along option definitions
        "\noption ",
        // Split along import statements
        "\nimport ",
        // Split along syntax declarations
        "\nsyntax ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "python") {
      return [
        // First, try to split along class definitions
        "\nclass ",
        "\ndef ",
        "\n	def ",
        // Now split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "rst") {
      return [
        // Split along section titles
        "\n===\n",
        "\n---\n",
        "\n***\n",
        // Split along directive markers
        "\n.. ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "ruby") {
      return [
        // Split along method definitions
        "\ndef ",
        "\nclass ",
        // Split along control flow statements
        "\nif ",
        "\nunless ",
        "\nwhile ",
        "\nfor ",
        "\ndo ",
        "\nbegin ",
        "\nrescue ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "rust") {
      return [
        // Split along function definitions
        "\nfn ",
        "\nconst ",
        "\nlet ",
        // Split along control flow statements
        "\nif ",
        "\nwhile ",
        "\nfor ",
        "\nloop ",
        "\nmatch ",
        "\nconst ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "scala") {
      return [
        // Split along class definitions
        "\nclass ",
        "\nobject ",
        // Split along method definitions
        "\ndef ",
        "\nval ",
        "\nvar ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\nmatch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "swift") {
      return [
        // Split along function definitions
        "\nfunc ",
        // Split along class definitions
        "\nclass ",
        "\nstruct ",
        "\nenum ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\ndo ",
        "\nswitch ",
        "\ncase ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "markdown") {
      return [
        // First, try to split along Markdown headings (starting with level 2)
        "\n## ",
        "\n### ",
        "\n#### ",
        "\n##### ",
        "\n###### ",
        // Note the alternative syntax for headings (below) is not handled here
        // Heading level 2
        // ---------------
        // End of code block
        "```\n\n",
        // Horizontal lines
        "\n\n***\n\n",
        "\n\n---\n\n",
        "\n\n___\n\n",
        // Note that this splitter doesn't handle horizontal lines defined
        // by *three or more* of ***, ---, or ___, but this is not handled
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "latex") {
      return [
        // First, try to split along Latex sections
        "\n\\chapter{",
        "\n\\section{",
        "\n\\subsection{",
        "\n\\subsubsection{",
        // Now split by environments
        "\n\\begin{enumerate}",
        "\n\\begin{itemize}",
        "\n\\begin{description}",
        "\n\\begin{list}",
        "\n\\begin{quote}",
        "\n\\begin{quotation}",
        "\n\\begin{verse}",
        "\n\\begin{verbatim}",
        // Now split by math environments
        "\n\\begin{align}",
        "$$",
        "$",
        // Now split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else if (language === "html") {
      return [
        // First, try to split along HTML tags
        "<body>",
        "<div>",
        "<p>",
        "<br>",
        "<li>",
        "<h1>",
        "<h2>",
        "<h3>",
        "<h4>",
        "<h5>",
        "<h6>",
        "<span>",
        "<table>",
        "<tr>",
        "<td>",
        "<th>",
        "<ul>",
        "<ol>",
        "<header>",
        "<footer>",
        "<nav>",
        // Head
        "<head>",
        "<style>",
        "<script>",
        "<meta>",
        "<title>",
        // Normal type of lines
        " ",
        ""
      ];
    } else if (language === "sol") {
      return [
        // Split along compiler informations definitions
        "\npragma ",
        "\nusing ",
        // Split along contract definitions
        "\ncontract ",
        "\ninterface ",
        "\nlibrary ",
        // Split along method definitions
        "\nconstructor ",
        "\ntype ",
        "\nfunction ",
        "\nevent ",
        "\nmodifier ",
        "\nerror ",
        "\nstruct ",
        "\nenum ",
        // Split along control flow statements
        "\nif ",
        "\nfor ",
        "\nwhile ",
        "\ndo while ",
        "\nassembly ",
        // Split by the normal type of lines
        "\n\n",
        "\n",
        " ",
        ""
      ];
    } else {
      throw new Error(`Language ${language} is not supported.`);
    }
  }
};

// src/search/indexOperations.ts
var import_obsidian8 = require("obsidian");
var CHECKPOINT_INTERVAL = 8 * EMBEDDING_BATCH_SIZE;
var IndexOperations = class {
  constructor(app2, dbOps, embeddingsManager) {
    this.app = app2;
    this.dbOps = dbOps;
    this.embeddingsManager = embeddingsManager;
    this.state = {
      isIndexingPaused: false,
      isIndexingCancelled: false,
      indexedCount: 0,
      totalFilesToIndex: 0,
      processedFiles: /* @__PURE__ */ new Set(),
      currentIndexingNotice: null,
      indexNoticeMessage: null
    };
    this.rateLimiter = new RateLimiter(getSettings().embeddingRequestsPerSecond);
    subscribeToSettingsChange(async () => {
      const settings = getSettings();
      this.rateLimiter = new RateLimiter(settings.embeddingRequestsPerSecond);
    });
  }
  async indexVaultToVectorStore(overwrite) {
    let rateLimitNoticeShown = false;
    try {
      const embeddingInstance = await this.embeddingsManager.getEmbeddingsAPI();
      if (!embeddingInstance) {
        console.error("Embedding instance not found.");
        return 0;
      }
      const modelChanged = await this.dbOps.checkAndHandleEmbeddingModelChange(embeddingInstance);
      if (modelChanged) {
        overwrite = true;
      }
      if (overwrite) {
        await this.dbOps.clearIndex(embeddingInstance);
      } else {
        await this.dbOps.garbageCollect();
      }
      const files = await this.getFilesToIndex(overwrite);
      if (files.length === 0) {
        new import_obsidian8.Notice("Copilot vault index is up-to-date.");
        return 0;
      }
      this.initializeIndexingState(files.length);
      this.createIndexingNotice();
      const allChunks = await this.prepareAllChunks(files);
      if (allChunks.length === 0) {
        new import_obsidian8.Notice("No valid content to index.");
        return 0;
      }
      const errors2 = [];
      for (let i3 = 0; i3 < allChunks.length; i3 += EMBEDDING_BATCH_SIZE) {
        if (this.state.isIndexingCancelled)
          break;
        await this.handlePause();
        const batch = allChunks.slice(i3, i3 + EMBEDDING_BATCH_SIZE);
        try {
          await this.rateLimiter.wait();
          const embeddings = await embeddingInstance.embedDocuments(
            batch.map((chunk) => chunk.content)
          );
          for (let j3 = 0; j3 < batch.length; j3++) {
            const chunk = batch[j3];
            await this.dbOps.upsert({
              ...chunk.fileInfo,
              id: this.getDocHash(chunk.content),
              content: chunk.content,
              embedding: embeddings[j3],
              created_at: Date.now(),
              nchars: chunk.content.length
            });
          }
          batch.forEach((chunk) => {
            this.state.processedFiles.add(chunk.fileInfo.path);
          });
          this.state.indexedCount = this.state.processedFiles.size;
          this.updateIndexingNoticeMessage();
          const previousCheckpoint = Math.floor(
            (this.state.indexedCount - batch.length) / CHECKPOINT_INTERVAL
          );
          const currentCheckpoint = Math.floor(this.state.indexedCount / CHECKPOINT_INTERVAL);
          if (currentCheckpoint > previousCheckpoint) {
            await this.dbOps.saveDB();
            console.log("Copilot index checkpoint save completed.");
          }
        } catch (err) {
          console.error("Batch processing error:", {
            error: err,
            batchSize: batch?.length || 0,
            firstChunk: batch?.[0] ? {
              path: batch[0].fileInfo?.path,
              contentLength: batch[0].content?.length,
              hasFileInfo: !!batch[0].fileInfo
            } : "No chunks in batch",
            errorType: err?.constructor?.name,
            errorMessage: err?.message
          });
          this.handleIndexingError(err, batch?.[0]?.fileInfo?.path, errors2, rateLimitNoticeShown);
          if (this.isRateLimitError(err)) {
            rateLimitNoticeShown = true;
            break;
          }
        }
      }
      this.finalizeIndexing(errors2);
      await this.dbOps.saveDB();
      console.log("Copilot index final save completed.");
      return this.state.indexedCount;
    } catch (error) {
      this.handleFatalError(error);
      return 0;
    }
  }
  async prepareAllChunks(files) {
    const embeddingInstance = await this.embeddingsManager.getEmbeddingsAPI();
    if (!embeddingInstance) {
      console.error("Embedding instance not found.");
      return [];
    }
    const embeddingModel = EmbeddingManager.getModelName(embeddingInstance);
    const textSplitter = RecursiveCharacterTextSplitter.fromLanguage("markdown", {
      chunkSize: CHUNK_SIZE
    });
    const allChunks = [];
    for (const file of files) {
      const content = await this.app.vault.cachedRead(file);
      if (!content?.trim())
        continue;
      const fileCache = this.app.metadataCache.getFileCache(file);
      const fileInfo = {
        title: file.basename,
        path: file.path,
        embeddingModel,
        ctime: file.stat.ctime,
        mtime: file.stat.mtime,
        tags: fileCache?.tags?.map((tag) => tag.tag) ?? [],
        extension: file.extension,
        metadata: {
          ...fileCache?.frontmatter ?? {},
          created: formatDateTime(new Date(file.stat.ctime)).display,
          modified: formatDateTime(new Date(file.stat.mtime)).display
        }
      };
      const chunks = await textSplitter.createDocuments([content], [], {
        chunkHeader: `

NOTE TITLE: [[${fileInfo.title}]]

METADATA:${JSON.stringify(
          fileInfo.metadata
        )}

NOTE BLOCK CONTENT:

`,
        appendChunkOverlapHeader: true
      });
      chunks.forEach((chunk) => {
        if (chunk.pageContent.trim()) {
          allChunks.push({
            content: chunk.pageContent,
            fileInfo
          });
        }
      });
    }
    return allChunks;
  }
  getDocHash(sourceDocument) {
    return (0, import_crypto_js2.MD5)(sourceDocument).toString();
  }
  async getFilesToIndex(overwrite) {
    const { inclusions, exclusions } = getMatchingPatterns();
    const allMarkdownFiles = this.app.vault.getMarkdownFiles();
    if (overwrite) {
      return allMarkdownFiles.filter((file) => {
        return shouldIndexFile(file, inclusions, exclusions);
      });
    }
    const indexedFilePaths = new Set(await this.dbOps.getIndexedFiles());
    const latestMtime = await this.dbOps.getLatestFileMtime();
    const filesToIndex = /* @__PURE__ */ new Set();
    const emptyFiles = /* @__PURE__ */ new Set();
    for (const file of allMarkdownFiles) {
      if (!shouldIndexFile(file, inclusions, exclusions)) {
        continue;
      }
      const content = await this.app.vault.cachedRead(file);
      if (!content || content.trim().length === 0) {
        emptyFiles.add(file.path);
        continue;
      }
      const isIndexed = indexedFilePaths.has(file.path);
      if (!isIndexed || file.stat.mtime > latestMtime) {
        filesToIndex.add(file);
      }
    }
    if (getSettings().debug) {
      console.log(`Files to index: ${filesToIndex.size}`);
      console.log(`Previously indexed: ${indexedFilePaths.size}`);
      console.log(`Empty files skipped: ${emptyFiles.size}`);
    }
    return Array.from(filesToIndex);
  }
  initializeIndexingState(totalFiles) {
    this.state = {
      isIndexingPaused: false,
      isIndexingCancelled: false,
      indexedCount: 0,
      totalFilesToIndex: totalFiles,
      processedFiles: /* @__PURE__ */ new Set(),
      currentIndexingNotice: null,
      indexNoticeMessage: null
    };
  }
  createIndexingNotice() {
    const frag = document.createDocumentFragment();
    const container = frag.createEl("div", { cls: "copilot-notice-container" });
    this.state.indexNoticeMessage = container.createEl("div", { cls: "copilot-notice-message" });
    this.updateIndexingNoticeMessage();
    const buttonContainer = container.createEl("div", { cls: "copilot-notice-buttons" });
    const pauseButton = buttonContainer.createEl("button");
    pauseButton.textContent = "Pause";
    pauseButton.addEventListener("click", (event) => {
      event.stopPropagation();
      event.preventDefault();
      if (this.state.isIndexingPaused) {
        this.resumeIndexing();
        pauseButton.textContent = "Pause";
      } else {
        this.pauseIndexing();
        pauseButton.textContent = "Resume";
      }
    });
    const stopButton = buttonContainer.createEl("button");
    stopButton.textContent = "Stop";
    stopButton.style.marginLeft = "8px";
    stopButton.addEventListener("click", (event) => {
      event.stopPropagation();
      event.preventDefault();
      this.cancelIndexing();
    });
    frag.appendChild(this.state.indexNoticeMessage);
    frag.appendChild(buttonContainer);
    this.state.currentIndexingNotice = new import_obsidian8.Notice(frag, 0);
    return this.state.currentIndexingNotice;
  }
  async handlePause() {
    if (this.state.isIndexingPaused) {
      while (this.state.isIndexingPaused && !this.state.isIndexingCancelled) {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
      if (!this.state.isIndexingCancelled) {
        const files = await this.getFilesToIndex();
        if (files.length === 0) {
          console.log("No files to index after filter change, stopping indexing");
          this.cancelIndexing();
          new import_obsidian8.Notice("No files to index with current filters");
          return;
        }
        this.state.totalFilesToIndex = files.length;
        console.log("Total files to index:", this.state.totalFilesToIndex);
        console.log("Files to index:", files);
        this.updateIndexingNoticeMessage();
      }
    }
  }
  pauseIndexing() {
    this.state.isIndexingPaused = true;
  }
  resumeIndexing() {
    this.state.isIndexingPaused = false;
  }
  updateIndexingNoticeMessage() {
    if (this.state.indexNoticeMessage) {
      const status = this.state.isIndexingPaused ? " (Paused)" : "";
      const settings = getSettings();
      const folders = extractAppIgnoreSettings(this.app);
      const inclusions = settings.qaInclusions ? `Inclusions: ${settings.qaInclusions}` : "Inclusions: None";
      const exclusions = folders.length > 0 || settings.qaExclusions ? `Exclusions: ${folders.join(", ")}${folders.length ? ", " : ""}${settings.qaExclusions || "None"}` : "Exclusions: None";
      this.state.indexNoticeMessage.textContent = `Copilot is indexing your vault...
${this.state.indexedCount}/${this.state.totalFilesToIndex} files processed${status}
${exclusions}
${inclusions}`;
    }
  }
  handleIndexingError(err, filePath, errors2, rateLimitNoticeShown) {
    console.error(`Error indexing file ${filePath || "unknown"}:`, err);
    errors2.push(filePath || "unknown");
    if (!rateLimitNoticeShown) {
      new import_obsidian8.Notice(`Error indexing file ${filePath || "unknown"}. Check console for details.`);
    }
  }
  isRateLimitError(err) {
    return err?.message?.includes?.("rate limit") || false;
  }
  finalizeIndexing(errors2) {
    if (this.state.currentIndexingNotice) {
      this.state.currentIndexingNotice.hide();
    }
    if (this.state.isIndexingCancelled) {
      new import_obsidian8.Notice(`Indexing cancelled`);
      return;
    }
    if (errors2.length > 0) {
      new import_obsidian8.Notice(`Indexing completed with ${errors2.length} errors. Check console for details.`);
    } else {
      new import_obsidian8.Notice("Indexing completed successfully!");
    }
  }
  handleFatalError(error) {
    console.error("Fatal error during indexing:", error);
    if (this.state.currentIndexingNotice) {
      this.state.currentIndexingNotice.hide();
    }
    new import_obsidian8.Notice("Fatal error during indexing. Check console for details.");
  }
  async reindexFile(file) {
    try {
      const embeddingInstance = await this.embeddingsManager.getEmbeddingsAPI();
      if (!embeddingInstance) {
        return;
      }
      await this.dbOps.removeDocs(file.path);
      const modelChanged = await this.dbOps.checkAndHandleEmbeddingModelChange(embeddingInstance);
      if (modelChanged) {
        await this.indexVaultToVectorStore(true);
        return;
      }
      const chunks = await this.prepareAllChunks([file]);
      if (chunks.length === 0)
        return;
      const embeddings = await embeddingInstance.embedDocuments(
        chunks.map((chunk) => chunk.content)
      );
      for (let i3 = 0; i3 < chunks.length; i3++) {
        const chunk = chunks[i3];
        await this.dbOps.upsert({
          ...chunk.fileInfo,
          id: this.getDocHash(chunk.content),
          content: chunk.content,
          embedding: embeddings[i3],
          created_at: Date.now(),
          nchars: chunk.content.length
        });
      }
      this.dbOps.markUnsavedChanges();
      if (getSettings().debug) {
        console.log(`Reindexed file: ${file.path}`);
      }
    } catch (error) {
      console.error(`Error reindexing file ${file.path}:`, error);
    }
  }
  async cancelIndexing() {
    console.log("Indexing cancelled by user");
    this.state.isIndexingCancelled = true;
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (this.state.currentIndexingNotice) {
      this.state.currentIndexingNotice.hide();
    }
  }
};

// src/search/vectorStoreManager.ts
var VectorStoreManager = class {
  constructor() {
    this.embeddingsManager = EmbeddingManager.getInstance();
    this.dbOps = new DBOperations(app);
    this.indexOps = new IndexOperations(app, this.dbOps, this.embeddingsManager);
    this.eventHandler = new IndexEventHandler(app, this.indexOps, this.dbOps);
    this.initializationPromise = this.initialize();
    this.setupSettingsSubscription();
  }
  static getInstance() {
    if (!VectorStoreManager.instance) {
      VectorStoreManager.instance = new VectorStoreManager();
    }
    return VectorStoreManager.instance;
  }
  setupSettingsSubscription() {
    this.lastKnownSettings = { ...getSettings() };
    const reinitialize = async () => {
      const settings = getSettings();
      const prevSettings = this.lastKnownSettings;
      this.lastKnownSettings = { ...settings };
      if (settings.enableIndexSync !== prevSettings?.enableIndexSync) {
        const newPath = await this.dbOps.getDbPath();
        const oldPath = this.dbOps.getCurrentDbPath();
        if (oldPath !== newPath) {
          await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI());
        }
      }
    };
    subscribeToSettingsChange(() => {
      this.initializationPromise = reinitialize();
    });
  }
  async initialize() {
    try {
      let retries = 3;
      while (retries > 0) {
        try {
          await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI());
          break;
        } catch (error) {
          if (error instanceof CustomError && error.message.includes("Vault adapter not available")) {
            retries--;
            if (retries > 0) {
              await new Promise((resolve) => setTimeout(resolve, 100));
              continue;
            }
          }
          new import_obsidian9.Notice(
            "Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."
          );
          console.error("Failed to initialize vector store:", error);
          break;
        }
      }
    } catch (error) {
      console.error("Failed to initialize vector store:", error);
    }
  }
  async waitForInitialization() {
    await this.initializationPromise;
  }
  async indexVaultToVectorStore(overwrite) {
    await this.waitForInitialization();
    if (import_obsidian9.Platform.isMobile && getSettings().disableIndexOnMobile) {
      new import_obsidian9.Notice("Indexing is disabled on mobile devices");
      return 0;
    }
    return this.indexOps.indexVaultToVectorStore(overwrite);
  }
  async clearIndex() {
    await this.waitForInitialization();
    await this.dbOps.clearIndex(await this.embeddingsManager.getEmbeddingsAPI());
  }
  async garbageCollectVectorStore() {
    await this.waitForInitialization();
    return this.dbOps.garbageCollect();
  }
  async getIndexedFiles() {
    await this.waitForInitialization();
    return this.dbOps.getIndexedFiles();
  }
  async isIndexEmpty() {
    await this.waitForInitialization();
    return this.dbOps.isIndexEmpty();
  }
  async hasIndex(notePath) {
    await this.waitForInitialization();
    return this.dbOps.hasIndex(notePath);
  }
  onunload() {
    this.eventHandler.cleanup();
    this.dbOps.onunload();
  }
  async getDbOps() {
    await this.waitForInitialization();
    return this.dbOps;
  }
  async getDb() {
    await this.waitForInitialization();
    const db = this.dbOps.getDb();
    if (!db) {
      throw new Error("Database is not loaded. Please restart the plugin.");
    }
    return db;
  }
  async reindexFile(file) {
    await this.waitForInitialization();
    await this.indexOps.reindexFile(file);
  }
};

// src/plusUtils.ts
var DEFAULT_COPILOT_PLUS_CHAT_MODEL = "copilot-plus-flash" /* COPILOT_PLUS_FLASH */;
var DEFAULT_COPILOT_PLUS_CHAT_MODEL_KEY = DEFAULT_COPILOT_PLUS_CHAT_MODEL + "|" + "copilot-plus" /* COPILOT_PLUS */;
var DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL = "copilot-plus-small" /* COPILOT_PLUS_SMALL */;
var DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL_KEY = DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL + "|" + "copilot-plus" /* COPILOT_PLUS */;
function isPlusModel(modelKey) {
  return modelKey.split("|")[1] === "copilot-plus" /* COPILOT_PLUS */;
}
function useIsPlusUser() {
  const settings = useSettingsValue();
  return settings.isPlusUser;
}
async function checkIsPlusUser() {
  if (!getSettings().plusLicenseKey) {
    turnOffPlus();
    return false;
  }
  const brevilabsClient = BrevilabsClient.getInstance();
  return await brevilabsClient.validateLicenseKey();
}
function applyPlusSettings() {
  const defaultModelKey = DEFAULT_COPILOT_PLUS_CHAT_MODEL_KEY;
  const embeddingModelKey = DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL_KEY;
  const previousEmbeddingModelKey = getSettings().embeddingModelKey;
  setModelKey(defaultModelKey);
  setChainType("copilot_plus" /* COPILOT_PLUS_CHAIN */);
  setSettings({
    defaultModelKey,
    embeddingModelKey,
    defaultChainType: "copilot_plus" /* COPILOT_PLUS_CHAIN */
  });
  if (previousEmbeddingModelKey !== embeddingModelKey) {
    VectorStoreManager.getInstance().indexVaultToVectorStore(true);
  }
}
function createPlusPageUrl(medium) {
  return `https://www.obsidiancopilot.com?utm_source=obsidian&utm_medium=${medium}`;
}
function navigateToPlusPage(medium) {
  window.open(createPlusPageUrl(medium), "_blank");
}
function turnOnPlus() {
  updateSetting("isPlusUser", true);
}
function turnOffPlus() {
  const previousIsPlusUser = getSettings().isPlusUser;
  updateSetting("isPlusUser", false);
  if (previousIsPlusUser) {
    new CopilotPlusExpiredModal(app).open();
  }
}

// src/LLMProviders/brevilabsClient.ts
var import_obsidian10 = require("obsidian");
var BrevilabsClient = class {
  constructor() {
    this.pluginVersion = "Unknown";
  }
  static getInstance() {
    if (!BrevilabsClient.instance) {
      BrevilabsClient.instance = new BrevilabsClient();
    }
    return BrevilabsClient.instance;
  }
  checkLicenseKey() {
    if (!getSettings().plusLicenseKey) {
      new import_obsidian10.Notice(
        "Copilot Plus license key not found. Please enter your license key in the settings."
      );
      throw new Error("License key not initialized");
    }
  }
  setPluginVersion(pluginVersion) {
    this.pluginVersion = pluginVersion;
  }
  async makeRequest(endpoint, body, method = "POST", excludeAuthHeader = false) {
    this.checkLicenseKey();
    const url = new URL(`${BREVILABS_API_BASE_URL}${endpoint}`);
    if (method === "GET") {
      Object.entries(body).forEach(([key, value]) => {
        url.searchParams.append(key, value);
      });
    }
    const response = await safeFetch(url.toString(), {
      method,
      headers: {
        "Content-Type": "application/json",
        ...!excludeAuthHeader && {
          Authorization: `Bearer ${await getDecryptedKey(getSettings().plusLicenseKey)}`
        },
        "X-Client-Version": this.pluginVersion
      },
      ...method === "POST" && { body: JSON.stringify(body) }
    });
    const data = await response.json();
    if (getSettings().debug) {
      console.log(`==== ${endpoint} request ====:`, data);
    }
    return data;
  }
  async makeRequestWithCustomBaseUrl(baseUrl, endpoint, body, method = "POST") {
    this.checkLicenseKey();
    const url = new URL(`${baseUrl}${endpoint}`);
    if (method === "GET") {
      Object.entries(body).forEach(([key, value]) => {
        url.searchParams.append(key, value);
      });
    }
    const response = await safeFetch(url.toString(), {
      method,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${await getDecryptedKey(getSettings().plusLicenseKey)}`,
        "X-Client-Version": this.pluginVersion
      },
      ...method === "POST" && { body: JSON.stringify(body) }
    });
    const data = await response.json();
    if (getSettings().debug) {
      console.log(`==== ${endpoint} request ====:`, data);
    }
    return data;
  }
  /**
   * Validate the license key and update the isPlusUser setting.
   * @returns true if the license key is valid, false if the license key is invalid, and undefined if
   * unknown error.
   */
  async validateLicenseKey() {
    try {
      logInfo("settings value", getSettings().plusLicenseKey);
      await this.makeRequest(
        "/license",
        {
          license_key: await getDecryptedKey(getSettings().plusLicenseKey)
        },
        "POST",
        true
      );
      turnOnPlus();
      return true;
    } catch (error) {
      if (extractErrorDetail(error).reason === "Invalid license key") {
        logInfo("validateLicenseKey: false");
        turnOffPlus();
        return false;
      }
      return;
    }
  }
  async broca(userMessage) {
    const brocaResponse = await this.makeRequest("/broca", {
      message: userMessage
    });
    return brocaResponse;
  }
  async rerank(query, documents) {
    return this.makeRequest("/rerank", {
      query,
      documents,
      model: "rerank-2"
    });
  }
  async url4llm(url) {
    return this.makeRequest("/url4llm", { url });
  }
  async pdf4llm(binaryContent) {
    const base64Content = Buffer.from(binaryContent).toString("base64");
    return this.makeRequest("/pdf4llm", {
      pdf: base64Content
    });
  }
  async webSearch(query) {
    return this.makeRequest("/websearch", { query });
  }
  async youtube4llm(url) {
    try {
      return await this.makeRequest("/youtube4llm", { url });
    } catch (error) {
      const response = error instanceof Response ? await error.json() : null;
      if (!response?.response?.transcript) {
        const stagingUrl = "https://brevilabs-api-staging.up.railway.app/v1";
        return await this.makeRequestWithCustomBaseUrl(
          stagingUrl,
          "/youtube4llm",
          { url }
        );
      }
      throw error;
    }
  }
};

// node_modules/@anthropic-ai/sdk/error.mjs
var error_exports2 = {};
__export(error_exports2, {
  APIConnectionError: () => APIConnectionError2,
  APIConnectionTimeoutError: () => APIConnectionTimeoutError2,
  APIError: () => APIError2,
  APIUserAbortError: () => APIUserAbortError2,
  AnthropicError: () => AnthropicError,
  AuthenticationError: () => AuthenticationError2,
  BadRequestError: () => BadRequestError2,
  ConflictError: () => ConflictError2,
  InternalServerError: () => InternalServerError2,
  NotFoundError: () => NotFoundError2,
  PermissionDeniedError: () => PermissionDeniedError2,
  RateLimitError: () => RateLimitError2,
  UnprocessableEntityError: () => UnprocessableEntityError2
});

// node_modules/@anthropic-ai/sdk/version.mjs
var VERSION2 = "0.27.3";

// node_modules/@anthropic-ai/sdk/_shims/registry.mjs
var auto2 = false;
var kind2 = void 0;
var fetch4 = void 0;
var Request4 = void 0;
var Response4 = void 0;
var Headers4 = void 0;
var FormData3 = void 0;
var Blob3 = void 0;
var File3 = void 0;
var ReadableStream3 = void 0;
var getMultipartRequestOptions2 = void 0;
var getDefaultAgent2 = void 0;
var fileFromPath2 = void 0;
var isFsReadStream2 = void 0;
function setShims2(shims, options = { auto: false }) {
  if (auto2) {
    throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
  }
  if (kind2) {
    throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${kind2}'\``);
  }
  auto2 = options.auto;
  kind2 = shims.kind;
  fetch4 = shims.fetch;
  Request4 = shims.Request;
  Response4 = shims.Response;
  Headers4 = shims.Headers;
  FormData3 = shims.FormData;
  Blob3 = shims.Blob;
  File3 = shims.File;
  ReadableStream3 = shims.ReadableStream;
  getMultipartRequestOptions2 = shims.getMultipartRequestOptions;
  getDefaultAgent2 = shims.getDefaultAgent;
  fileFromPath2 = shims.fileFromPath;
  isFsReadStream2 = shims.isFsReadStream;
}

// node_modules/@anthropic-ai/sdk/_shims/MultipartBody.mjs
var MultipartBody2 = class {
  constructor(body) {
    this.body = body;
  }
  get [Symbol.toStringTag]() {
    return "MultipartBody";
  }
};

// node_modules/@anthropic-ai/sdk/_shims/web-runtime.mjs
function getRuntime2({ manuallyImported } = {}) {
  const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from '@anthropic-ai/sdk'\`:
- \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node)
- \`import '@anthropic-ai/sdk/shims/web'\` (otherwise)
`;
  let _fetch, _Request, _Response, _Headers;
  try {
    _fetch = fetch;
    _Request = Request;
    _Response = Response;
    _Headers = Headers;
  } catch (error) {
    throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
  }
  return {
    kind: "web",
    fetch: _fetch,
    Request: _Request,
    Response: _Response,
    Headers: _Headers,
    FormData: (
      // @ts-ignore
      typeof FormData !== "undefined" ? FormData : class FormData {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
        }
      }
    ),
    Blob: typeof Blob !== "undefined" ? Blob : class Blob {
      constructor() {
        throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
      }
    },
    File: (
      // @ts-ignore
      typeof File !== "undefined" ? File : class File {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
        }
      }
    ),
    ReadableStream: (
      // @ts-ignore
      typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream {
        // @ts-ignore
        constructor() {
          throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
        }
      }
    ),
    getMultipartRequestOptions: async (form, opts) => ({
      ...opts,
      body: new MultipartBody2(form)
    }),
    getDefaultAgent: (url) => void 0,
    fileFromPath: () => {
      throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads");
    },
    isFsReadStream: (value) => false
  };
}

// node_modules/@anthropic-ai/sdk/_shims/index.mjs
if (!kind2)
  setShims2(getRuntime2(), { auto: true });

// node_modules/@anthropic-ai/sdk/streaming.mjs
var Stream2 = class {
  constructor(iterator, controller) {
    this.iterator = iterator;
    this.controller = controller;
  }
  static fromSSEResponse(response, controller) {
    let consumed2 = false;
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const sse of _iterSSEMessages2(response, controller)) {
          if (sse.event === "completion") {
            try {
              yield JSON.parse(sse.data);
            } catch (e3) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e3;
            }
          }
          if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") {
            try {
              yield JSON.parse(sse.data);
            } catch (e3) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e3;
            }
          }
          if (sse.event === "ping") {
            continue;
          }
          if (sse.event === "error") {
            throw APIError2.generate(void 0, `SSE Error: ${sse.data}`, sse.data, createResponseHeaders2(response.headers));
          }
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream2(iterator, controller);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller) {
    let consumed2 = false;
    async function* iterLines() {
      const lineDecoder = new LineDecoder2();
      const iter = readableStreamAsyncIterable2(readableStream);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          yield line;
        }
      }
      for (const line of lineDecoder.flush()) {
        yield line;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const line of iterLines()) {
          if (done)
            continue;
          if (line)
            yield JSON.parse(line);
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream2(iterator, controller);
  }
  [Symbol.asyncIterator]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue2) => {
      return {
        next: () => {
          if (queue2.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue2.shift();
        }
      };
    };
    return [
      new Stream2(() => teeIterator(left), this.controller),
      new Stream2(() => teeIterator(right), this.controller)
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    const encoder = new TextEncoder();
    return new ReadableStream3({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encoder.encode(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        await iter.return?.();
      }
    });
  }
};
async function* _iterSSEMessages2(response, controller) {
  if (!response.body) {
    controller.abort();
    throw new AnthropicError(`Attempted to iterate over a response with no body`);
  }
  const sseDecoder = new SSEDecoder2();
  const lineDecoder = new LineDecoder2();
  const iter = readableStreamAsyncIterable2(response.body);
  for await (const sseChunk of iterSSEChunks2(iter)) {
    for (const line of lineDecoder.decode(sseChunk)) {
      const sse = sseDecoder.decode(line);
      if (sse)
        yield sse;
    }
  }
  for (const line of lineDecoder.flush()) {
    const sse = sseDecoder.decode(line);
    if (sse)
      yield sse;
  }
}
async function* iterSSEChunks2(iterator) {
  let data = new Uint8Array();
  for await (const chunk of iterator) {
    if (chunk == null) {
      continue;
    }
    const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
    let newData = new Uint8Array(data.length + binaryChunk.length);
    newData.set(data);
    newData.set(binaryChunk, data.length);
    data = newData;
    let patternIndex;
    while ((patternIndex = findDoubleNewlineIndex2(data)) !== -1) {
      yield data.slice(0, patternIndex);
      data = data.slice(patternIndex);
    }
  }
  if (data.length > 0) {
    yield data;
  }
}
function findDoubleNewlineIndex2(buffer) {
  const newline = 10;
  const carriage = 13;
  for (let i3 = 0; i3 < buffer.length - 2; i3++) {
    if (buffer[i3] === newline && buffer[i3 + 1] === newline) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === carriage) {
      return i3 + 2;
    }
    if (buffer[i3] === carriage && buffer[i3 + 1] === newline && i3 + 3 < buffer.length && buffer[i3 + 2] === carriage && buffer[i3 + 3] === newline) {
      return i3 + 4;
    }
  }
  return -1;
}
var SSEDecoder2 = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _2, value] = partition3(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
var LineDecoder2 = class {
  constructor() {
    this.buffer = [];
    this.trailingCR = false;
  }
  decode(chunk) {
    let text = this.decodeText(chunk);
    if (this.trailingCR) {
      text = "\r" + text;
      this.trailingCR = false;
    }
    if (text.endsWith("\r")) {
      this.trailingCR = true;
      text = text.slice(0, -1);
    }
    if (!text) {
      return [];
    }
    const trailingNewline = LineDecoder2.NEWLINE_CHARS.has(text[text.length - 1] || "");
    let lines = text.split(LineDecoder2.NEWLINE_REGEXP);
    if (trailingNewline) {
      lines.pop();
    }
    if (lines.length === 1 && !trailingNewline) {
      this.buffer.push(lines[0]);
      return [];
    }
    if (this.buffer.length > 0) {
      lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
      this.buffer = [];
    }
    if (!trailingNewline) {
      this.buffer = [lines.pop() || ""];
    }
    return lines;
  }
  decodeText(bytes) {
    if (bytes == null)
      return "";
    if (typeof bytes === "string")
      return bytes;
    if (typeof Buffer !== "undefined") {
      if (bytes instanceof Buffer) {
        return bytes.toString();
      }
      if (bytes instanceof Uint8Array) {
        return Buffer.from(bytes).toString();
      }
      throw new AnthropicError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
    }
    if (typeof TextDecoder !== "undefined") {
      if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
        this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
        return this.textDecoder.decode(bytes);
      }
      throw new AnthropicError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
    }
    throw new AnthropicError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
  }
  flush() {
    if (!this.buffer.length && !this.trailingCR) {
      return [];
    }
    const lines = [this.buffer.join("")];
    this.buffer = [];
    this.trailingCR = false;
    return lines;
  }
};
LineDecoder2.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function partition3(str2, delimiter) {
  const index2 = str2.indexOf(delimiter);
  if (index2 !== -1) {
    return [str2.substring(0, index2), delimiter, str2.substring(index2 + delimiter.length)];
  }
  return [str2, "", ""];
}
function readableStreamAsyncIterable2(stream) {
  if (stream[Symbol.asyncIterator])
    return stream;
  const reader = stream.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e3) {
        reader.releaseLock();
        throw e3;
      }
    },
    async return() {
      const cancelPromise2 = reader.cancel();
      reader.releaseLock();
      await cancelPromise2;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}

// node_modules/@anthropic-ai/sdk/uploads.mjs
var isResponseLike2 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
var isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value);
var isBlobLike2 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
async function toFile2(value, name, options) {
  value = await value;
  if (isFileLike2(value)) {
    return value;
  }
  if (isResponseLike2(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
    const data = isBlobLike2(blob) ? [await blob.arrayBuffer()] : [blob];
    return new File3(data, name, options);
  }
  const bits = await getBytes2(value);
  name || (name = getName2(value) ?? "unknown_file");
  if (!options?.type) {
    const type = bits[0]?.type;
    if (typeof type === "string") {
      options = { ...options, type };
    }
  }
  return new File3(bits, name, options);
}
async function getBytes2(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike2(value)) {
    parts.push(await value.arrayBuffer());
  } else if (isAsyncIterableIterator2(value)) {
    for await (const chunk of value) {
      parts.push(chunk);
    }
  } else {
    throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError2(value)}`);
  }
  return parts;
}
function propsForError2(value) {
  const props = Object.getOwnPropertyNames(value);
  return `[${props.map((p3) => `"${p3}"`).join(", ")}]`;
}
function getName2(value) {
  return getStringFromMaybeBuffer2(value.name) || getStringFromMaybeBuffer2(value.filename) || // For fs.ReadStream
  getStringFromMaybeBuffer2(value.path)?.split(/[\\/]/).pop();
}
var getStringFromMaybeBuffer2 = (x2) => {
  if (typeof x2 === "string")
    return x2;
  if (typeof Buffer !== "undefined" && x2 instanceof Buffer)
    return String(x2);
  return void 0;
};
var isAsyncIterableIterator2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var isMultipartBody2 = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody";

// node_modules/@anthropic-ai/sdk/core.mjs
var __classPrivateFieldSet10 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet11 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _AbstractPage_client2;
async function defaultParseResponse2(props) {
  const { response } = props;
  if (props.options.stream) {
    debug2("response", response.status, response.url, response.headers, response.body);
    if (props.options.__streamClass) {
      return props.options.__streamClass.fromSSEResponse(response, props.controller);
    }
    return Stream2.fromSSEResponse(response, props.controller);
  }
  if (response.status === 204) {
    return null;
  }
  if (props.options.__binaryResponse) {
    return response;
  }
  const contentType = response.headers.get("content-type");
  const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
  if (isJSON) {
    const json = await response.json();
    debug2("response", response.status, response.url, response.headers, json);
    return json;
  }
  const text = await response.text();
  debug2("response", response.status, response.url, response.headers, text);
  return text;
}
var APIPromise2 = class extends Promise {
  constructor(responsePromise, parseResponse = defaultParseResponse2) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse;
  }
  _thenUnwrap(transform) {
    return new APIPromise2(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
   * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
   * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
   */
  asResponse() {
    return this.responsePromise.then((p3) => p3.response);
  }
  /**
   * Gets the parsed response data and the raw `Response` instance.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from '@anthropic-ai/sdk'`:
   * - `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)
   * - `import '@anthropic-ai/sdk/shims/web'` (otherwise)
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then(this.parseResponse);
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
var APIClient2 = class {
  constructor({
    baseURL,
    maxRetries = 2,
    timeout = 6e5,
    // 10 minutes
    httpAgent,
    fetch: overridenFetch
  }) {
    this.baseURL = baseURL;
    this.maxRetries = validatePositiveInteger2("maxRetries", maxRetries);
    this.timeout = validatePositiveInteger2("timeout", timeout);
    this.httpAgent = httpAgent;
    this.fetch = overridenFetch ?? fetch4;
  }
  authHeaders(opts) {
    return {};
  }
  /**
   * Override this to add your own default headers, for example:
   *
   *  {
   *    ...super.defaultHeaders(),
   *    Authorization: 'Bearer 123',
   *  }
   */
  defaultHeaders(opts) {
    return {
      Accept: "application/json",
      "Content-Type": "application/json",
      "User-Agent": this.getUserAgent(),
      ...getPlatformHeaders2(),
      ...this.authHeaders(opts)
    };
  }
  /**
   * Override this to add your own headers validation:
   */
  validateHeaders(headers, customHeaders) {
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid42()}`;
  }
  get(path, opts) {
    return this.methodRequest("get", path, opts);
  }
  post(path, opts) {
    return this.methodRequest("post", path, opts);
  }
  patch(path, opts) {
    return this.methodRequest("patch", path, opts);
  }
  put(path, opts) {
    return this.methodRequest("put", path, opts);
  }
  delete(path, opts) {
    return this.methodRequest("delete", path, opts);
  }
  methodRequest(method, path, opts) {
    return this.request(Promise.resolve(opts).then(async (opts2) => {
      const body = opts2 && isBlobLike2(opts2?.body) ? new DataView(await opts2.body.arrayBuffer()) : opts2?.body instanceof DataView ? opts2.body : opts2?.body instanceof ArrayBuffer ? new DataView(opts2.body) : opts2 && ArrayBuffer.isView(opts2?.body) ? new DataView(opts2.body.buffer) : opts2?.body;
      return { method, path, ...opts2, body };
    }));
  }
  getAPIList(path, Page2, opts) {
    return this.requestAPIList(Page2, { method: "get", path, ...opts });
  }
  calculateContentLength(body) {
    if (typeof body === "string") {
      if (typeof Buffer !== "undefined") {
        return Buffer.byteLength(body, "utf8").toString();
      }
      if (typeof TextEncoder !== "undefined") {
        const encoder = new TextEncoder();
        const encoded = encoder.encode(body);
        return encoded.length.toString();
      }
    } else if (ArrayBuffer.isView(body)) {
      return body.byteLength.toString();
    }
    return null;
  }
  buildRequest(options) {
    const { method, path, query, headers = {} } = options;
    const body = ArrayBuffer.isView(options.body) || options.__binaryRequest && typeof options.body === "string" ? options.body : isMultipartBody2(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null;
    const contentLength = this.calculateContentLength(body);
    const url = this.buildURL(path, query);
    if ("timeout" in options)
      validatePositiveInteger2("timeout", options.timeout);
    const timeout = options.timeout ?? this.timeout;
    const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent2(url);
    const minAgentTimeout = timeout + 1e3;
    if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
      httpAgent.options.timeout = minAgentTimeout;
    }
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      headers[this.idempotencyHeader] = options.idempotencyKey;
    }
    const reqHeaders = this.buildHeaders({ options, headers, contentLength });
    const req = {
      method,
      ...body && { body },
      headers: reqHeaders,
      ...httpAgent && { agent: httpAgent },
      // @ts-ignore node-fetch uses a custom AbortSignal type that is
      // not compatible with standard web types
      signal: options.signal ?? null
    };
    return { req, url, timeout };
  }
  buildHeaders({ options, headers, contentLength }) {
    const reqHeaders = {};
    if (contentLength) {
      reqHeaders["content-length"] = contentLength;
    }
    const defaultHeaders = this.defaultHeaders(options);
    applyHeadersMut2(reqHeaders, defaultHeaders);
    applyHeadersMut2(reqHeaders, headers);
    if (isMultipartBody2(options.body) && kind2 !== "node") {
      delete reqHeaders["content-type"];
    }
    this.validateHeaders(reqHeaders, headers);
    return reqHeaders;
  }
  /**
   * Used as a callback for mutating the given `FinalRequestOptions` object.
   */
  async prepareOptions(options) {
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  parseHeaders(headers) {
    return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
  }
  makeStatusError(status, error, message, headers) {
    return APIError2.generate(status, error, message, headers);
  }
  request(options, remainingRetries = null) {
    return new APIPromise2(this.makeRequest(options, remainingRetries));
  }
  async makeRequest(optionsInput, retriesRemaining) {
    const options = await optionsInput;
    if (retriesRemaining == null) {
      retriesRemaining = options.maxRetries ?? this.maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = this.buildRequest(options);
    await this.prepareRequest(req, { url, options });
    debug2("request", url, options, req.headers);
    if (options.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2);
    if (response instanceof Error) {
      if (options.signal?.aborted) {
        throw new APIUserAbortError2();
      }
      if (retriesRemaining) {
        return this.retryRequest(options, retriesRemaining);
      }
      if (response.name === "AbortError") {
        throw new APIConnectionTimeoutError2();
      }
      throw new APIConnectionError2({ cause: response });
    }
    const responseHeaders = createResponseHeaders2(response.headers);
    if (!response.ok) {
      if (retriesRemaining && this.shouldRetry(response)) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        debug2(`response (error; ${retryMessage2})`, response.status, url, responseHeaders);
        return this.retryRequest(options, retriesRemaining, responseHeaders);
      }
      const errText = await response.text().catch((e3) => castToError2(e3).message);
      const errJSON = safeJSON2(errText);
      const errMessage = errJSON ? void 0 : errText;
      const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
      debug2(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
      const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
      throw err;
    }
    return { response, options, controller };
  }
  requestAPIList(Page2, options) {
    const request = this.makeRequest(options, null);
    return new PagePromise2(this, request, Page2);
  }
  buildURL(path, query) {
    const url = isAbsoluteURL2(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path));
    const defaultQuery = this.defaultQuery();
    if (!isEmptyObj3(defaultQuery)) {
      query = { ...defaultQuery, ...query };
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  stringifyQuery(query) {
    return Object.entries(query).filter(([_2, value]) => typeof value !== "undefined").map(([key, value]) => {
      if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }
      if (value === null) {
        return `${encodeURIComponent(key)}=`;
      }
      throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
    }).join("&");
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const { signal, ...options } = init || {};
    if (signal)
      signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => {
      clearTimeout(timeout);
    });
  }
  getRequestClient() {
    return { fetch: this.fetch };
  }
  shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, responseHeaders) {
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"];
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders?.["retry-after"];
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
      const maxRetries = options.maxRetries ?? this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep2(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION2}`;
  }
};
var AbstractPage2 = class {
  constructor(client2, response, body, options) {
    _AbstractPage_client2.set(this, void 0);
    __classPrivateFieldSet10(this, _AbstractPage_client2, client2, "f");
    this.options = options;
    this.response = response;
    this.body = body;
  }
  hasNextPage() {
    const items = this.getPaginatedItems();
    if (!items.length)
      return false;
    return this.nextPageInfo() != null;
  }
  async getNextPage() {
    const nextInfo = this.nextPageInfo();
    if (!nextInfo) {
      throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    }
    const nextOptions = { ...this.options };
    if ("params" in nextInfo && typeof nextOptions.query === "object") {
      nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
    } else if ("url" in nextInfo) {
      const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
      for (const [key, value] of params) {
        nextInfo.url.searchParams.set(key, value);
      }
      nextOptions.query = void 0;
      nextOptions.path = nextInfo.url.toString();
    }
    return await __classPrivateFieldGet11(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions);
  }
  async *iterPages() {
    let page = this;
    yield page;
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      yield page;
    }
  }
  async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (const page of this.iterPages()) {
      for (const item of page.getPaginatedItems()) {
        yield item;
      }
    }
  }
};
var PagePromise2 = class extends APIPromise2 {
  constructor(client2, request, Page2) {
    super(request, async (props) => new Page2(client2, props.response, await defaultParseResponse2(props), props.options));
  }
  /**
   * Allow auto-paginating iteration on an unawaited list call, eg:
   *
   *    for await (const item of client.items.list()) {
   *      console.log(item)
   *    }
   */
  async *[Symbol.asyncIterator]() {
    const page = await this;
    for await (const item of page) {
      yield item;
    }
  }
};
var createResponseHeaders2 = (headers) => {
  return new Proxy(Object.fromEntries(
    // @ts-ignore
    headers.entries()
  ), {
    get(target, name) {
      const key = name.toString();
      return target[key.toLowerCase()] || target[key];
    }
  });
};
var getPlatformProperties2 = () => {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": normalizePlatform2(Deno.build.os),
      "X-Stainless-Arch": normalizeArch2(Deno.build.arch),
      "X-Stainless-Runtime": "deno",
      "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
    };
  }
  if (typeof EdgeRuntime !== "undefined") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": `other:${EdgeRuntime}`,
      "X-Stainless-Runtime": "edge",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": normalizePlatform2(process.platform),
      "X-Stainless-Arch": normalizeArch2(process.arch),
      "X-Stainless-Runtime": "node",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  const browserInfo = getBrowserInfo2();
  if (browserInfo) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION2,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": "unknown",
      "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
      "X-Stainless-Runtime-Version": browserInfo.version
    };
  }
  return {
    "X-Stainless-Lang": "js",
    "X-Stainless-Package-Version": VERSION2,
    "X-Stainless-OS": "Unknown",
    "X-Stainless-Arch": "unknown",
    "X-Stainless-Runtime": "unknown",
    "X-Stainless-Runtime-Version": "unknown"
  };
};
function getBrowserInfo2() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major}.${minor}.${patch}` };
    }
  }
  return null;
}
var normalizeArch2 = (arch) => {
  if (arch === "x32")
    return "x32";
  if (arch === "x86_64" || arch === "x64")
    return "x64";
  if (arch === "arm")
    return "arm";
  if (arch === "aarch64" || arch === "arm64")
    return "arm64";
  if (arch)
    return `other:${arch}`;
  return "unknown";
};
var normalizePlatform2 = (platform2) => {
  platform2 = platform2.toLowerCase();
  if (platform2.includes("ios"))
    return "iOS";
  if (platform2 === "android")
    return "Android";
  if (platform2 === "darwin")
    return "MacOS";
  if (platform2 === "win32")
    return "Windows";
  if (platform2 === "freebsd")
    return "FreeBSD";
  if (platform2 === "openbsd")
    return "OpenBSD";
  if (platform2 === "linux")
    return "Linux";
  if (platform2)
    return `Other:${platform2}`;
  return "Unknown";
};
var _platformHeaders2;
var getPlatformHeaders2 = () => {
  return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
};
var safeJSON2 = (text) => {
  try {
    return JSON.parse(text);
  } catch (err) {
    return void 0;
  }
};
var startsWithSchemeRegexp2 = new RegExp("^(?:[a-z]+:)?//", "i");
var isAbsoluteURL2 = (url) => {
  return startsWithSchemeRegexp2.test(url);
};
var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
var validatePositiveInteger2 = (name, n4) => {
  if (typeof n4 !== "number" || !Number.isInteger(n4)) {
    throw new AnthropicError(`${name} must be an integer`);
  }
  if (n4 < 0) {
    throw new AnthropicError(`${name} must be a positive integer`);
  }
  return n4;
};
var castToError2 = (err) => {
  if (err instanceof Error)
    return err;
  return new Error(err);
};
var readEnv2 = (env) => {
  if (typeof process !== "undefined") {
    return process.env?.[env]?.trim() ?? void 0;
  }
  if (typeof Deno !== "undefined") {
    return Deno.env?.get?.(env)?.trim();
  }
  return void 0;
};
function isEmptyObj3(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn2(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function applyHeadersMut2(targetHeaders, newHeaders) {
  for (const k3 in newHeaders) {
    if (!hasOwn2(newHeaders, k3))
      continue;
    const lowerKey = k3.toLowerCase();
    if (!lowerKey)
      continue;
    const val2 = newHeaders[k3];
    if (val2 === null) {
      delete targetHeaders[lowerKey];
    } else if (val2 !== void 0) {
      targetHeaders[lowerKey] = val2;
    }
  }
}
function debug2(action, ...args) {
  if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
    console.log(`Anthropic:DEBUG:${action}`, ...args);
  }
}
var uuid42 = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c4) => {
    const r4 = Math.random() * 16 | 0;
    const v5 = c4 === "x" ? r4 : r4 & 3 | 8;
    return v5.toString(16);
  });
};
var isRunningInBrowser2 = () => {
  return (
    // @ts-ignore
    typeof window !== "undefined" && // @ts-ignore
    typeof window.document !== "undefined" && // @ts-ignore
    typeof navigator !== "undefined"
  );
};

// node_modules/@anthropic-ai/sdk/error.mjs
var AnthropicError = class extends Error {
};
var APIError2 = class extends AnthropicError {
  constructor(status, error, message, headers) {
    super(`${APIError2.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.request_id = headers?.["request-id"];
    this.error = error;
  }
  static makeMessage(status, error, message) {
    const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status) {
      return new APIConnectionError2({ message, cause: castToError2(errorResponse) });
    }
    const error = errorResponse;
    if (status === 400) {
      return new BadRequestError2(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError2(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError2(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError2(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError2(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError2(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError2(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError2(status, error, message, headers);
    }
    return new APIError2(status, error, message, headers);
  }
};
var APIUserAbortError2 = class extends APIError2 {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
    this.status = void 0;
  }
};
var APIConnectionError2 = class extends APIError2 {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    this.status = void 0;
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError2 = class extends APIConnectionError2 {
  constructor({ message } = {}) {
    super({ message: message ?? "Request timed out." });
  }
};
var BadRequestError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 400;
  }
};
var AuthenticationError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 401;
  }
};
var PermissionDeniedError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 403;
  }
};
var NotFoundError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 404;
  }
};
var ConflictError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 409;
  }
};
var UnprocessableEntityError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 422;
  }
};
var RateLimitError2 = class extends APIError2 {
  constructor() {
    super(...arguments);
    this.status = 429;
  }
};
var InternalServerError2 = class extends APIError2 {
};

// node_modules/@anthropic-ai/sdk/resource.mjs
var APIResource2 = class {
  constructor(client2) {
    this._client = client2;
  }
};

// node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
var tokenize2 = (input) => {
  let current = 0;
  let tokens = [];
  while (current < input.length) {
    let char = input[current];
    if (char === "\\") {
      current++;
      continue;
    }
    if (char === "{") {
      tokens.push({
        type: "brace",
        value: "{"
      });
      current++;
      continue;
    }
    if (char === "}") {
      tokens.push({
        type: "brace",
        value: "}"
      });
      current++;
      continue;
    }
    if (char === "[") {
      tokens.push({
        type: "paren",
        value: "["
      });
      current++;
      continue;
    }
    if (char === "]") {
      tokens.push({
        type: "paren",
        value: "]"
      });
      current++;
      continue;
    }
    if (char === ":") {
      tokens.push({
        type: "separator",
        value: ":"
      });
      current++;
      continue;
    }
    if (char === ",") {
      tokens.push({
        type: "delimiter",
        value: ","
      });
      current++;
      continue;
    }
    if (char === '"') {
      let value = "";
      let danglingQuote = false;
      char = input[++current];
      while (char !== '"') {
        if (current === input.length) {
          danglingQuote = true;
          break;
        }
        if (char === "\\") {
          current++;
          if (current === input.length) {
            danglingQuote = true;
            break;
          }
          value += char + input[current];
          char = input[++current];
        } else {
          value += char;
          char = input[++current];
        }
      }
      char = input[++current];
      if (!danglingQuote) {
        tokens.push({
          type: "string",
          value
        });
      }
      continue;
    }
    let WHITESPACE = /\s/;
    if (char && WHITESPACE.test(char)) {
      current++;
      continue;
    }
    let NUMBERS = /[0-9]/;
    if (char && NUMBERS.test(char) || char === "-" || char === ".") {
      let value = "";
      if (char === "-") {
        value += char;
        char = input[++current];
      }
      while (char && NUMBERS.test(char) || char === ".") {
        value += char;
        char = input[++current];
      }
      tokens.push({
        type: "number",
        value
      });
      continue;
    }
    let LETTERS = /[a-z]/i;
    if (char && LETTERS.test(char)) {
      let value = "";
      while (char && LETTERS.test(char)) {
        if (current === input.length) {
          break;
        }
        value += char;
        char = input[++current];
      }
      if (value == "true" || value == "false" || value === "null") {
        tokens.push({
          type: "name",
          value
        });
      } else {
        current++;
        continue;
      }
      continue;
    }
    current++;
  }
  return tokens;
};
var strip = (tokens) => {
  if (tokens.length === 0) {
    return tokens;
  }
  let lastToken = tokens[tokens.length - 1];
  switch (lastToken.type) {
    case "separator":
      tokens = tokens.slice(0, tokens.length - 1);
      return strip(tokens);
      break;
    case "number":
      let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
      if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      }
    case "string":
      let tokenBeforeTheLastToken = tokens[tokens.length - 2];
      if (tokenBeforeTheLastToken?.type === "delimiter") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") {
        tokens = tokens.slice(0, tokens.length - 1);
        return strip(tokens);
      }
      break;
    case "delimiter":
      tokens = tokens.slice(0, tokens.length - 1);
      return strip(tokens);
      break;
  }
  return tokens;
};
var unstrip = (tokens) => {
  let tail = [];
  tokens.map((token) => {
    if (token.type === "brace") {
      if (token.value === "{") {
        tail.push("}");
      } else {
        tail.splice(tail.lastIndexOf("}"), 1);
      }
    }
    if (token.type === "paren") {
      if (token.value === "[") {
        tail.push("]");
      } else {
        tail.splice(tail.lastIndexOf("]"), 1);
      }
    }
  });
  if (tail.length > 0) {
    tail.reverse().map((item) => {
      if (item === "}") {
        tokens.push({
          type: "brace",
          value: "}"
        });
      } else if (item === "]") {
        tokens.push({
          type: "paren",
          value: "]"
        });
      }
    });
  }
  return tokens;
};
var generate = (tokens) => {
  let output = "";
  tokens.map((token) => {
    switch (token.type) {
      case "string":
        output += '"' + token.value + '"';
        break;
      default:
        output += token.value;
        break;
    }
  });
  return output;
};
var partialParse2 = (input) => JSON.parse(generate(unstrip(strip(tokenize2(input)))));

// node_modules/@anthropic-ai/sdk/lib/PromptCachingBetaMessageStream.mjs
var __classPrivateFieldSet11 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet12 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _PromptCachingBetaMessageStream_instances;
var _PromptCachingBetaMessageStream_currentMessageSnapshot;
var _PromptCachingBetaMessageStream_connectedPromise;
var _PromptCachingBetaMessageStream_resolveConnectedPromise;
var _PromptCachingBetaMessageStream_rejectConnectedPromise;
var _PromptCachingBetaMessageStream_endPromise;
var _PromptCachingBetaMessageStream_resolveEndPromise;
var _PromptCachingBetaMessageStream_rejectEndPromise;
var _PromptCachingBetaMessageStream_listeners;
var _PromptCachingBetaMessageStream_ended;
var _PromptCachingBetaMessageStream_errored;
var _PromptCachingBetaMessageStream_aborted;
var _PromptCachingBetaMessageStream_catchingPromiseCreated;
var _PromptCachingBetaMessageStream_getFinalMessage;
var _PromptCachingBetaMessageStream_getFinalText;
var _PromptCachingBetaMessageStream_handleError;
var _PromptCachingBetaMessageStream_beginRequest;
var _PromptCachingBetaMessageStream_addStreamEvent;
var _PromptCachingBetaMessageStream_endRequest;
var _PromptCachingBetaMessageStream_accumulateMessage;
var JSON_BUF_PROPERTY = "__json_buf";
var PromptCachingBetaMessageStream = class {
  constructor() {
    _PromptCachingBetaMessageStream_instances.add(this);
    this.messages = [];
    this.receivedMessages = [];
    _PromptCachingBetaMessageStream_currentMessageSnapshot.set(this, void 0);
    this.controller = new AbortController();
    _PromptCachingBetaMessageStream_connectedPromise.set(this, void 0);
    _PromptCachingBetaMessageStream_resolveConnectedPromise.set(this, () => {
    });
    _PromptCachingBetaMessageStream_rejectConnectedPromise.set(this, () => {
    });
    _PromptCachingBetaMessageStream_endPromise.set(this, void 0);
    _PromptCachingBetaMessageStream_resolveEndPromise.set(this, () => {
    });
    _PromptCachingBetaMessageStream_rejectEndPromise.set(this, () => {
    });
    _PromptCachingBetaMessageStream_listeners.set(this, {});
    _PromptCachingBetaMessageStream_ended.set(this, false);
    _PromptCachingBetaMessageStream_errored.set(this, false);
    _PromptCachingBetaMessageStream_aborted.set(this, false);
    _PromptCachingBetaMessageStream_catchingPromiseCreated.set(this, false);
    _PromptCachingBetaMessageStream_handleError.set(this, (error) => {
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_errored, true, "f");
      if (error instanceof Error && error.name === "AbortError") {
        error = new APIUserAbortError2();
      }
      if (error instanceof APIUserAbortError2) {
        __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_aborted, true, "f");
        return this._emit("abort", error);
      }
      if (error instanceof AnthropicError) {
        return this._emit("error", error);
      }
      if (error instanceof Error) {
        const anthropicError = new AnthropicError(error.message);
        anthropicError.cause = error;
        return this._emit("error", anthropicError);
      }
      return this._emit("error", new AnthropicError(String(error)));
    });
    __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_endPromise, "f").catch(() => {
    });
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream) {
    const runner = new PromptCachingBetaMessageStream();
    runner._run(() => runner._fromReadableStream(stream));
    return runner;
  }
  static createMessage(messages, params, options) {
    const runner = new PromptCachingBetaMessageStream();
    for (const message of params.messages) {
      runner._addPromptCachingBetaMessageParam(message);
    }
    runner._run(() => runner._createPromptCachingBetaMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  _run(executor) {
    executor().then(() => {
      this._emitFinal();
      this._emit("end");
    }, __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_handleError, "f"));
  }
  _addPromptCachingBetaMessageParam(message) {
    this.messages.push(message);
  }
  _addPromptCachingBetaMessage(message, emit = true) {
    this.receivedMessages.push(message);
    if (emit) {
      this._emit("message", message);
    }
  }
  async _createPromptCachingBetaMessage(messages, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_beginRequest).call(this);
    const stream = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream) {
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_addStreamEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_endRequest).call(this);
  }
  _connected() {
    if (this.ended)
      return;
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_resolveConnectedPromise, "f").call(this);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this PromptCachingBetaMessageStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this PromptCachingBetaMessageStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index2 = listeners.findIndex((l4) => l4.listener === listener);
    if (index2 >= 0)
      listeners.splice(index2, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this PromptCachingBetaMessageStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_endPromise, "f");
  }
  get currentMessage() {
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, "f");
  }
  /**
   * @returns a promise that resolves with the the final assistant PromptCachingBetaMessage response,
   * or rejects if an error occurred or the stream ended prematurely without producing a PromptCachingBetaMessage.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant PromptCachingBetaMessage's text response, concatenated
   * together if there are more than one text blocks.
   * Rejects if an error occurred or the stream ended prematurely without producing a PromptCachingBetaMessage.
   */
  async finalText() {
    await this.done();
    return __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_getFinalText).call(this);
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_ended, "f"))
      return;
    if (event === "end") {
      __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_ended, true, "f");
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
    const finalPromptCachingBetaMessage = this.receivedMessages.at(-1);
    if (finalPromptCachingBetaMessage) {
      this._emit("finalPromptCachingBetaMessage", __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_getFinalMessage).call(this));
    }
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_beginRequest).call(this);
    this._connected();
    const stream = Stream2.fromReadableStream(readableStream, this.controller);
    for await (const event of stream) {
      __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_addStreamEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_endRequest).call(this);
  }
  [(_PromptCachingBetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _PromptCachingBetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _PromptCachingBetaMessageStream_getFinalMessage = function _PromptCachingBetaMessageStream_getFinalMessage2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a PromptCachingBetaMessage with role=assistant");
    }
    return this.receivedMessages.at(-1);
  }, _PromptCachingBetaMessageStream_getFinalText = function _PromptCachingBetaMessageStream_getFinalText2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a PromptCachingBetaMessage with role=assistant");
    }
    const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
    if (textBlocks.length === 0) {
      throw new AnthropicError("stream ended without producing a content block with type=text");
    }
    return textBlocks.join(" ");
  }, _PromptCachingBetaMessageStream_beginRequest = function _PromptCachingBetaMessageStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, void 0, "f");
  }, _PromptCachingBetaMessageStream_addStreamEvent = function _PromptCachingBetaMessageStream_addStreamEvent2(event) {
    if (this.ended)
      return;
    const messageSnapshot = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_accumulateMessage).call(this, event);
    this._emit("streamEvent", event, messageSnapshot);
    switch (event.type) {
      case "content_block_delta": {
        const content = messageSnapshot.content.at(-1);
        if (event.delta.type === "text_delta" && content.type === "text") {
          this._emit("text", event.delta.text, content.text || "");
        } else if (event.delta.type === "input_json_delta" && content.type === "tool_use") {
          if (content.input) {
            this._emit("inputJson", event.delta.partial_json, content.input);
          }
        }
        break;
      }
      case "message_stop": {
        this._addPromptCachingBetaMessageParam(messageSnapshot);
        this._addPromptCachingBetaMessage(messageSnapshot, true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", messageSnapshot.content.at(-1));
        break;
      }
      case "message_start": {
        __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, _PromptCachingBetaMessageStream_endRequest = function _PromptCachingBetaMessageStream_endRequest2() {
    if (this.ended) {
      throw new AnthropicError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, "f");
    if (!snapshot) {
      throw new AnthropicError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet11(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, void 0, "f");
    return snapshot;
  }, _PromptCachingBetaMessageStream_accumulateMessage = function _PromptCachingBetaMessageStream_accumulateMessage2(event) {
    let snapshot = __classPrivateFieldGet12(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, "f");
    if (event.type === "message_start") {
      if (snapshot) {
        throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
      }
      return event.message;
    }
    if (!snapshot) {
      throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
    }
    switch (event.type) {
      case "message_stop":
        return snapshot;
      case "message_delta":
        snapshot.stop_reason = event.delta.stop_reason;
        snapshot.stop_sequence = event.delta.stop_sequence;
        snapshot.usage.output_tokens = event.usage.output_tokens;
        return snapshot;
      case "content_block_start":
        snapshot.content.push(event.content_block);
        return snapshot;
      case "content_block_delta": {
        const snapshotContent = snapshot.content.at(event.index);
        if (snapshotContent?.type === "text" && event.delta.type === "text_delta") {
          snapshotContent.text += event.delta.text;
        } else if (snapshotContent?.type === "tool_use" && event.delta.type === "input_json_delta") {
          let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || "";
          jsonBuf += event.delta.partial_json;
          Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, {
            value: jsonBuf,
            enumerable: false,
            writable: true
          });
          if (jsonBuf) {
            snapshotContent.input = partialParse2(jsonBuf);
          }
        }
        return snapshot;
      }
      case "content_block_stop":
        return snapshot;
    }
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("streamEvent", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream.toReadableStream();
  }
};

// node_modules/@anthropic-ai/sdk/resources/beta/prompt-caching/messages.mjs
var Messages2 = class extends APIResource2 {
  create(body, options) {
    return this._client.post("/v1/messages?beta=prompt_caching", {
      body,
      timeout: this._client._options.timeout ?? 6e5,
      ...options,
      headers: { "anthropic-beta": "prompt-caching-2024-07-31", ...options?.headers },
      stream: body.stream ?? false
    });
  }
  /**
   * Create a Message stream
   */
  stream(body, options) {
    return PromptCachingBetaMessageStream.createMessage(this, body, options);
  }
};
(function(Messages4) {
})(Messages2 || (Messages2 = {}));

// node_modules/@anthropic-ai/sdk/resources/beta/prompt-caching/prompt-caching.mjs
var PromptCaching = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.messages = new Messages2(this._client);
  }
};
(function(PromptCaching2) {
  PromptCaching2.Messages = Messages2;
})(PromptCaching || (PromptCaching = {}));

// node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
var Beta2 = class extends APIResource2 {
  constructor() {
    super(...arguments);
    this.promptCaching = new PromptCaching(this._client);
  }
};
(function(Beta3) {
  Beta3.PromptCaching = PromptCaching;
})(Beta2 || (Beta2 = {}));

// node_modules/@anthropic-ai/sdk/resources/completions.mjs
var Completions4 = class extends APIResource2 {
  create(body, options) {
    return this._client.post("/v1/complete", {
      body,
      timeout: this._client._options.timeout ?? 6e5,
      ...options,
      stream: body.stream ?? false
    });
  }
};
(function(Completions7) {
})(Completions4 || (Completions4 = {}));

// node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
var __classPrivateFieldSet12 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet13 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _MessageStream_instances;
var _MessageStream_currentMessageSnapshot;
var _MessageStream_connectedPromise;
var _MessageStream_resolveConnectedPromise;
var _MessageStream_rejectConnectedPromise;
var _MessageStream_endPromise;
var _MessageStream_resolveEndPromise;
var _MessageStream_rejectEndPromise;
var _MessageStream_listeners;
var _MessageStream_ended;
var _MessageStream_errored;
var _MessageStream_aborted;
var _MessageStream_catchingPromiseCreated;
var _MessageStream_getFinalMessage;
var _MessageStream_getFinalText;
var _MessageStream_handleError;
var _MessageStream_beginRequest;
var _MessageStream_addStreamEvent;
var _MessageStream_endRequest;
var _MessageStream_accumulateMessage;
var JSON_BUF_PROPERTY2 = "__json_buf";
var MessageStream = class {
  constructor() {
    _MessageStream_instances.add(this);
    this.messages = [];
    this.receivedMessages = [];
    _MessageStream_currentMessageSnapshot.set(this, void 0);
    this.controller = new AbortController();
    _MessageStream_connectedPromise.set(this, void 0);
    _MessageStream_resolveConnectedPromise.set(this, () => {
    });
    _MessageStream_rejectConnectedPromise.set(this, () => {
    });
    _MessageStream_endPromise.set(this, void 0);
    _MessageStream_resolveEndPromise.set(this, () => {
    });
    _MessageStream_rejectEndPromise.set(this, () => {
    });
    _MessageStream_listeners.set(this, {});
    _MessageStream_ended.set(this, false);
    _MessageStream_errored.set(this, false);
    _MessageStream_aborted.set(this, false);
    _MessageStream_catchingPromiseCreated.set(this, false);
    _MessageStream_handleError.set(this, (error) => {
      __classPrivateFieldSet12(this, _MessageStream_errored, true, "f");
      if (error instanceof Error && error.name === "AbortError") {
        error = new APIUserAbortError2();
      }
      if (error instanceof APIUserAbortError2) {
        __classPrivateFieldSet12(this, _MessageStream_aborted, true, "f");
        return this._emit("abort", error);
      }
      if (error instanceof AnthropicError) {
        return this._emit("error", error);
      }
      if (error instanceof Error) {
        const anthropicError = new AnthropicError(error.message);
        anthropicError.cause = error;
        return this._emit("error", anthropicError);
      }
      return this._emit("error", new AnthropicError(String(error)));
    });
    __classPrivateFieldSet12(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet12(this, _MessageStream_resolveConnectedPromise, resolve, "f");
      __classPrivateFieldSet12(this, _MessageStream_rejectConnectedPromise, reject, "f");
    }), "f");
    __classPrivateFieldSet12(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
      __classPrivateFieldSet12(this, _MessageStream_resolveEndPromise, resolve, "f");
      __classPrivateFieldSet12(this, _MessageStream_rejectEndPromise, reject, "f");
    }), "f");
    __classPrivateFieldGet13(this, _MessageStream_connectedPromise, "f").catch(() => {
    });
    __classPrivateFieldGet13(this, _MessageStream_endPromise, "f").catch(() => {
    });
  }
  /**
   * Intended for use on the frontend, consuming a stream produced with
   * `.toReadableStream()` on the backend.
   *
   * Note that messages sent to the model do not appear in `.on('message')`
   * in this context.
   */
  static fromReadableStream(stream) {
    const runner = new MessageStream();
    runner._run(() => runner._fromReadableStream(stream));
    return runner;
  }
  static createMessage(messages, params, options) {
    const runner = new MessageStream();
    for (const message of params.messages) {
      runner._addMessageParam(message);
    }
    runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
    return runner;
  }
  _run(executor) {
    executor().then(() => {
      this._emitFinal();
      this._emit("end");
    }, __classPrivateFieldGet13(this, _MessageStream_handleError, "f"));
  }
  _addMessageParam(message) {
    this.messages.push(message);
  }
  _addMessage(message, emit = true) {
    this.receivedMessages.push(message);
    if (emit) {
      this._emit("message", message);
    }
  }
  async _createMessage(messages, params, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
    const stream = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
    this._connected();
    for await (const event of stream) {
      __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
  }
  _connected() {
    if (this.ended)
      return;
    __classPrivateFieldGet13(this, _MessageStream_resolveConnectedPromise, "f").call(this);
    this._emit("connect");
  }
  get ended() {
    return __classPrivateFieldGet13(this, _MessageStream_ended, "f");
  }
  get errored() {
    return __classPrivateFieldGet13(this, _MessageStream_errored, "f");
  }
  get aborted() {
    return __classPrivateFieldGet13(this, _MessageStream_aborted, "f");
  }
  abort() {
    this.controller.abort();
  }
  /**
   * Adds the listener function to the end of the listeners array for the event.
   * No checks are made to see if the listener has already been added. Multiple calls passing
   * the same combination of event and listener will result in the listener being added, and
   * called, multiple times.
   * @returns this MessageStream, so that calls can be chained
   */
  on(event, listener) {
    const listeners = __classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event] = []);
    listeners.push({ listener });
    return this;
  }
  /**
   * Removes the specified listener from the listener array for the event.
   * off() will remove, at most, one instance of a listener from the listener array. If any single
   * listener has been added multiple times to the listener array for the specified event, then
   * off() must be called multiple times to remove each instance.
   * @returns this MessageStream, so that calls can be chained
   */
  off(event, listener) {
    const listeners = __classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event];
    if (!listeners)
      return this;
    const index2 = listeners.findIndex((l4) => l4.listener === listener);
    if (index2 >= 0)
      listeners.splice(index2, 1);
    return this;
  }
  /**
   * Adds a one-time listener function for the event. The next time the event is triggered,
   * this listener is removed and then invoked.
   * @returns this MessageStream, so that calls can be chained
   */
  once(event, listener) {
    const listeners = __classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event] = []);
    listeners.push({ listener, once: true });
    return this;
  }
  /**
   * This is similar to `.once()`, but returns a Promise that resolves the next time
   * the event is triggered, instead of calling a listener callback.
   * @returns a Promise that resolves the next time given event is triggered,
   * or rejects if an error is emitted.  (If you request the 'error' event,
   * returns a promise that resolves with the error).
   *
   * Example:
   *
   *   const message = await stream.emitted('message') // rejects if the stream errors
   */
  emitted(event) {
    return new Promise((resolve, reject) => {
      __classPrivateFieldSet12(this, _MessageStream_catchingPromiseCreated, true, "f");
      if (event !== "error")
        this.once("error", reject);
      this.once(event, resolve);
    });
  }
  async done() {
    __classPrivateFieldSet12(this, _MessageStream_catchingPromiseCreated, true, "f");
    await __classPrivateFieldGet13(this, _MessageStream_endPromise, "f");
  }
  get currentMessage() {
    return __classPrivateFieldGet13(this, _MessageStream_currentMessageSnapshot, "f");
  }
  /**
   * @returns a promise that resolves with the the final assistant Message response,
   * or rejects if an error occurred or the stream ended prematurely without producing a Message.
   */
  async finalMessage() {
    await this.done();
    return __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
  }
  /**
   * @returns a promise that resolves with the the final assistant Message's text response, concatenated
   * together if there are more than one text blocks.
   * Rejects if an error occurred or the stream ended prematurely without producing a Message.
   */
  async finalText() {
    await this.done();
    return __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
  }
  _emit(event, ...args) {
    if (__classPrivateFieldGet13(this, _MessageStream_ended, "f"))
      return;
    if (event === "end") {
      __classPrivateFieldSet12(this, _MessageStream_ended, true, "f");
      __classPrivateFieldGet13(this, _MessageStream_resolveEndPromise, "f").call(this);
    }
    const listeners = __classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event];
    if (listeners) {
      __classPrivateFieldGet13(this, _MessageStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
      listeners.forEach(({ listener }) => listener(...args));
    }
    if (event === "abort") {
      const error = args[0];
      if (!__classPrivateFieldGet13(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet13(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet13(this, _MessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
      return;
    }
    if (event === "error") {
      const error = args[0];
      if (!__classPrivateFieldGet13(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
        Promise.reject(error);
      }
      __classPrivateFieldGet13(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
      __classPrivateFieldGet13(this, _MessageStream_rejectEndPromise, "f").call(this, error);
      this._emit("end");
    }
  }
  _emitFinal() {
    const finalMessage = this.receivedMessages.at(-1);
    if (finalMessage) {
      this._emit("finalMessage", __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
    }
  }
  async _fromReadableStream(readableStream, options) {
    const signal = options?.signal;
    if (signal) {
      if (signal.aborted)
        this.controller.abort();
      signal.addEventListener("abort", () => this.controller.abort());
    }
    __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
    this._connected();
    const stream = Stream2.fromReadableStream(readableStream, this.controller);
    for await (const event of stream) {
      __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
    }
    if (stream.controller.signal?.aborted) {
      throw new APIUserAbortError2();
    }
    __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
  }
  [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    return this.receivedMessages.at(-1);
  }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() {
    if (this.receivedMessages.length === 0) {
      throw new AnthropicError("stream ended without producing a Message with role=assistant");
    }
    const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
    if (textBlocks.length === 0) {
      throw new AnthropicError("stream ended without producing a content block with type=text");
    }
    return textBlocks.join(" ");
  }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() {
    if (this.ended)
      return;
    __classPrivateFieldSet12(this, _MessageStream_currentMessageSnapshot, void 0, "f");
  }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
    if (this.ended)
      return;
    const messageSnapshot = __classPrivateFieldGet13(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
    this._emit("streamEvent", event, messageSnapshot);
    switch (event.type) {
      case "content_block_delta": {
        const content = messageSnapshot.content.at(-1);
        if (event.delta.type === "text_delta" && content.type === "text") {
          this._emit("text", event.delta.text, content.text || "");
        } else if (event.delta.type === "input_json_delta" && content.type === "tool_use") {
          if (content.input) {
            this._emit("inputJson", event.delta.partial_json, content.input);
          }
        }
        break;
      }
      case "message_stop": {
        this._addMessageParam(messageSnapshot);
        this._addMessage(messageSnapshot, true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", messageSnapshot.content.at(-1));
        break;
      }
      case "message_start": {
        __classPrivateFieldSet12(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, _MessageStream_endRequest = function _MessageStream_endRequest2() {
    if (this.ended) {
      throw new AnthropicError(`stream has ended, this shouldn't happen`);
    }
    const snapshot = __classPrivateFieldGet13(this, _MessageStream_currentMessageSnapshot, "f");
    if (!snapshot) {
      throw new AnthropicError(`request ended without sending any chunks`);
    }
    __classPrivateFieldSet12(this, _MessageStream_currentMessageSnapshot, void 0, "f");
    return snapshot;
  }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
    let snapshot = __classPrivateFieldGet13(this, _MessageStream_currentMessageSnapshot, "f");
    if (event.type === "message_start") {
      if (snapshot) {
        throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
      }
      return event.message;
    }
    if (!snapshot) {
      throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
    }
    switch (event.type) {
      case "message_stop":
        return snapshot;
      case "message_delta":
        snapshot.stop_reason = event.delta.stop_reason;
        snapshot.stop_sequence = event.delta.stop_sequence;
        snapshot.usage.output_tokens = event.usage.output_tokens;
        return snapshot;
      case "content_block_start":
        snapshot.content.push(event.content_block);
        return snapshot;
      case "content_block_delta": {
        const snapshotContent = snapshot.content.at(event.index);
        if (snapshotContent?.type === "text" && event.delta.type === "text_delta") {
          snapshotContent.text += event.delta.text;
        } else if (snapshotContent?.type === "tool_use" && event.delta.type === "input_json_delta") {
          let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || "";
          jsonBuf += event.delta.partial_json;
          Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY2, {
            value: jsonBuf,
            enumerable: false,
            writable: true
          });
          if (jsonBuf) {
            snapshotContent.input = partialParse2(jsonBuf);
          }
        }
        return snapshot;
      }
      case "content_block_stop":
        return snapshot;
    }
  }, Symbol.asyncIterator)]() {
    const pushQueue = [];
    const readQueue = [];
    let done = false;
    this.on("streamEvent", (event) => {
      const reader = readQueue.shift();
      if (reader) {
        reader.resolve(event);
      } else {
        pushQueue.push(event);
      }
    });
    this.on("end", () => {
      done = true;
      for (const reader of readQueue) {
        reader.resolve(void 0);
      }
      readQueue.length = 0;
    });
    this.on("abort", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    this.on("error", (err) => {
      done = true;
      for (const reader of readQueue) {
        reader.reject(err);
      }
      readQueue.length = 0;
    });
    return {
      next: async () => {
        if (!pushQueue.length) {
          if (done) {
            return { value: void 0, done: true };
          }
          return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
        }
        const chunk = pushQueue.shift();
        return { value: chunk, done: false };
      },
      return: async () => {
        this.abort();
        return { value: void 0, done: true };
      }
    };
  }
  toReadableStream() {
    const stream = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
    return stream.toReadableStream();
  }
};

// node_modules/@anthropic-ai/sdk/resources/messages.mjs
var Messages3 = class extends APIResource2 {
  create(body, options) {
    if (body.model in DEPRECATED_MODELS) {
      console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
    }
    return this._client.post("/v1/messages", {
      body,
      timeout: this._client._options.timeout ?? 6e5,
      ...options,
      stream: body.stream ?? false
    });
  }
  /**
   * Create a Message stream
   */
  stream(body, options) {
    return MessageStream.createMessage(this, body, options);
  }
};
var DEPRECATED_MODELS = {
  "claude-1.3": "November 6th, 2024",
  "claude-1.3-100k": "November 6th, 2024",
  "claude-instant-1.1": "November 6th, 2024",
  "claude-instant-1.1-100k": "November 6th, 2024",
  "claude-instant-1.2": "November 6th, 2024"
};
(function(Messages4) {
})(Messages3 || (Messages3 = {}));

// node_modules/@anthropic-ai/sdk/index.mjs
var _a3;
var Anthropic = class extends APIClient2 {
  /**
   * API Client for interfacing with the Anthropic API.
   *
   * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
   * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
   * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
   * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
   * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv2("ANTHROPIC_BASE_URL"), apiKey = readEnv2("ANTHROPIC_API_KEY") ?? null, authToken = readEnv2("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
    const options = {
      apiKey,
      authToken,
      ...opts,
      baseURL: baseURL || `https://api.anthropic.com`
    };
    if (!options.dangerouslyAllowBrowser && isRunningInBrowser2()) {
      throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n\nTODO: link!\n");
    }
    super({
      baseURL: options.baseURL,
      timeout: options.timeout ?? 6e5,
      httpAgent: options.httpAgent,
      maxRetries: options.maxRetries,
      fetch: options.fetch
    });
    this.completions = new Completions4(this);
    this.messages = new Messages3(this);
    this.beta = new Beta2(this);
    this._options = options;
    this.apiKey = apiKey;
    this.authToken = authToken;
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  defaultHeaders(opts) {
    return {
      ...super.defaultHeaders(opts),
      ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
      "anthropic-version": "2023-06-01",
      ...this._options.defaultHeaders
    };
  }
  validateHeaders(headers, customHeaders) {
    if (this.apiKey && headers["x-api-key"]) {
      return;
    }
    if (customHeaders["x-api-key"] === null) {
      return;
    }
    if (this.authToken && headers["authorization"]) {
      return;
    }
    if (customHeaders["authorization"] === null) {
      return;
    }
    throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
  }
  authHeaders(opts) {
    const apiKeyAuth = this.apiKeyAuth(opts);
    const bearerAuth = this.bearerAuth(opts);
    if (apiKeyAuth != null && !isEmptyObj3(apiKeyAuth)) {
      return apiKeyAuth;
    }
    if (bearerAuth != null && !isEmptyObj3(bearerAuth)) {
      return bearerAuth;
    }
    return {};
  }
  apiKeyAuth(opts) {
    if (this.apiKey == null) {
      return {};
    }
    return { "X-Api-Key": this.apiKey };
  }
  bearerAuth(opts) {
    if (this.authToken == null) {
      return {};
    }
    return { Authorization: `Bearer ${this.authToken}` };
  }
};
_a3 = Anthropic;
Anthropic.Anthropic = _a3;
Anthropic.HUMAN_PROMPT = "\n\nHuman:";
Anthropic.AI_PROMPT = "\n\nAssistant:";
Anthropic.DEFAULT_TIMEOUT = 6e5;
Anthropic.AnthropicError = AnthropicError;
Anthropic.APIError = APIError2;
Anthropic.APIConnectionError = APIConnectionError2;
Anthropic.APIConnectionTimeoutError = APIConnectionTimeoutError2;
Anthropic.APIUserAbortError = APIUserAbortError2;
Anthropic.NotFoundError = NotFoundError2;
Anthropic.ConflictError = ConflictError2;
Anthropic.RateLimitError = RateLimitError2;
Anthropic.BadRequestError = BadRequestError2;
Anthropic.AuthenticationError = AuthenticationError2;
Anthropic.InternalServerError = InternalServerError2;
Anthropic.PermissionDeniedError = PermissionDeniedError2;
Anthropic.UnprocessableEntityError = UnprocessableEntityError2;
Anthropic.toFile = toFile2;
Anthropic.fileFromPath = fileFromPath2;
var { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
var { AnthropicError: AnthropicError2, APIError: APIError3, APIConnectionError: APIConnectionError3, APIConnectionTimeoutError: APIConnectionTimeoutError3, APIUserAbortError: APIUserAbortError3, NotFoundError: NotFoundError3, ConflictError: ConflictError3, RateLimitError: RateLimitError3, BadRequestError: BadRequestError3, AuthenticationError: AuthenticationError3, InternalServerError: InternalServerError3, PermissionDeniedError: PermissionDeniedError3, UnprocessableEntityError: UnprocessableEntityError3 } = error_exports2;
(function(Anthropic2) {
  Anthropic2.Completions = Completions4;
  Anthropic2.Messages = Messages3;
  Anthropic2.Beta = Beta2;
})(Anthropic || (Anthropic = {}));

// node_modules/@langchain/anthropic/dist/chat_models.js
init_outputs2();
init_base9();
init_esm();
init_runnables2();

// node_modules/@langchain/anthropic/dist/output_parsers.js
init_output_parsers2();
var AnthropicToolsOutputParser = class extends BaseLLMOutputParser {
  static lc_name() {
    return "AnthropicToolsOutputParser";
  }
  constructor(params) {
    super(params);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "anthropic", "output_parsers"]
    });
    Object.defineProperty(this, "returnId", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "keyName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "returnSingle", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "zodSchema", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.keyName = params.keyName;
    this.returnSingle = params.returnSingle ?? this.returnSingle;
    this.zodSchema = params.zodSchema;
  }
  async _validateResult(result) {
    let parsedResult = result;
    if (typeof result === "string") {
      try {
        parsedResult = JSON.parse(result);
      } catch (e3) {
        throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e3.message)}`, result);
      }
    } else {
      parsedResult = result;
    }
    if (this.zodSchema === void 0) {
      return parsedResult;
    }
    const zodParsedResult = await this.zodSchema.safeParseAsync(parsedResult);
    if (zodParsedResult.success) {
      return zodParsedResult.data;
    } else {
      throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(parsedResult, null, 2));
    }
  }
  async parseResult(generations) {
    const tools = generations.flatMap((generation) => {
      const { message } = generation;
      if (!Array.isArray(message.content)) {
        return [];
      }
      const tool3 = extractToolCalls(message.content)[0];
      return tool3;
    });
    if (tools[0] === void 0) {
      throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");
    }
    const [tool2] = tools;
    const validatedResult = await this._validateResult(tool2.args);
    return validatedResult;
  }
};
function extractToolCalls(content) {
  const toolCalls = [];
  for (const block of content) {
    if (block.type === "tool_use") {
      toolCalls.push({
        name: block.name,
        args: block.input,
        id: block.id,
        type: "tool_call"
      });
    }
  }
  return toolCalls;
}

// node_modules/@langchain/anthropic/dist/utils/tools.js
function handleToolChoice(toolChoice) {
  if (!toolChoice) {
    return void 0;
  } else if (toolChoice === "any") {
    return {
      type: "any"
    };
  } else if (toolChoice === "auto") {
    return {
      type: "auto"
    };
  } else if (typeof toolChoice === "string") {
    return {
      type: "tool",
      name: toolChoice
    };
  } else {
    return toolChoice;
  }
}
function extractToolCallChunk(chunk) {
  let newToolCallChunk;
  const toolUseChunks = Array.isArray(chunk.content) ? chunk.content.find((c4) => c4.type === "tool_use") : void 0;
  if (toolUseChunks && "index" in toolUseChunks && "name" in toolUseChunks && "id" in toolUseChunks) {
    newToolCallChunk = {
      args: "",
      id: toolUseChunks.id,
      name: toolUseChunks.name,
      index: toolUseChunks.index,
      type: "tool_call_chunk"
    };
  }
  const inputJsonDeltaChunks = Array.isArray(chunk.content) ? chunk.content.find((c4) => c4.type === "input_json_delta") : void 0;
  if (inputJsonDeltaChunks && "index" in inputJsonDeltaChunks && "input" in inputJsonDeltaChunks) {
    if (typeof inputJsonDeltaChunks.input === "string") {
      newToolCallChunk = {
        id: inputJsonDeltaChunks.id,
        name: inputJsonDeltaChunks.name,
        args: inputJsonDeltaChunks.input,
        index: inputJsonDeltaChunks.index,
        type: "tool_call_chunk"
      };
    } else {
      newToolCallChunk = {
        id: inputJsonDeltaChunks.id,
        name: inputJsonDeltaChunks.name,
        args: JSON.stringify(inputJsonDeltaChunks.input, null, 2),
        index: inputJsonDeltaChunks.index,
        type: "tool_call_chunk"
      };
    }
  }
  return newToolCallChunk;
}

// node_modules/@langchain/anthropic/dist/utils/message_inputs.js
function _formatImage(imageUrl) {
  const regex2 = /^data:(image\/.+);base64,(.+)$/;
  const match2 = imageUrl.match(regex2);
  if (match2 === null) {
    throw new Error([
      "Anthropic only supports base64-encoded images currently.",
      "Example: data:image/png;base64,/9j/4AAQSk..."
    ].join("\n\n"));
  }
  return {
    type: "base64",
    media_type: match2[1] ?? "",
    data: match2[2] ?? ""
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
  };
}
function _mergeMessages(messages) {
  const merged = [];
  for (const message of messages) {
    if (message._getType() === "tool") {
      if (typeof message.content === "string") {
        const previousMessage = merged[merged.length - 1];
        if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") {
          previousMessage.content.push({
            type: "tool_result",
            content: message.content,
            tool_use_id: message.tool_call_id
          });
        } else {
          merged.push(new HumanMessage({
            content: [
              {
                type: "tool_result",
                content: message.content,
                tool_use_id: message.tool_call_id
              }
            ]
          }));
        }
      } else {
        merged.push(new HumanMessage({ content: message.content }));
      }
    } else {
      const previousMessage = merged[merged.length - 1];
      if (previousMessage?._getType() === "human" && message._getType() === "human") {
        let combinedContent;
        if (typeof previousMessage.content === "string") {
          combinedContent = [{ type: "text", text: previousMessage.content }];
        } else {
          combinedContent = previousMessage.content;
        }
        if (typeof message.content === "string") {
          combinedContent.push({ type: "text", text: message.content });
        } else {
          combinedContent = combinedContent.concat(message.content);
        }
        previousMessage.content = combinedContent;
      } else {
        merged.push(message);
      }
    }
  }
  return merged;
}
function _convertLangChainToolCallToAnthropic(toolCall) {
  if (toolCall.id === void 0) {
    throw new Error(`Anthropic requires all tool calls to have an "id".`);
  }
  return {
    type: "tool_use",
    id: toolCall.id,
    name: toolCall.name,
    input: toolCall.args
  };
}
function _formatContent(content) {
  const toolTypes = ["tool_use", "tool_result", "input_json_delta"];
  const textTypes = ["text", "text_delta"];
  if (typeof content === "string") {
    return content;
  } else {
    const contentBlocks = content.map((contentPart) => {
      const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : void 0;
      if (contentPart.type === "image_url") {
        let source;
        if (typeof contentPart.image_url === "string") {
          source = _formatImage(contentPart.image_url);
        } else {
          source = _formatImage(contentPart.image_url.url);
        }
        return {
          type: "image",
          source,
          ...cacheControl ? { cache_control: cacheControl } : {}
        };
      } else if (textTypes.find((t3) => t3 === contentPart.type) && "text" in contentPart) {
        return {
          type: "text",
          text: contentPart.text,
          ...cacheControl ? { cache_control: cacheControl } : {}
        };
      } else if (toolTypes.find((t3) => t3 === contentPart.type)) {
        const contentPartCopy = { ...contentPart };
        if ("index" in contentPartCopy) {
          delete contentPartCopy.index;
        }
        if (contentPartCopy.type === "input_json_delta") {
          contentPartCopy.type = "tool_use";
        }
        if ("input" in contentPartCopy) {
          try {
            contentPartCopy.input = JSON.parse(contentPartCopy.input);
          } catch {
          }
        }
        return {
          ...contentPartCopy,
          ...cacheControl ? { cache_control: cacheControl } : {}
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
        };
      } else {
        throw new Error("Unsupported message content format");
      }
    });
    return contentBlocks;
  }
}
function _convertMessagesToAnthropicPayload(messages) {
  const mergedMessages = _mergeMessages(messages);
  let system;
  if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") {
    system = messages[0].content;
  }
  const conversationMessages = system !== void 0 ? mergedMessages.slice(1) : mergedMessages;
  const formattedMessages = conversationMessages.map((message) => {
    let role;
    if (message._getType() === "human") {
      role = "user";
    } else if (message._getType() === "ai") {
      role = "assistant";
    } else if (message._getType() === "tool") {
      role = "user";
    } else if (message._getType() === "system") {
      throw new Error("System messages are only permitted as the first passed message.");
    } else {
      throw new Error(`Message type "${message._getType()}" is not supported.`);
    }
    if (isAIMessage(message) && !!message.tool_calls?.length) {
      if (typeof message.content === "string") {
        if (message.content === "") {
          return {
            role,
            content: message.tool_calls.map(_convertLangChainToolCallToAnthropic)
          };
        } else {
          return {
            role,
            content: [
              { type: "text", text: message.content },
              ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)
            ]
          };
        }
      } else {
        const { content } = message;
        const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta") && contentPart.id === toolCall.id));
        if (hasMismatchedToolCalls) {
          console.warn(`The "tool_calls" field on a message is only respected if content is a string.`);
        }
        return {
          role,
          content: _formatContent(message.content)
        };
      }
    } else {
      return {
        role,
        content: _formatContent(message.content)
      };
    }
  });
  return {
    messages: formattedMessages,
    system
  };
}

// node_modules/@langchain/anthropic/dist/utils/message_outputs.js
function _makeMessageChunkFromAnthropicEvent(data, fields) {
  if (data.type === "message_start") {
    const { content, usage, ...additionalKwargs } = data.message;
    const filteredAdditionalKwargs = {};
    for (const [key, value] of Object.entries(additionalKwargs)) {
      if (value !== void 0 && value !== null) {
        filteredAdditionalKwargs[key] = value;
      }
    }
    const usageMetadata = {
      input_tokens: usage.input_tokens,
      output_tokens: usage.output_tokens,
      total_tokens: usage.input_tokens + usage.output_tokens
    };
    return {
      chunk: new AIMessageChunk({
        content: fields.coerceContentToString ? "" : [],
        additional_kwargs: filteredAdditionalKwargs,
        usage_metadata: fields.streamUsage ? usageMetadata : void 0,
        id: data.message.id
      })
    };
  } else if (data.type === "message_delta") {
    const usageMetadata = {
      input_tokens: 0,
      output_tokens: data.usage.output_tokens,
      total_tokens: data.usage.output_tokens
    };
    return {
      chunk: new AIMessageChunk({
        content: fields.coerceContentToString ? "" : [],
        additional_kwargs: { ...data.delta },
        usage_metadata: fields.streamUsage ? usageMetadata : void 0
      })
    };
  } else if (data.type === "content_block_start" && data.content_block.type === "tool_use") {
    return {
      chunk: new AIMessageChunk({
        content: fields.coerceContentToString ? "" : [
          {
            index: data.index,
            ...data.content_block,
            input: ""
          }
        ],
        additional_kwargs: {}
      })
    };
  } else if (data.type === "content_block_delta" && data.delta.type === "text_delta") {
    const content = data.delta?.text;
    if (content !== void 0) {
      return {
        chunk: new AIMessageChunk({
          content: fields.coerceContentToString ? content : [
            {
              index: data.index,
              ...data.delta
            }
          ],
          additional_kwargs: {}
        })
      };
    }
  } else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") {
    return {
      chunk: new AIMessageChunk({
        content: fields.coerceContentToString ? "" : [
          {
            index: data.index,
            input: data.delta.partial_json,
            type: data.delta.type
          }
        ],
        additional_kwargs: {}
      })
    };
  } else if (data.type === "content_block_start" && data.content_block.type === "text") {
    const content = data.content_block?.text;
    if (content !== void 0) {
      return {
        chunk: new AIMessageChunk({
          content: fields.coerceContentToString ? content : [
            {
              index: data.index,
              ...data.content_block
            }
          ],
          additional_kwargs: {}
        })
      };
    }
  }
  return null;
}
function anthropicResponseToChatMessages(messages, additionalKwargs) {
  const usage = additionalKwargs.usage;
  const usageMetadata = usage != null ? {
    input_tokens: usage.input_tokens ?? 0,
    output_tokens: usage.output_tokens ?? 0,
    total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0)
  } : void 0;
  if (messages.length === 1 && messages[0].type === "text") {
    return [
      {
        text: messages[0].text,
        message: new AIMessage({
          content: messages[0].text,
          additional_kwargs: additionalKwargs,
          usage_metadata: usageMetadata,
          response_metadata: additionalKwargs,
          id: additionalKwargs.id
        })
      }
    ];
  } else {
    const toolCalls = extractToolCalls(messages);
    const generations = [
      {
        text: "",
        message: new AIMessage({
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          content: messages,
          additional_kwargs: additionalKwargs,
          tool_calls: toolCalls,
          usage_metadata: usageMetadata,
          response_metadata: additionalKwargs,
          id: additionalKwargs.id
        })
      }
    ];
    return generations;
  }
}

// node_modules/@langchain/anthropic/dist/chat_models.js
function _toolsInParams(params) {
  return !!(params.tools && params.tools.length > 0);
}
function isAnthropicTool(tool2) {
  return "input_schema" in tool2;
}
function extractToken(chunk) {
  if (typeof chunk.content === "string") {
    return chunk.content;
  } else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) {
    return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input);
  } else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0]) {
    return chunk.content[0].text;
  }
  return void 0;
}
var ChatAnthropicMessages = class extends BaseChatModel {
  static lc_name() {
    return "ChatAnthropic";
  }
  get lc_secrets() {
    return {
      anthropicApiKey: "ANTHROPIC_API_KEY",
      apiKey: "ANTHROPIC_API_KEY"
    };
  }
  get lc_aliases() {
    return {
      modelName: "model"
    };
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "anthropicApiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "apiUrl", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 1
    });
    Object.defineProperty(this, "topK", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -1
    });
    Object.defineProperty(this, "topP", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -1
    });
    Object.defineProperty(this, "maxTokens", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 2048
    });
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "claude-2.1"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "claude-2.1"
    });
    Object.defineProperty(this, "invocationKwargs", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stopSequences", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "clientOptions", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "batchClient", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streamingClient", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streamUsage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    Object.defineProperty(this, "createClient", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable2("ANTHROPIC_API_KEY");
    if (!this.anthropicApiKey && !fields?.createClient) {
      throw new Error("Anthropic API key not found");
    }
    this.clientOptions = fields?.clientOptions ?? {};
    this.apiKey = this.anthropicApiKey;
    this.apiUrl = fields?.anthropicApiUrl;
    this.modelName = fields?.model ?? fields?.modelName ?? this.model;
    this.model = this.modelName;
    this.invocationKwargs = fields?.invocationKwargs ?? {};
    this.temperature = fields?.temperature ?? this.temperature;
    this.topK = fields?.topK ?? this.topK;
    this.topP = fields?.topP ?? this.topP;
    this.maxTokens = fields?.maxTokensToSample ?? fields?.maxTokens ?? this.maxTokens;
    this.stopSequences = fields?.stopSequences ?? this.stopSequences;
    this.streaming = fields?.streaming ?? false;
    this.streamUsage = fields?.streamUsage ?? this.streamUsage;
    this.createClient = fields?.createClient ?? ((options) => new Anthropic(options));
  }
  getLsParams(options) {
    const params = this.invocationParams(options);
    return {
      ls_provider: "anthropic",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: params.temperature ?? void 0,
      ls_max_tokens: params.max_tokens ?? void 0,
      ls_stop: options.stop
    };
  }
  /**
   * Formats LangChain StructuredTools to AnthropicTools.
   *
   * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format
   * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.
   */
  formatStructuredToolToAnthropic(tools) {
    if (!tools || !tools.length) {
      return void 0;
    }
    return tools.map((tool2) => {
      if (isAnthropicTool(tool2)) {
        return tool2;
      }
      if (isOpenAITool(tool2)) {
        return {
          name: tool2.function.name,
          description: tool2.function.description,
          input_schema: tool2.function.parameters
        };
      }
      if (isLangChainTool(tool2)) {
        return {
          name: tool2.name,
          description: tool2.description,
          input_schema: zodToJsonSchema(tool2.schema)
        };
      }
      throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool2, null, 2)}`);
    });
  }
  bindTools(tools, kwargs) {
    return this.bind({
      tools: this.formatStructuredToolToAnthropic(tools),
      ...kwargs
    });
  }
  /**
   * Get the parameters used to invoke the model
   */
  invocationParams(options) {
    const tool_choice = handleToolChoice(options?.tool_choice);
    return {
      model: this.model,
      temperature: this.temperature,
      top_k: this.topK,
      top_p: this.topP,
      stop_sequences: options?.stop ?? this.stopSequences,
      stream: this.streaming,
      max_tokens: this.maxTokens,
      tools: this.formatStructuredToolToAnthropic(options?.tools),
      tool_choice,
      ...this.invocationKwargs
    };
  }
  /** @ignore */
  _identifyingParams() {
    return {
      model_name: this.model,
      ...this.invocationParams()
    };
  }
  /**
   * Get the identifying parameters for the model
   */
  identifyingParams() {
    return {
      model_name: this.model,
      ...this.invocationParams()
    };
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const params = this.invocationParams(options);
    const formattedMessages = _convertMessagesToAnthropicPayload(messages);
    const coerceContentToString = !_toolsInParams({
      ...params,
      ...formattedMessages,
      stream: false
    });
    const stream = await this.createStreamWithRetry({
      ...params,
      ...formattedMessages,
      stream: true
    }, {
      headers: options.headers
    });
    for await (const data of stream) {
      if (options.signal?.aborted) {
        stream.controller.abort();
        throw new Error("AbortError: User aborted the request.");
      }
      const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
      const result = _makeMessageChunkFromAnthropicEvent(data, {
        streamUsage: shouldStreamUsage,
        coerceContentToString
      });
      if (!result)
        continue;
      const { chunk } = result;
      const newToolCallChunk = extractToolCallChunk(chunk);
      const token = extractToken(chunk);
      yield new ChatGenerationChunk({
        message: new AIMessageChunk({
          // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().
          content: chunk.content,
          additional_kwargs: chunk.additional_kwargs,
          tool_call_chunks: newToolCallChunk ? [newToolCallChunk] : void 0,
          usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0,
          response_metadata: chunk.response_metadata,
          id: chunk.id
        }),
        text: token ?? ""
      });
      if (token) {
        await runManager?.handleLLMNewToken(token);
      }
    }
  }
  /** @ignore */
  async _generateNonStreaming(messages, params, requestOptions) {
    const response = await this.completionWithRetry({
      ...params,
      stream: false,
      ..._convertMessagesToAnthropicPayload(messages)
    }, requestOptions);
    const { content, ...additionalKwargs } = response;
    const generations = anthropicResponseToChatMessages(content, additionalKwargs);
    const { role: _role, type: _type, ...rest } = additionalKwargs;
    return { generations, llmOutput: rest };
  }
  /** @ignore */
  async _generate(messages, options, runManager) {
    if (this.stopSequences && options.stop) {
      throw new Error(`"stopSequence" parameter found in input and default params`);
    }
    const params = this.invocationParams(options);
    if (params.stream) {
      let finalChunk;
      const stream = this._streamResponseChunks(messages, options, runManager);
      for await (const chunk of stream) {
        if (finalChunk === void 0) {
          finalChunk = chunk;
        } else {
          finalChunk = finalChunk.concat(chunk);
        }
      }
      if (finalChunk === void 0) {
        throw new Error("No chunks returned from Anthropic API.");
      }
      return {
        generations: [
          {
            text: finalChunk.text,
            message: finalChunk.message
          }
        ]
      };
    } else {
      return this._generateNonStreaming(messages, params, {
        signal: options.signal,
        headers: options.headers
      });
    }
  }
  /**
   * Creates a streaming request with retry.
   * @param request The parameters for creating a completion.
   * @param options
   * @returns A streaming request.
   */
  async createStreamWithRetry(request, options) {
    if (!this.streamingClient) {
      const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0;
      this.streamingClient = this.createClient({
        dangerouslyAllowBrowser: true,
        ...this.clientOptions,
        ...options_,
        apiKey: this.apiKey,
        // Prefer LangChain built-in retries
        maxRetries: 0
      });
    }
    const makeCompletionRequest = async () => this.streamingClient.messages.create({
      ...request,
      ...this.invocationKwargs,
      stream: true
    }, options);
    return this.caller.call(makeCompletionRequest);
  }
  /** @ignore */
  async completionWithRetry(request, options) {
    if (!this.batchClient) {
      const options2 = this.apiUrl ? { baseURL: this.apiUrl } : void 0;
      this.batchClient = this.createClient({
        dangerouslyAllowBrowser: true,
        ...this.clientOptions,
        ...options2,
        apiKey: this.apiKey,
        maxRetries: 0
      });
    }
    const makeCompletionRequest = async () => this.batchClient.messages.create({
      ...request,
      ...this.invocationKwargs
    }, options);
    return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest);
  }
  _llmType() {
    return "anthropic";
  }
  withStructuredOutput(outputSchema, config) {
    const schema = outputSchema;
    const name = config?.name;
    const method = config?.method;
    const includeRaw = config?.includeRaw;
    if (method === "jsonMode") {
      throw new Error(`Anthropic only supports "functionCalling" as a method.`);
    }
    let functionName = name ?? "extract";
    let outputParser;
    let tools;
    if (isZodSchema(schema)) {
      const jsonSchema = zodToJsonSchema(schema);
      tools = [
        {
          name: functionName,
          description: jsonSchema.description ?? "A function available to call.",
          input_schema: jsonSchema
        }
      ];
      outputParser = new AnthropicToolsOutputParser({
        returnSingle: true,
        keyName: functionName,
        zodSchema: schema
      });
    } else {
      let anthropicTools;
      if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) {
        anthropicTools = schema;
        functionName = schema.name;
      } else {
        anthropicTools = {
          name: functionName,
          description: schema.description ?? "",
          input_schema: schema
        };
      }
      tools = [anthropicTools];
      outputParser = new AnthropicToolsOutputParser({
        returnSingle: true,
        keyName: functionName
      });
    }
    const llm = this.bind({
      tools,
      tool_choice: {
        type: "tool",
        name: functionName
      }
    });
    if (!includeRaw) {
      return llm.pipe(outputParser).withConfig({
        runName: "ChatAnthropicStructuredOutput"
      });
    }
    const parserAssign = RunnablePassthrough.assign({
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parsed: (input, config2) => outputParser.invoke(input.raw, config2)
    });
    const parserNone = RunnablePassthrough.assign({
      parsed: () => null
    });
    const parsedWithFallback = parserAssign.withFallbacks({
      fallbacks: [parserNone]
    });
    return RunnableSequence.from([
      {
        raw: llm
      },
      parsedWithFallback
    ]).withConfig({
      runName: "StructuredOutputRunnable"
    });
  }
};
var ChatAnthropic = class extends ChatAnthropicMessages {
};

// node_modules/@langchain/groq/dist/chat_models.js
init_esm();
init_outputs2();

// node_modules/groq-sdk/version.mjs
var VERSION3 = "0.5.0";

// node_modules/groq-sdk/_shims/registry.mjs
var auto3 = false;
var kind3 = void 0;
var fetch5 = void 0;
var Request5 = void 0;
var Response5 = void 0;
var Headers5 = void 0;
var FormData4 = void 0;
var Blob4 = void 0;
var File4 = void 0;
var ReadableStream4 = void 0;
var getMultipartRequestOptions3 = void 0;
var getDefaultAgent3 = void 0;
var fileFromPath3 = void 0;
var isFsReadStream3 = void 0;
function setShims3(shims, options = { auto: false }) {
  if (auto3) {
    throw new Error(`you must \`import 'groq-sdk/shims/${shims.kind}'\` before importing anything else from groq-sdk`);
  }
  if (kind3) {
    throw new Error(`can't \`import 'groq-sdk/shims/${shims.kind}'\` after \`import 'groq-sdk/shims/${kind3}'\``);
  }
  auto3 = options.auto;
  kind3 = shims.kind;
  fetch5 = shims.fetch;
  Request5 = shims.Request;
  Response5 = shims.Response;
  Headers5 = shims.Headers;
  FormData4 = shims.FormData;
  Blob4 = shims.Blob;
  File4 = shims.File;
  ReadableStream4 = shims.ReadableStream;
  getMultipartRequestOptions3 = shims.getMultipartRequestOptions;
  getDefaultAgent3 = shims.getDefaultAgent;
  fileFromPath3 = shims.fileFromPath;
  isFsReadStream3 = shims.isFsReadStream;
}

// node_modules/groq-sdk/_shims/MultipartBody.mjs
var MultipartBody3 = class {
  constructor(body) {
    this.body = body;
  }
  get [Symbol.toStringTag]() {
    return "MultipartBody";
  }
};

// node_modules/groq-sdk/_shims/web-runtime.mjs
function getRuntime3({ manuallyImported } = {}) {
  const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from 'groq-sdk'\`:
- \`import 'groq-sdk/shims/node'\` (if you're running on Node)
- \`import 'groq-sdk/shims/web'\` (otherwise)
`;
  let _fetch, _Request, _Response, _Headers;
  try {
    _fetch = fetch;
    _Request = Request;
    _Response = Response;
    _Headers = Headers;
  } catch (error) {
    throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
  }
  return {
    kind: "web",
    fetch: _fetch,
    Request: _Request,
    Response: _Response,
    Headers: _Headers,
    FormData: (
      // @ts-ignore
      typeof FormData !== "undefined" ? FormData : class FormData {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
        }
      }
    ),
    Blob: typeof Blob !== "undefined" ? Blob : class Blob {
      constructor() {
        throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
      }
    },
    File: (
      // @ts-ignore
      typeof File !== "undefined" ? File : class File {
        // @ts-ignore
        constructor() {
          throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
        }
      }
    ),
    ReadableStream: (
      // @ts-ignore
      typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream {
        // @ts-ignore
        constructor() {
          throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
        }
      }
    ),
    getMultipartRequestOptions: async (form, opts) => ({
      ...opts,
      body: new MultipartBody3(form)
    }),
    getDefaultAgent: (url) => void 0,
    fileFromPath: () => {
      throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/groq/groq-typescript#file-uploads");
    },
    isFsReadStream: (value) => false
  };
}

// node_modules/groq-sdk/_shims/index.mjs
if (!kind3)
  setShims3(getRuntime3(), { auto: true });

// node_modules/groq-sdk/error.mjs
var error_exports3 = {};
__export(error_exports3, {
  APIConnectionError: () => APIConnectionError4,
  APIConnectionTimeoutError: () => APIConnectionTimeoutError4,
  APIError: () => APIError4,
  APIUserAbortError: () => APIUserAbortError4,
  AuthenticationError: () => AuthenticationError4,
  BadRequestError: () => BadRequestError4,
  ConflictError: () => ConflictError4,
  GroqError: () => GroqError,
  InternalServerError: () => InternalServerError4,
  NotFoundError: () => NotFoundError4,
  PermissionDeniedError: () => PermissionDeniedError4,
  RateLimitError: () => RateLimitError4,
  UnprocessableEntityError: () => UnprocessableEntityError4
});
var GroqError = class extends Error {
};
var APIError4 = class extends GroqError {
  constructor(status, error, message, headers) {
    super(`${APIError4.makeMessage(status, error, message)}`);
    this.status = status;
    this.headers = headers;
    this.error = error;
  }
  static makeMessage(status, error, message) {
    const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
    if (status && msg) {
      return `${status} ${msg}`;
    }
    if (status) {
      return `${status} status code (no body)`;
    }
    if (msg) {
      return msg;
    }
    return "(no status code or body)";
  }
  static generate(status, errorResponse, message, headers) {
    if (!status) {
      return new APIConnectionError4({ cause: castToError3(errorResponse) });
    }
    const error = errorResponse;
    if (status === 400) {
      return new BadRequestError4(status, error, message, headers);
    }
    if (status === 401) {
      return new AuthenticationError4(status, error, message, headers);
    }
    if (status === 403) {
      return new PermissionDeniedError4(status, error, message, headers);
    }
    if (status === 404) {
      return new NotFoundError4(status, error, message, headers);
    }
    if (status === 409) {
      return new ConflictError4(status, error, message, headers);
    }
    if (status === 422) {
      return new UnprocessableEntityError4(status, error, message, headers);
    }
    if (status === 429) {
      return new RateLimitError4(status, error, message, headers);
    }
    if (status >= 500) {
      return new InternalServerError4(status, error, message, headers);
    }
    return new APIError4(status, error, message, headers);
  }
};
var APIUserAbortError4 = class extends APIError4 {
  constructor({ message } = {}) {
    super(void 0, void 0, message || "Request was aborted.", void 0);
    this.status = void 0;
  }
};
var APIConnectionError4 = class extends APIError4 {
  constructor({ message, cause }) {
    super(void 0, void 0, message || "Connection error.", void 0);
    this.status = void 0;
    if (cause)
      this.cause = cause;
  }
};
var APIConnectionTimeoutError4 = class extends APIConnectionError4 {
  constructor({ message } = {}) {
    super({ message: message ?? "Request timed out." });
  }
};
var BadRequestError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 400;
  }
};
var AuthenticationError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 401;
  }
};
var PermissionDeniedError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 403;
  }
};
var NotFoundError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 404;
  }
};
var ConflictError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 409;
  }
};
var UnprocessableEntityError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 422;
  }
};
var RateLimitError4 = class extends APIError4 {
  constructor() {
    super(...arguments);
    this.status = 429;
  }
};
var InternalServerError4 = class extends APIError4 {
};

// node_modules/groq-sdk/lib/streaming.mjs
var Stream3 = class {
  constructor(iterator, controller) {
    this.iterator = iterator;
    this.controller = controller;
  }
  static fromSSEResponse(response, controller) {
    let consumed2 = false;
    const decoder = new SSEDecoder3();
    async function* iterMessages() {
      if (!response.body) {
        controller.abort();
        throw new GroqError(`Attempted to iterate over a response with no body`);
      }
      const lineDecoder = new LineDecoder3();
      const iter = readableStreamAsyncIterable3(response.body);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          const sse = decoder.decode(line);
          if (sse)
            yield sse;
        }
      }
      for (const line of lineDecoder.flush()) {
        const sse = decoder.decode(line);
        if (sse)
          yield sse;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const sse of iterMessages()) {
          if (done)
            continue;
          if (sse.data.startsWith("[DONE]")) {
            done = true;
            continue;
          }
          if (sse.event === null) {
            let data;
            try {
              data = JSON.parse(sse.data);
            } catch (e3) {
              console.error(`Could not parse message into JSON:`, sse.data);
              console.error(`From chunk:`, sse.raw);
              throw e3;
            }
            if (data && data.error) {
              throw new APIError4(void 0, data.error, void 0, void 0);
            }
            yield data;
          }
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream3(iterator, controller);
  }
  /**
   * Generates a Stream from a newline-separated ReadableStream
   * where each item is a JSON value.
   */
  static fromReadableStream(readableStream, controller) {
    let consumed2 = false;
    async function* iterLines() {
      const lineDecoder = new LineDecoder3();
      const iter = readableStreamAsyncIterable3(readableStream);
      for await (const chunk of iter) {
        for (const line of lineDecoder.decode(chunk)) {
          yield line;
        }
      }
      for (const line of lineDecoder.flush()) {
        yield line;
      }
    }
    async function* iterator() {
      if (consumed2) {
        throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      }
      consumed2 = true;
      let done = false;
      try {
        for await (const line of iterLines()) {
          if (done)
            continue;
          if (line)
            yield JSON.parse(line);
        }
        done = true;
      } catch (e3) {
        if (e3 instanceof Error && e3.name === "AbortError")
          return;
        throw e3;
      } finally {
        if (!done)
          controller.abort();
      }
    }
    return new Stream3(iterator, controller);
  }
  [Symbol.asyncIterator]() {
    return this.iterator();
  }
  /**
   * Splits the stream into two streams which can be
   * independently read from at different speeds.
   */
  tee() {
    const left = [];
    const right = [];
    const iterator = this.iterator();
    const teeIterator = (queue2) => {
      return {
        next: () => {
          if (queue2.length === 0) {
            const result = iterator.next();
            left.push(result);
            right.push(result);
          }
          return queue2.shift();
        }
      };
    };
    return [
      new Stream3(() => teeIterator(left), this.controller),
      new Stream3(() => teeIterator(right), this.controller)
    ];
  }
  /**
   * Converts this stream to a newline-separated ReadableStream of
   * JSON stringified values in the stream
   * which can be turned back into a Stream with `Stream.fromReadableStream()`.
   */
  toReadableStream() {
    const self2 = this;
    let iter;
    const encoder = new TextEncoder();
    return new ReadableStream4({
      async start() {
        iter = self2[Symbol.asyncIterator]();
      },
      async pull(ctrl) {
        try {
          const { value, done } = await iter.next();
          if (done)
            return ctrl.close();
          const bytes = encoder.encode(JSON.stringify(value) + "\n");
          ctrl.enqueue(bytes);
        } catch (err) {
          ctrl.error(err);
        }
      },
      async cancel() {
        await iter.return?.();
      }
    });
  }
};
var SSEDecoder3 = class {
  constructor() {
    this.event = null;
    this.data = [];
    this.chunks = [];
  }
  decode(line) {
    if (line.endsWith("\r")) {
      line = line.substring(0, line.length - 1);
    }
    if (!line) {
      if (!this.event && !this.data.length)
        return null;
      const sse = {
        event: this.event,
        data: this.data.join("\n"),
        raw: this.chunks
      };
      this.event = null;
      this.data = [];
      this.chunks = [];
      return sse;
    }
    this.chunks.push(line);
    if (line.startsWith(":")) {
      return null;
    }
    let [fieldname, _2, value] = partition4(line, ":");
    if (value.startsWith(" ")) {
      value = value.substring(1);
    }
    if (fieldname === "event") {
      this.event = value;
    } else if (fieldname === "data") {
      this.data.push(value);
    }
    return null;
  }
};
var LineDecoder3 = class {
  constructor() {
    this.buffer = [];
    this.trailingCR = false;
  }
  decode(chunk) {
    let text = this.decodeText(chunk);
    if (this.trailingCR) {
      text = "\r" + text;
      this.trailingCR = false;
    }
    if (text.endsWith("\r")) {
      this.trailingCR = true;
      text = text.slice(0, -1);
    }
    if (!text) {
      return [];
    }
    const trailingNewline = LineDecoder3.NEWLINE_CHARS.has(text[text.length - 1] || "");
    let lines = text.split(LineDecoder3.NEWLINE_REGEXP);
    if (lines.length === 1 && !trailingNewline) {
      this.buffer.push(lines[0]);
      return [];
    }
    if (this.buffer.length > 0) {
      lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
      this.buffer = [];
    }
    if (!trailingNewline) {
      this.buffer = [lines.pop() || ""];
    }
    return lines;
  }
  decodeText(bytes) {
    if (bytes == null)
      return "";
    if (typeof bytes === "string")
      return bytes;
    if (typeof Buffer !== "undefined") {
      if (bytes instanceof Buffer) {
        return bytes.toString();
      }
      if (bytes instanceof Uint8Array) {
        return Buffer.from(bytes).toString();
      }
      throw new GroqError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`);
    }
    if (typeof TextDecoder !== "undefined") {
      if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
        this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
        return this.textDecoder.decode(bytes);
      }
      throw new GroqError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);
    }
    throw new GroqError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);
  }
  flush() {
    if (!this.buffer.length && !this.trailingCR) {
      return [];
    }
    const lines = [this.buffer.join("")];
    this.buffer = [];
    this.trailingCR = false;
    return lines;
  }
};
LineDecoder3.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r", "\v", "\f", "", "", "", "\x85", "\u2028", "\u2029"]);
LineDecoder3.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;
function partition4(str2, delimiter) {
  const index2 = str2.indexOf(delimiter);
  if (index2 !== -1) {
    return [str2.substring(0, index2), delimiter, str2.substring(index2 + delimiter.length)];
  }
  return [str2, "", ""];
}
function readableStreamAsyncIterable3(stream) {
  if (stream[Symbol.asyncIterator])
    return stream;
  const reader = stream.getReader();
  return {
    async next() {
      try {
        const result = await reader.read();
        if (result?.done)
          reader.releaseLock();
        return result;
      } catch (e3) {
        reader.releaseLock();
        throw e3;
      }
    },
    async return() {
      const cancelPromise2 = reader.cancel();
      reader.releaseLock();
      await cancelPromise2;
      return { done: true, value: void 0 };
    },
    [Symbol.asyncIterator]() {
      return this;
    }
  };
}

// node_modules/groq-sdk/uploads.mjs
var isResponseLike3 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
var isFileLike3 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike3(value);
var isBlobLike3 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
var isUploadable2 = (value) => {
  return isFileLike3(value) || isResponseLike3(value) || isFsReadStream3(value);
};
async function toFile3(value, name, options) {
  value = await value;
  options ?? (options = isFileLike3(value) ? { lastModified: value.lastModified, type: value.type } : {});
  if (isResponseLike3(value)) {
    const blob = await value.blob();
    name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
    return new File4([blob], name, options);
  }
  const bits = await getBytes3(value);
  name || (name = getName3(value) ?? "unknown_file");
  if (!options.type) {
    const type = bits[0]?.type;
    if (typeof type === "string") {
      options = { ...options, type };
    }
  }
  return new File4(bits, name, options);
}
async function getBytes3(value) {
  let parts = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts.push(value);
  } else if (isBlobLike3(value)) {
    parts.push(await value.arrayBuffer());
  } else if (isAsyncIterableIterator3(value)) {
    for await (const chunk of value) {
      parts.push(chunk);
    }
  } else {
    throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError3(value)}`);
  }
  return parts;
}
function propsForError3(value) {
  const props = Object.getOwnPropertyNames(value);
  return `[${props.map((p3) => `"${p3}"`).join(", ")}]`;
}
function getName3(value) {
  return getStringFromMaybeBuffer3(value.name) || getStringFromMaybeBuffer3(value.filename) || // For fs.ReadStream
  getStringFromMaybeBuffer3(value.path)?.split(/[\\/]/).pop();
}
var getStringFromMaybeBuffer3 = (x2) => {
  if (typeof x2 === "string")
    return x2;
  if (typeof Buffer !== "undefined" && x2 instanceof Buffer)
    return String(x2);
  return void 0;
};
var isAsyncIterableIterator3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
var isMultipartBody3 = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody";
var multipartFormRequestOptions2 = async (opts) => {
  const form = await createForm2(opts.body);
  return getMultipartRequestOptions3(form, opts);
};
var createForm2 = async (body) => {
  const form = new FormData4();
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue2(form, key, value)));
  return form;
};
var addFormValue2 = async (form, key, value) => {
  if (value === void 0)
    return;
  if (value == null) {
    throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
  }
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    form.append(key, String(value));
  } else if (isUploadable2(value)) {
    const file = await toFile3(value);
    form.append(key, file);
  } else if (Array.isArray(value)) {
    await Promise.all(value.map((entry) => addFormValue2(form, key + "[]", entry)));
  } else if (typeof value === "object") {
    await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue2(form, `${key}[${name}]`, prop)));
  } else {
    throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
  }
};

// node_modules/groq-sdk/core.mjs
var __classPrivateFieldSet13 = function(receiver, state, value, kind4, f3) {
  if (kind4 === "m")
    throw new TypeError("Private method is not writable");
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet14 = function(receiver, state, kind4, f3) {
  if (kind4 === "a" && !f3)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver);
};
var _AbstractPage_client3;
async function defaultParseResponse3(props) {
  const { response } = props;
  if (props.options.stream) {
    debug3("response", response.status, response.url, response.headers, response.body);
    if (props.options.__streamClass) {
      return props.options.__streamClass.fromSSEResponse(response, props.controller);
    }
    return Stream3.fromSSEResponse(response, props.controller);
  }
  if (response.status === 204) {
    return null;
  }
  if (props.options.__binaryResponse) {
    return response;
  }
  const contentType = response.headers.get("content-type");
  const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
  if (isJSON) {
    const json = await response.json();
    debug3("response", response.status, response.url, response.headers, json);
    return json;
  }
  const text = await response.text();
  debug3("response", response.status, response.url, response.headers, text);
  return text;
}
var APIPromise3 = class extends Promise {
  constructor(responsePromise, parseResponse = defaultParseResponse3) {
    super((resolve) => {
      resolve(null);
    });
    this.responsePromise = responsePromise;
    this.parseResponse = parseResponse;
  }
  _thenUnwrap(transform) {
    return new APIPromise3(this.responsePromise, async (props) => transform(await this.parseResponse(props)));
  }
  /**
   * Gets the raw `Response` instance instead of parsing the response
   * data.
   *
   * If you want to parse the response body but still get the `Response`
   * instance, you can use {@link withResponse()}.
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from 'groq-sdk'`:
   * - `import 'groq-sdk/shims/node'` (if you're running on Node)
   * - `import 'groq-sdk/shims/web'` (otherwise)
   */
  asResponse() {
    return this.responsePromise.then((p3) => p3.response);
  }
  /**
   * Gets the parsed response data and the raw `Response` instance.
   *
   * If you just want to get the raw `Response` instance without parsing it,
   * you can use {@link asResponse()}.
   *
   *
   * 👋 Getting the wrong TypeScript type for `Response`?
   * Try setting `"moduleResolution": "NodeNext"` if you can,
   * or add one of these imports before your first `import … from 'groq-sdk'`:
   * - `import 'groq-sdk/shims/node'` (if you're running on Node)
   * - `import 'groq-sdk/shims/web'` (otherwise)
   */
  async withResponse() {
    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
    return { data, response };
  }
  parse() {
    if (!this.parsedPromise) {
      this.parsedPromise = this.responsePromise.then(this.parseResponse);
    }
    return this.parsedPromise;
  }
  then(onfulfilled, onrejected) {
    return this.parse().then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.parse().catch(onrejected);
  }
  finally(onfinally) {
    return this.parse().finally(onfinally);
  }
};
var APIClient3 = class {
  constructor({
    baseURL,
    maxRetries = 2,
    timeout = 6e4,
    // 1 minute
    httpAgent,
    fetch: overridenFetch
  }) {
    this.baseURL = baseURL;
    this.maxRetries = validatePositiveInteger3("maxRetries", maxRetries);
    this.timeout = validatePositiveInteger3("timeout", timeout);
    this.httpAgent = httpAgent;
    this.fetch = overridenFetch ?? fetch5;
  }
  authHeaders(opts) {
    return {};
  }
  /**
   * Override this to add your own default headers, for example:
   *
   *  {
   *    ...super.defaultHeaders(),
   *    Authorization: 'Bearer 123',
   *  }
   */
  defaultHeaders(opts) {
    return {
      Accept: "application/json",
      "Content-Type": "application/json",
      "User-Agent": this.getUserAgent(),
      ...getPlatformHeaders3(),
      ...this.authHeaders(opts)
    };
  }
  /**
   * Override this to add your own headers validation:
   */
  validateHeaders(headers, customHeaders) {
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${uuid43()}`;
  }
  get(path, opts) {
    return this.methodRequest("get", path, opts);
  }
  post(path, opts) {
    return this.methodRequest("post", path, opts);
  }
  patch(path, opts) {
    return this.methodRequest("patch", path, opts);
  }
  put(path, opts) {
    return this.methodRequest("put", path, opts);
  }
  delete(path, opts) {
    return this.methodRequest("delete", path, opts);
  }
  methodRequest(method, path, opts) {
    return this.request(Promise.resolve(opts).then(async (opts2) => {
      const body = opts2 && isBlobLike3(opts2?.body) ? new DataView(await opts2.body.arrayBuffer()) : opts2?.body instanceof DataView ? opts2.body : opts2?.body instanceof ArrayBuffer ? new DataView(opts2.body) : opts2 && ArrayBuffer.isView(opts2?.body) ? new DataView(opts2.body.buffer) : opts2?.body;
      return { method, path, ...opts2, body };
    }));
  }
  getAPIList(path, Page2, opts) {
    return this.requestAPIList(Page2, { method: "get", path, ...opts });
  }
  calculateContentLength(body) {
    if (typeof body === "string") {
      if (typeof Buffer !== "undefined") {
        return Buffer.byteLength(body, "utf8").toString();
      }
      if (typeof TextEncoder !== "undefined") {
        const encoder = new TextEncoder();
        const encoded = encoder.encode(body);
        return encoded.length.toString();
      }
    } else if (ArrayBuffer.isView(body)) {
      return body.byteLength.toString();
    }
    return null;
  }
  buildRequest(options) {
    const { method, path, query, headers = {} } = options;
    const body = ArrayBuffer.isView(options.body) || options.__binaryRequest && typeof options.body === "string" ? options.body : isMultipartBody3(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null;
    const contentLength = this.calculateContentLength(body);
    const url = this.buildURL(path, query);
    if ("timeout" in options)
      validatePositiveInteger3("timeout", options.timeout);
    const timeout = options.timeout ?? this.timeout;
    const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent3(url);
    const minAgentTimeout = timeout + 1e3;
    if (typeof httpAgent?.options?.timeout === "number" && minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
      httpAgent.options.timeout = minAgentTimeout;
    }
    if (this.idempotencyHeader && method !== "get") {
      if (!options.idempotencyKey)
        options.idempotencyKey = this.defaultIdempotencyKey();
      headers[this.idempotencyHeader] = options.idempotencyKey;
    }
    const reqHeaders = this.buildHeaders({ options, headers, contentLength });
    const req = {
      method,
      ...body && { body },
      headers: reqHeaders,
      ...httpAgent && { agent: httpAgent },
      // @ts-ignore node-fetch uses a custom AbortSignal type that is
      // not compatible with standard web types
      signal: options.signal ?? null
    };
    return { req, url, timeout };
  }
  buildHeaders({ options, headers, contentLength }) {
    const reqHeaders = {};
    if (contentLength) {
      reqHeaders["content-length"] = contentLength;
    }
    const defaultHeaders = this.defaultHeaders(options);
    applyHeadersMut3(reqHeaders, defaultHeaders);
    applyHeadersMut3(reqHeaders, headers);
    if (isMultipartBody3(options.body) && kind3 !== "node") {
      delete reqHeaders["content-type"];
    }
    this.validateHeaders(reqHeaders, headers);
    return reqHeaders;
  }
  /**
   * Used as a callback for mutating the given `FinalRequestOptions` object.
   */
  async prepareOptions(options) {
  }
  /**
   * Used as a callback for mutating the given `RequestInit` object.
   *
   * This is useful for cases where you want to add certain headers based off of
   * the request properties, e.g. `method` or `url`.
   */
  async prepareRequest(request, { url, options }) {
  }
  parseHeaders(headers) {
    return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
  }
  makeStatusError(status, error, message, headers) {
    return APIError4.generate(status, error, message, headers);
  }
  request(options, remainingRetries = null) {
    return new APIPromise3(this.makeRequest(options, remainingRetries));
  }
  async makeRequest(optionsInput, retriesRemaining) {
    const options = await optionsInput;
    if (retriesRemaining == null) {
      retriesRemaining = options.maxRetries ?? this.maxRetries;
    }
    await this.prepareOptions(options);
    const { req, url, timeout } = this.buildRequest(options);
    await this.prepareRequest(req, { url, options });
    debug3("request", url, options, req.headers);
    if (options.signal?.aborted) {
      throw new APIUserAbortError4();
    }
    const controller = new AbortController();
    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3);
    if (response instanceof Error) {
      if (options.signal?.aborted) {
        throw new APIUserAbortError4();
      }
      if (retriesRemaining) {
        return this.retryRequest(options, retriesRemaining);
      }
      if (response.name === "AbortError") {
        throw new APIConnectionTimeoutError4();
      }
      throw new APIConnectionError4({ cause: response });
    }
    const responseHeaders = createResponseHeaders3(response.headers);
    if (!response.ok) {
      if (retriesRemaining && this.shouldRetry(response)) {
        const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
        debug3(`response (error; ${retryMessage2})`, response.status, url, responseHeaders);
        return this.retryRequest(options, retriesRemaining, responseHeaders);
      }
      const errText = await response.text().catch((e3) => castToError3(e3).message);
      const errJSON = safeJSON3(errText);
      const errMessage = errJSON ? void 0 : errText;
      const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
      debug3(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
      const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
      throw err;
    }
    return { response, options, controller };
  }
  requestAPIList(Page2, options) {
    const request = this.makeRequest(options, null);
    return new PagePromise3(this, request, Page2);
  }
  buildURL(path, query) {
    const url = isAbsoluteURL3(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path));
    const defaultQuery = this.defaultQuery();
    if (!isEmptyObj4(defaultQuery)) {
      query = { ...defaultQuery, ...query };
    }
    if (typeof query === "object" && query && !Array.isArray(query)) {
      url.search = this.stringifyQuery(query);
    }
    return url.toString();
  }
  stringifyQuery(query) {
    return Object.entries(query).filter(([_2, value]) => typeof value !== "undefined").map(([key, value]) => {
      if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }
      if (value === null) {
        return `${encodeURIComponent(key)}=`;
      }
      throw new GroqError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
    }).join("&");
  }
  async fetchWithTimeout(url, init, ms, controller) {
    const { signal, ...options } = init || {};
    if (signal)
      signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => {
      clearTimeout(timeout);
    });
  }
  getRequestClient() {
    return { fetch: this.fetch };
  }
  shouldRetry(response) {
    const shouldRetryHeader = response.headers.get("x-should-retry");
    if (shouldRetryHeader === "true")
      return true;
    if (shouldRetryHeader === "false")
      return false;
    if (response.status === 408)
      return true;
    if (response.status === 409)
      return true;
    if (response.status === 429)
      return true;
    if (response.status >= 500)
      return true;
    return false;
  }
  async retryRequest(options, retriesRemaining, responseHeaders) {
    let timeoutMillis;
    const retryAfterMillisHeader = responseHeaders?.["retry-after-ms"];
    if (retryAfterMillisHeader) {
      const timeoutMs = parseFloat(retryAfterMillisHeader);
      if (!Number.isNaN(timeoutMs)) {
        timeoutMillis = timeoutMs;
      }
    }
    const retryAfterHeader = responseHeaders?.["retry-after"];
    if (retryAfterHeader && !timeoutMillis) {
      const timeoutSeconds = parseFloat(retryAfterHeader);
      if (!Number.isNaN(timeoutSeconds)) {
        timeoutMillis = timeoutSeconds * 1e3;
      } else {
        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
      }
    }
    if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) {
      const maxRetries = options.maxRetries ?? this.maxRetries;
      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
    }
    await sleep3(timeoutMillis);
    return this.makeRequest(options, retriesRemaining - 1);
  }
  calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
    const initialRetryDelay = 0.5;
    const maxRetryDelay = 8;
    const numRetries = maxRetries - retriesRemaining;
    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
    const jitter = 1 - Math.random() * 0.25;
    return sleepSeconds * jitter * 1e3;
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${VERSION3}`;
  }
};
var AbstractPage3 = class {
  constructor(client2, response, body, options) {
    _AbstractPage_client3.set(this, void 0);
    __classPrivateFieldSet13(this, _AbstractPage_client3, client2, "f");
    this.options = options;
    this.response = response;
    this.body = body;
  }
  hasNextPage() {
    const items = this.getPaginatedItems();
    if (!items.length)
      return false;
    return this.nextPageInfo() != null;
  }
  async getNextPage() {
    const nextInfo = this.nextPageInfo();
    if (!nextInfo) {
      throw new GroqError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    }
    const nextOptions = { ...this.options };
    if ("params" in nextInfo && typeof nextOptions.query === "object") {
      nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
    } else if ("url" in nextInfo) {
      const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
      for (const [key, value] of params) {
        nextInfo.url.searchParams.set(key, value);
      }
      nextOptions.query = void 0;
      nextOptions.path = nextInfo.url.toString();
    }
    return await __classPrivateFieldGet14(this, _AbstractPage_client3, "f").requestAPIList(this.constructor, nextOptions);
  }
  async *iterPages() {
    let page = this;
    yield page;
    while (page.hasNextPage()) {
      page = await page.getNextPage();
      yield page;
    }
  }
  async *[(_AbstractPage_client3 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (const page of this.iterPages()) {
      for (const item of page.getPaginatedItems()) {
        yield item;
      }
    }
  }
};
var PagePromise3 = class extends APIPromise3 {
  constructor(client2, request, Page2) {
    super(request, async (props) => new Page2(client2, props.response, await defaultParseResponse3(props), props.options));
  }
  /**
   * Allow auto-paginating iteration on an unawaited list call, eg:
   *
   *    for await (const item of client.items.list()) {
   *      console.log(item)
   *    }
   */
  async *[Symbol.asyncIterator]() {
    const page = await this;
    for await (const item of page) {
      yield item;
    }
  }
};
var createResponseHeaders3 = (headers) => {
  return new Proxy(Object.fromEntries(
    // @ts-ignore
    headers.entries()
  ), {
    get(target, name) {
      const key = name.toString();
      return target[key.toLowerCase()] || target[key];
    }
  });
};
var getPlatformProperties3 = () => {
  if (typeof Deno !== "undefined" && Deno.build != null) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION3,
      "X-Stainless-OS": normalizePlatform3(Deno.build.os),
      "X-Stainless-Arch": normalizeArch3(Deno.build.arch),
      "X-Stainless-Runtime": "deno",
      "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
    };
  }
  if (typeof EdgeRuntime !== "undefined") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION3,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": `other:${EdgeRuntime}`,
      "X-Stainless-Runtime": "edge",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION3,
      "X-Stainless-OS": normalizePlatform3(process.platform),
      "X-Stainless-Arch": normalizeArch3(process.arch),
      "X-Stainless-Runtime": "node",
      "X-Stainless-Runtime-Version": process.version
    };
  }
  const browserInfo = getBrowserInfo3();
  if (browserInfo) {
    return {
      "X-Stainless-Lang": "js",
      "X-Stainless-Package-Version": VERSION3,
      "X-Stainless-OS": "Unknown",
      "X-Stainless-Arch": "unknown",
      "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
      "X-Stainless-Runtime-Version": browserInfo.version
    };
  }
  return {
    "X-Stainless-Lang": "js",
    "X-Stainless-Package-Version": VERSION3,
    "X-Stainless-OS": "Unknown",
    "X-Stainless-Arch": "unknown",
    "X-Stainless-Runtime": "unknown",
    "X-Stainless-Runtime-Version": "unknown"
  };
};
function getBrowserInfo3() {
  if (typeof navigator === "undefined" || !navigator) {
    return null;
  }
  const browserPatterns = [
    { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
    { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
  ];
  for (const { key, pattern } of browserPatterns) {
    const match2 = pattern.exec(navigator.userAgent);
    if (match2) {
      const major = match2[1] || 0;
      const minor = match2[2] || 0;
      const patch = match2[3] || 0;
      return { browser: key, version: `${major}.${minor}.${patch}` };
    }
  }
  return null;
}
var normalizeArch3 = (arch) => {
  if (arch === "x32")
    return "x32";
  if (arch === "x86_64" || arch === "x64")
    return "x64";
  if (arch === "arm")
    return "arm";
  if (arch === "aarch64" || arch === "arm64")
    return "arm64";
  if (arch)
    return `other:${arch}`;
  return "unknown";
};
var normalizePlatform3 = (platform2) => {
  platform2 = platform2.toLowerCase();
  if (platform2.includes("ios"))
    return "iOS";
  if (platform2 === "android")
    return "Android";
  if (platform2 === "darwin")
    return "MacOS";
  if (platform2 === "win32")
    return "Windows";
  if (platform2 === "freebsd")
    return "FreeBSD";
  if (platform2 === "openbsd")
    return "OpenBSD";
  if (platform2 === "linux")
    return "Linux";
  if (platform2)
    return `Other:${platform2}`;
  return "Unknown";
};
var _platformHeaders3;
var getPlatformHeaders3 = () => {
  return _platformHeaders3 ?? (_platformHeaders3 = getPlatformProperties3());
};
var safeJSON3 = (text) => {
  try {
    return JSON.parse(text);
  } catch (err) {
    return void 0;
  }
};
var startsWithSchemeRegexp3 = new RegExp("^(?:[a-z]+:)?//", "i");
var isAbsoluteURL3 = (url) => {
  return startsWithSchemeRegexp3.test(url);
};
var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
var validatePositiveInteger3 = (name, n4) => {
  if (typeof n4 !== "number" || !Number.isInteger(n4)) {
    throw new GroqError(`${name} must be an integer`);
  }
  if (n4 < 0) {
    throw new GroqError(`${name} must be a positive integer`);
  }
  return n4;
};
var castToError3 = (err) => {
  if (err instanceof Error)
    return err;
  return new Error(err);
};
var readEnv3 = (env) => {
  if (typeof process !== "undefined") {
    return process.env?.[env]?.trim() ?? void 0;
  }
  if (typeof Deno !== "undefined") {
    return Deno.env?.get?.(env)?.trim();
  }
  return void 0;
};
function isEmptyObj4(obj) {
  if (!obj)
    return true;
  for (const _k in obj)
    return false;
  return true;
}
function hasOwn3(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}
function applyHeadersMut3(targetHeaders, newHeaders) {
  for (const k3 in newHeaders) {
    if (!hasOwn3(newHeaders, k3))
      continue;
    const lowerKey = k3.toLowerCase();
    if (!lowerKey)
      continue;
    const val2 = newHeaders[k3];
    if (val2 === null) {
      delete targetHeaders[lowerKey];
    } else if (val2 !== void 0) {
      targetHeaders[lowerKey] = val2;
    }
  }
}
function debug3(action, ...args) {
  if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
    console.log(`Groq:DEBUG:${action}`, ...args);
  }
}
var uuid43 = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c4) => {
    const r4 = Math.random() * 16 | 0;
    const v5 = c4 === "x" ? r4 : r4 & 3 | 8;
    return v5.toString(16);
  });
};
var isRunningInBrowser3 = () => {
  return (
    // @ts-ignore
    typeof window !== "undefined" && // @ts-ignore
    typeof window.document !== "undefined" && // @ts-ignore
    typeof navigator !== "undefined"
  );
};

// node_modules/groq-sdk/resource.mjs
var APIResource3 = class {
  constructor(client2) {
    this._client = client2;
  }
};

// node_modules/groq-sdk/resources/audio/transcriptions.mjs
var Transcriptions2 = class extends APIResource3 {
  /**
   * Transcribes audio into the input language.
   */
  create(body, options) {
    return this._client.post("/openai/v1/audio/transcriptions", multipartFormRequestOptions2({ body, ...options }));
  }
};
(function(Transcriptions3) {
})(Transcriptions2 || (Transcriptions2 = {}));

// node_modules/groq-sdk/resources/audio/translations.mjs
var Translations2 = class extends APIResource3 {
  /**
   * Translates audio into English.
   */
  create(body, options) {
    return this._client.post("/openai/v1/audio/translations", multipartFormRequestOptions2({ body, ...options }));
  }
};
(function(Translations3) {
})(Translations2 || (Translations2 = {}));

// node_modules/groq-sdk/resources/audio/audio.mjs
var Audio2 = class extends APIResource3 {
  constructor() {
    super(...arguments);
    this.transcriptions = new Transcriptions2(this._client);
    this.translations = new Translations2(this._client);
  }
};
(function(Audio3) {
  Audio3.Transcriptions = Transcriptions2;
  Audio3.Translations = Translations2;
})(Audio2 || (Audio2 = {}));

// node_modules/groq-sdk/resources/chat/completions.mjs
var Completions5 = class extends APIResource3 {
  create(body, options) {
    return this._client.post("/openai/v1/chat/completions", {
      body,
      ...options,
      stream: body.stream ?? false
    });
  }
};
(function(Completions7) {
})(Completions5 || (Completions5 = {}));

// node_modules/groq-sdk/resources/chat/chat.mjs
var Chat3 = class extends APIResource3 {
  constructor() {
    super(...arguments);
    this.completions = new Completions5(this._client);
  }
};
(function(Chat5) {
  Chat5.Completions = Completions5;
})(Chat3 || (Chat3 = {}));

// node_modules/groq-sdk/resources/completions.mjs
var Completions6 = class extends APIResource3 {
};
(function(Completions7) {
})(Completions6 || (Completions6 = {}));

// node_modules/groq-sdk/resources/embeddings.mjs
var Embeddings3 = class extends APIResource3 {
  /**
   * Creates an embedding vector representing the input text.
   */
  create(body, options) {
    return this._client.post("/openai/v1/embeddings", { body, ...options });
  }
};
(function(Embeddings4) {
})(Embeddings3 || (Embeddings3 = {}));

// node_modules/groq-sdk/resources/models.mjs
var Models2 = class extends APIResource3 {
  /**
   * Get a specific model
   */
  retrieve(model, options) {
    return this._client.get(`/openai/v1/models/${model}`, options);
  }
  /**
   * get all available models
   */
  list(options) {
    return this._client.get("/openai/v1/models", options);
  }
  /**
   * Delete a model
   */
  delete(model, options) {
    return this._client.delete(`/openai/v1/models/${model}`, options);
  }
};
(function(Models3) {
})(Models2 || (Models2 = {}));

// node_modules/groq-sdk/index.mjs
var _a4;
var Groq = class extends APIClient3 {
  /**
   * API Client for interfacing with the Groq API.
   *
   * @param {string | undefined} [opts.apiKey=process.env['GROQ_API_KEY'] ?? undefined]
   * @param {string} [opts.baseURL=process.env['GROQ_BASE_URL'] ?? https://api.groq.com] - Override the default base URL for the API.
   * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
   * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
   * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
   * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
   * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
   * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
   */
  constructor({ baseURL = readEnv3("GROQ_BASE_URL"), apiKey = readEnv3("GROQ_API_KEY"), ...opts } = {}) {
    if (apiKey === void 0) {
      throw new GroqError("The GROQ_API_KEY environment variable is missing or empty; either provide it, or instantiate the Groq client with an apiKey option, like new Groq({ apiKey: 'My API Key' }).");
    }
    const options = {
      apiKey,
      ...opts,
      baseURL: baseURL || `https://api.groq.com`
    };
    if (!options.dangerouslyAllowBrowser && isRunningInBrowser3()) {
      throw new GroqError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Groq({ apiKey, dangerouslyAllowBrowser: true })");
    }
    super({
      baseURL: options.baseURL,
      timeout: options.timeout ?? 6e4,
      httpAgent: options.httpAgent,
      maxRetries: options.maxRetries,
      fetch: options.fetch
    });
    this.completions = new Completions6(this);
    this.chat = new Chat3(this);
    this.embeddings = new Embeddings3(this);
    this.audio = new Audio2(this);
    this.models = new Models2(this);
    this._options = options;
    this.apiKey = apiKey;
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  defaultHeaders(opts) {
    return {
      ...super.defaultHeaders(opts),
      ...this._options.defaultHeaders
    };
  }
  authHeaders(opts) {
    return { Authorization: `Bearer ${this.apiKey}` };
  }
};
_a4 = Groq;
Groq.Groq = _a4;
Groq.GroqError = GroqError;
Groq.APIError = APIError4;
Groq.APIConnectionError = APIConnectionError4;
Groq.APIConnectionTimeoutError = APIConnectionTimeoutError4;
Groq.APIUserAbortError = APIUserAbortError4;
Groq.NotFoundError = NotFoundError4;
Groq.ConflictError = ConflictError4;
Groq.RateLimitError = RateLimitError4;
Groq.BadRequestError = BadRequestError4;
Groq.AuthenticationError = AuthenticationError4;
Groq.InternalServerError = InternalServerError4;
Groq.PermissionDeniedError = PermissionDeniedError4;
Groq.UnprocessableEntityError = UnprocessableEntityError4;
Groq.toFile = toFile3;
Groq.fileFromPath = fileFromPath3;
var { GroqError: GroqError2, APIError: APIError5, APIConnectionError: APIConnectionError5, APIConnectionTimeoutError: APIConnectionTimeoutError5, APIUserAbortError: APIUserAbortError5, NotFoundError: NotFoundError5, ConflictError: ConflictError5, RateLimitError: RateLimitError5, BadRequestError: BadRequestError5, AuthenticationError: AuthenticationError5, InternalServerError: InternalServerError5, PermissionDeniedError: PermissionDeniedError5, UnprocessableEntityError: UnprocessableEntityError5 } = error_exports3;
(function(Groq2) {
  Groq2.Completions = Completions6;
  Groq2.Chat = Chat3;
  Groq2.Embeddings = Embeddings3;
  Groq2.Audio = Audio2;
  Groq2.Models = Models2;
})(Groq || (Groq = {}));
var groq_sdk_default = Groq;

// node_modules/@langchain/groq/dist/chat_models.js
init_runnables2();
init_output_parsers2();
function messageToGroqRole(message) {
  const type = message._getType();
  switch (type) {
    case "system":
      return "system";
    case "ai":
      return "assistant";
    case "human":
      return "user";
    case "function":
      return "function";
    case "tool":
      return "tool";
    default:
      throw new Error(`Unknown message type: ${type}`);
  }
}
function convertMessagesToGroqParams(messages) {
  return messages.map((message) => {
    if (typeof message.content !== "string") {
      throw new Error("Non string message content not supported");
    }
    const completionParam = {
      role: messageToGroqRole(message),
      content: message.content,
      name: message.name,
      function_call: message.additional_kwargs.function_call,
      tool_calls: message.additional_kwargs.tool_calls,
      tool_call_id: message.tool_call_id
    };
    if (isAIMessage(message) && !!message.tool_calls?.length) {
      completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI);
    } else {
      if (message.additional_kwargs.tool_calls != null) {
        completionParam.tool_calls = message.additional_kwargs.tool_calls;
      }
      if (message.tool_call_id != null) {
        completionParam.tool_call_id = message.tool_call_id;
      }
    }
    return completionParam;
  });
}
function groqResponseToChatMessage(message, usageMetadata) {
  const rawToolCalls = message.tool_calls;
  switch (message.role) {
    case "assistant": {
      const toolCalls = [];
      const invalidToolCalls = [];
      for (const rawToolCall of rawToolCalls ?? []) {
        try {
          toolCalls.push(parseToolCall2(rawToolCall, { returnId: true }));
        } catch (e3) {
          invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e3.message));
        }
      }
      return new AIMessage({
        content: message.content || "",
        additional_kwargs: { tool_calls: rawToolCalls },
        tool_calls: toolCalls,
        invalid_tool_calls: invalidToolCalls,
        usage_metadata: usageMetadata
      });
    }
    default:
      return new ChatMessage(message.content || "", message.role ?? "unknown");
  }
}
function _convertDeltaToolCallToToolCallChunk(toolCalls, index2) {
  if (!toolCalls?.length)
    return void 0;
  return toolCalls.map((tc) => ({
    id: tc.id,
    name: tc.function?.name,
    args: tc.function?.arguments,
    type: "tool_call_chunk",
    index: index2
  }));
}
function _convertDeltaToMessageChunk2(delta, index2, xGroq) {
  const { role } = delta;
  const content = delta.content ?? "";
  let additional_kwargs;
  if (delta.function_call) {
    additional_kwargs = {
      function_call: delta.function_call
    };
  } else if (delta.tool_calls) {
    additional_kwargs = {
      tool_calls: delta.tool_calls
    };
  } else {
    additional_kwargs = {};
  }
  let usageMetadata;
  let groqMessageId;
  if (xGroq?.usage) {
    usageMetadata = {
      input_tokens: xGroq.usage.prompt_tokens,
      output_tokens: xGroq.usage.completion_tokens,
      total_tokens: xGroq.usage.total_tokens
    };
    groqMessageId = xGroq.id;
  }
  if (role === "user") {
    return {
      message: new HumanMessageChunk({ content })
    };
  } else if (role === "assistant") {
    const toolCallChunks = _convertDeltaToolCallToToolCallChunk(delta.tool_calls, index2);
    return {
      message: new AIMessageChunk({
        content,
        additional_kwargs,
        tool_call_chunks: toolCallChunks ? toolCallChunks.map((tc) => ({
          type: tc.type,
          args: tc.args,
          index: tc.index
        })) : void 0,
        usage_metadata: usageMetadata,
        id: groqMessageId
      }),
      toolCallData: toolCallChunks ? toolCallChunks.map((tc) => ({
        id: tc.id ?? "",
        name: tc.name ?? "",
        index: tc.index ?? index2,
        type: "tool_call_chunk"
      })) : void 0
    };
  } else if (role === "system") {
    return {
      message: new SystemMessageChunk({ content })
    };
  } else {
    return {
      message: new ChatMessageChunk({ content, role })
    };
  }
}
var ChatGroq = class extends BaseChatModel {
  static lc_name() {
    return "ChatGroq";
  }
  _llmType() {
    return "groq";
  }
  get lc_secrets() {
    return {
      apiKey: "GROQ_API_KEY"
    };
  }
  constructor(fields) {
    super(fields ?? {});
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "chat_models", "groq"]
    });
    Object.defineProperty(this, "client", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "modelName", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "mixtral-8x7b-32768"
    });
    Object.defineProperty(this, "model", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "mixtral-8x7b-32768"
    });
    Object.defineProperty(this, "temperature", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 0.7
    });
    Object.defineProperty(this, "stop", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "stopSequences", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "maxTokens", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "streaming", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "apiKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "lc_serializable", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: true
    });
    const apiKey = fields?.apiKey || getEnvironmentVariable2("GROQ_API_KEY");
    if (!apiKey) {
      throw new Error(`Groq API key not found. Please set the GROQ_API_KEY environment variable or provide the key into "apiKey"`);
    }
    this.client = new groq_sdk_default({
      apiKey,
      dangerouslyAllowBrowser: true
    });
    this.apiKey = apiKey;
    this.temperature = fields?.temperature ?? this.temperature;
    this.modelName = fields?.model ?? fields?.modelName ?? this.model;
    this.model = this.modelName;
    this.streaming = fields?.streaming ?? this.streaming;
    this.stop = fields?.stopSequences ?? (typeof fields?.stop === "string" ? [fields.stop] : fields?.stop) ?? [];
    this.stopSequences = this.stop;
    this.maxTokens = fields?.maxTokens;
  }
  getLsParams(options) {
    const params = this.invocationParams(options);
    return {
      ls_provider: "groq",
      ls_model_name: this.model,
      ls_model_type: "chat",
      ls_temperature: params.temperature ?? this.temperature,
      ls_max_tokens: params.max_tokens ?? this.maxTokens,
      ls_stop: options.stop
    };
  }
  async completionWithRetry(request, options) {
    return this.caller.call(async () => this.client.chat.completions.create(request, options));
  }
  invocationParams(options) {
    const params = super.invocationParams(options);
    if (options.tool_choice !== void 0) {
      params.tool_choice = options.tool_choice;
    }
    if (options.tools !== void 0) {
      params.tools = options.tools;
    }
    if (options.response_format !== void 0) {
      params.response_format = options.response_format;
    }
    return {
      ...params,
      stop: options.stop ?? this.stopSequences,
      model: this.model,
      temperature: this.temperature,
      max_tokens: this.maxTokens
    };
  }
  bindTools(tools, kwargs) {
    return this.bind({
      tools: tools.map((tool2) => convertToOpenAITool(tool2)),
      ...kwargs
    });
  }
  async *_streamResponseChunks(messages, options, runManager) {
    const params = this.invocationParams(options);
    const messagesMapped = convertMessagesToGroqParams(messages);
    const response = await this.completionWithRetry({
      ...params,
      messages: messagesMapped,
      stream: true
    }, {
      signal: options?.signal,
      headers: options?.headers
    });
    let role = "";
    const toolCall = [];
    let responseMetadata;
    for await (const data of response) {
      responseMetadata = data;
      const choice = data?.choices[0];
      if (!choice) {
        continue;
      }
      if (choice.delta?.role) {
        role = choice.delta.role;
      }
      const { message, toolCallData } = _convertDeltaToMessageChunk2({
        ...choice.delta,
        role
      }, choice.index, data.x_groq);
      if (toolCallData) {
        const newToolCallData = toolCallData.filter((tc) => toolCall.every((t3) => t3.id !== tc.id));
        toolCall.push(...newToolCallData);
        yield new ChatGenerationChunk({
          message: new AIMessageChunk({
            content: "",
            tool_call_chunks: newToolCallData
          }),
          text: ""
        });
      }
      const chunk = new ChatGenerationChunk({
        message,
        text: choice.delta.content ?? "",
        generationInfo: {
          finishReason: choice.finish_reason
        }
      });
      yield chunk;
      void runManager?.handleLLMNewToken(chunk.text ?? "");
    }
    if (responseMetadata) {
      if ("choices" in responseMetadata) {
        delete responseMetadata.choices;
      }
      yield new ChatGenerationChunk({
        message: new AIMessageChunk({
          content: "",
          response_metadata: responseMetadata
        }),
        text: ""
      });
    }
    if (options.signal?.aborted) {
      throw new Error("AbortError");
    }
  }
  async _generate(messages, options, runManager) {
    if (this.streaming) {
      const tokenUsage = {};
      const stream = this._streamResponseChunks(messages, options, runManager);
      const finalChunks = {};
      for await (const chunk of stream) {
        const index2 = chunk.generationInfo?.completion ?? 0;
        if (finalChunks[index2] === void 0) {
          finalChunks[index2] = chunk;
        } else {
          finalChunks[index2] = finalChunks[index2].concat(chunk);
        }
      }
      const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_2, value]) => value);
      return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
    } else {
      return this._generateNonStreaming(messages, options, runManager);
    }
  }
  async _generateNonStreaming(messages, options, _runManager) {
    const tokenUsage = {};
    const params = this.invocationParams(options);
    const messagesMapped = convertMessagesToGroqParams(messages);
    const data = await this.completionWithRetry({
      ...params,
      stream: false,
      messages: messagesMapped
    }, {
      signal: options?.signal,
      headers: options?.headers
    });
    if ("usage" in data && data.usage) {
      const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage;
      if (completionTokens) {
        tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens;
      }
      if (promptTokens) {
        tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;
      }
      if (totalTokens) {
        tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;
      }
    }
    const generations = [];
    if ("choices" in data && data.choices) {
      for (const part of data.choices) {
        const text = part.message?.content ?? "";
        let usageMetadata;
        if (tokenUsage.totalTokens !== void 0) {
          usageMetadata = {
            input_tokens: tokenUsage.promptTokens ?? 0,
            output_tokens: tokenUsage.completionTokens ?? 0,
            total_tokens: tokenUsage.totalTokens
          };
        }
        const generation = {
          text,
          message: groqResponseToChatMessage(part.message ?? { role: "assistant" }, usageMetadata)
        };
        generation.generationInfo = {
          ...part.finish_reason ? { finish_reason: part.finish_reason } : {},
          ...part.logprobs ? { logprobs: part.logprobs } : {}
        };
        generations.push(generation);
      }
    }
    return {
      generations,
      llmOutput: { tokenUsage }
    };
  }
  withStructuredOutput(outputSchema, config) {
    const schema = outputSchema;
    const name = config?.name;
    const method = config?.method;
    const includeRaw = config?.includeRaw;
    let functionName = name ?? "extract";
    let outputParser;
    let llm;
    if (method === "jsonMode") {
      llm = this.bind({
        response_format: { type: "json_object" }
      });
      if (isZodSchema(schema)) {
        outputParser = StructuredOutputParser.fromZodSchema(schema);
      } else {
        outputParser = new JsonOutputParser();
      }
    } else {
      if (isZodSchema(schema)) {
        const asJsonSchema = zodToJsonSchema(schema);
        llm = this.bind({
          tools: [
            {
              type: "function",
              function: {
                name: functionName,
                description: asJsonSchema.description,
                parameters: asJsonSchema
              }
            }
          ],
          tool_choice: {
            type: "function",
            function: {
              name: functionName
            }
          }
        });
        outputParser = new JsonOutputKeyToolsParser({
          returnSingle: true,
          keyName: functionName,
          zodSchema: schema
        });
      } else {
        let openAIFunctionDefinition;
        if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
          openAIFunctionDefinition = schema;
          functionName = schema.name;
        } else {
          functionName = schema.title ?? functionName;
          openAIFunctionDefinition = {
            name: functionName,
            description: schema.description ?? "",
            parameters: schema
          };
        }
        llm = this.bind({
          tools: [
            {
              type: "function",
              function: openAIFunctionDefinition
            }
          ],
          tool_choice: {
            type: "function",
            function: {
              name: functionName
            }
          }
        });
        outputParser = new JsonOutputKeyToolsParser({
          returnSingle: true,
          keyName: functionName
        });
      }
    }
    if (!includeRaw) {
      return llm.pipe(outputParser).withConfig({
        runName: "ChatGroqStructuredOutput"
      });
    }
    const parserAssign = RunnablePassthrough.assign({
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      parsed: (input, config2) => outputParser.invoke(input.raw, config2)
    });
    const parserNone = RunnablePassthrough.assign({
      parsed: () => null
    });
    const parsedWithFallback = parserAssign.withFallbacks({
      fallbacks: [parserNone]
    });
    return RunnableSequence.from([
      {
        raw: llm
      },
      parsedWithFallback
    ]).withConfig({
      runName: "ChatGroqStructuredOutput"
    });
  }
};

// src/LLMProviders/chatModelManager.ts
var import_obsidian11 = require("obsidian");
var CHAT_PROVIDER_CONSTRUCTORS = {
  ["openai" /* OPENAI */]: ChatOpenAI,
  ["azure openai" /* AZURE_OPENAI */]: ChatOpenAI,
  ["anthropic" /* ANTHROPIC */]: ChatAnthropic,
  ["cohereai" /* COHEREAI */]: ChatCohere,
  ["google" /* GOOGLE */]: ChatGoogleGenerativeAI,
  ["openrouterai" /* OPENROUTERAI */]: ChatOpenAI,
  ["ollama" /* OLLAMA */]: ChatOllama,
  ["lm-studio" /* LM_STUDIO */]: ChatOpenAI,
  ["groq" /* GROQ */]: ChatGroq,
  ["3rd party (openai-format)" /* OPENAI_FORMAT */]: ChatOpenAI,
  ["copilot-plus" /* COPILOT_PLUS */]: ChatOpenAI
};
var ChatModelManager = class {
  constructor() {
    this.providerApiKeyMap = {
      ["openai" /* OPENAI */]: () => getSettings().openAIApiKey,
      ["google" /* GOOGLE */]: () => getSettings().googleApiKey,
      ["azure openai" /* AZURE_OPENAI */]: () => getSettings().azureOpenAIApiKey,
      ["anthropic" /* ANTHROPIC */]: () => getSettings().anthropicApiKey,
      ["cohereai" /* COHEREAI */]: () => getSettings().cohereApiKey,
      ["openrouterai" /* OPENROUTERAI */]: () => getSettings().openRouterAiApiKey,
      ["groq" /* GROQ */]: () => getSettings().groqApiKey,
      ["ollama" /* OLLAMA */]: () => "default-key",
      ["lm-studio" /* LM_STUDIO */]: () => "default-key",
      ["3rd party (openai-format)" /* OPENAI_FORMAT */]: () => "default-key",
      ["copilot-plus" /* COPILOT_PLUS */]: () => getSettings().plusLicenseKey
    };
    this.buildModelMap();
    subscribeToSettingsChange(() => {
      this.buildModelMap();
      this.validateCurrentModel();
    });
  }
  static getInstance() {
    if (!ChatModelManager.instance) {
      ChatModelManager.instance = new ChatModelManager();
    }
    return ChatModelManager.instance;
  }
  async getModelConfig(customModel) {
    const settings = getSettings();
    const modelName = customModel.name;
    const isO1Model = modelName.startsWith("o1");
    const baseConfig = {
      modelName,
      temperature: customModel.temperature ?? settings.temperature,
      streaming: customModel.stream ?? true,
      maxRetries: 3,
      maxConcurrency: 3,
      enableCors: customModel.enableCors
    };
    const providerConfig = {
      ["openai" /* OPENAI */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || settings.openAIApiKey),
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0
        },
        // @ts-ignore
        openAIOrgId: getDecryptedKey(customModel.openAIOrgId || settings.openAIOrgId),
        ...this.handleOpenAIExtraArgs(isO1Model, settings.maxTokens, settings.temperature)
      },
      ["anthropic" /* ANTHROPIC */]: {
        anthropicApiKey: await getDecryptedKey(customModel.apiKey || settings.anthropicApiKey),
        modelName,
        anthropicApiUrl: customModel.baseUrl,
        clientOptions: {
          // Required to bypass CORS restrictions
          defaultHeaders: { "anthropic-dangerous-direct-browser-access": "true" },
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["azure openai" /* AZURE_OPENAI */]: {
        azureOpenAIApiKey: await getDecryptedKey(customModel.apiKey || settings.azureOpenAIApiKey),
        azureOpenAIApiInstanceName: customModel.azureOpenAIApiInstanceName || settings.azureOpenAIApiInstanceName,
        azureOpenAIApiDeploymentName: customModel.azureOpenAIApiDeploymentName || settings.azureOpenAIApiDeploymentName,
        azureOpenAIApiVersion: customModel.azureOpenAIApiVersion || settings.azureOpenAIApiVersion,
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0
        },
        ...this.handleOpenAIExtraArgs(isO1Model, settings.maxTokens, settings.temperature)
      },
      ["cohereai" /* COHEREAI */]: {
        apiKey: await getDecryptedKey(customModel.apiKey || settings.cohereApiKey),
        model: modelName
      },
      ["google" /* GOOGLE */]: {
        apiKey: await getDecryptedKey(customModel.apiKey || settings.googleApiKey),
        modelName,
        safetySettings: [
          {
            category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
            threshold: HarmBlockThreshold.BLOCK_NONE
          },
          {
            category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
            threshold: HarmBlockThreshold.BLOCK_NONE
          },
          {
            category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
            threshold: HarmBlockThreshold.BLOCK_NONE
          },
          {
            category: HarmCategory.HARM_CATEGORY_HARASSMENT,
            threshold: HarmBlockThreshold.BLOCK_NONE
          }
        ],
        baseUrl: customModel.baseUrl
      },
      ["openrouterai" /* OPENROUTERAI */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || settings.openRouterAiApiKey),
        configuration: {
          baseURL: customModel.baseUrl || "https://openrouter.ai/api/v1",
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["groq" /* GROQ */]: {
        apiKey: await getDecryptedKey(customModel.apiKey || settings.groqApiKey),
        modelName
      },
      ["ollama" /* OLLAMA */]: {
        // ChatOllama has `model` instead of `modelName`!!
        model: modelName,
        // @ts-ignore
        apiKey: customModel.apiKey || "default-key",
        // MUST NOT use /v1 in the baseUrl for ollama
        baseUrl: customModel.baseUrl || "http://localhost:11434"
      },
      ["lm-studio" /* LM_STUDIO */]: {
        modelName,
        openAIApiKey: customModel.apiKey || "default-key",
        configuration: {
          baseURL: customModel.baseUrl || "http://localhost:1234/v1",
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      },
      ["3rd party (openai-format)" /* OPENAI_FORMAT */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(customModel.apiKey || settings.openAIApiKey),
        configuration: {
          baseURL: customModel.baseUrl,
          fetch: customModel.enableCors ? safeFetch : void 0,
          dangerouslyAllowBrowser: true
        },
        ...this.handleOpenAIExtraArgs(isO1Model, settings.maxTokens, settings.temperature)
      },
      ["copilot-plus" /* COPILOT_PLUS */]: {
        modelName,
        openAIApiKey: await getDecryptedKey(settings.plusLicenseKey),
        configuration: {
          baseURL: BREVILABS_API_BASE_URL,
          fetch: customModel.enableCors ? safeFetch : void 0
        }
      }
    };
    const selectedProviderConfig = providerConfig[customModel.provider] || {};
    return { ...baseConfig, ...selectedProviderConfig };
  }
  handleOpenAIExtraArgs(isO1Model, maxTokens, temperature) {
    return isO1Model ? {
      maxCompletionTokens: maxTokens,
      temperature: 1
    } : {
      maxTokens,
      temperature
    };
  }
  // Build a map of modelKey to model config
  buildModelMap() {
    const activeModels = getSettings().activeModels;
    ChatModelManager.modelMap = {};
    const modelMap = ChatModelManager.modelMap;
    const allModels = activeModels ?? BUILTIN_CHAT_MODELS;
    allModels.forEach((model) => {
      if (model.enabled) {
        if (!Object.values(ChatModelProviders).contains(model.provider)) {
          console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`);
          return;
        }
        const constructor = this.getProviderConstructor(model);
        const getDefaultApiKey = this.providerApiKeyMap[model.provider];
        const apiKey = model.apiKey || getDefaultApiKey();
        const modelKey = getModelKeyFromModel(model);
        modelMap[modelKey] = {
          hasApiKey: Boolean(model.apiKey || apiKey),
          AIConstructor: constructor,
          vendor: model.provider
        };
      }
    });
  }
  getProviderConstructor(model) {
    const constructor = CHAT_PROVIDER_CONSTRUCTORS[model.provider];
    if (!constructor) {
      console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`);
      throw new Error(`Unknown provider: ${model.provider} for model: ${model.name}`);
    }
    return constructor;
  }
  getChatModel() {
    if (!ChatModelManager.chatModel) {
      throw new Error("No valid chat model available. Please check your API key settings.");
    }
    return ChatModelManager.chatModel;
  }
  async setChatModel(model) {
    const modelKey = getModelKeyFromModel(model);
    setModelKey(modelKey);
    if (!ChatModelManager.modelMap.hasOwnProperty(modelKey)) {
      throw new Error(`No model found for: ${modelKey}`);
    }
    const selectedModel = ChatModelManager.modelMap[modelKey];
    if (!selectedModel.hasApiKey) {
      const errorMessage = `API key is not provided for the model: ${modelKey}. Model switch failed.`;
      new import_obsidian11.Notice(errorMessage);
      throw new Error(errorMessage);
    }
    const modelConfig = await this.getModelConfig(model);
    try {
      const newModelInstance = new selectedModel.AIConstructor({
        ...modelConfig
      });
      ChatModelManager.chatModel = newModelInstance;
    } catch (error) {
      console.error(error);
      new import_obsidian11.Notice(`Error creating model: ${modelKey}`);
    }
  }
  validateChatModel(chatModel) {
    if (chatModel === void 0 || chatModel === null) {
      return false;
    }
    return true;
  }
  async countTokens(inputStr) {
    return ChatModelManager.chatModel?.getNumTokens(inputStr) ?? 0;
  }
  validateCurrentModel() {
    if (!ChatModelManager.chatModel)
      return;
    const currentModelKey = getModelKey();
    if (!currentModelKey)
      return;
    const selectedModel = ChatModelManager.modelMap[currentModelKey];
    if (!selectedModel?.hasApiKey) {
      ChatModelManager.chatModel = null;
      console.log("Failed to reinitialize model due to missing API key");
    }
  }
  async ping(model) {
    const tryPing = async (enableCors) => {
      const modelToTest = { ...model, enableCors };
      const modelConfig = await this.getModelConfig(modelToTest);
      const { streaming, temperature, ...pingConfig } = modelConfig;
      pingConfig.maxTokens = 10;
      const testModel = new (this.getProviderConstructor(modelToTest))(pingConfig);
      await testModel.invoke([{ role: "user", content: "hello" }], {
        timeout: 3e3
      });
    };
    try {
      await tryPing(false);
      return true;
    } catch (firstError) {
      console.log("First ping attempt failed, trying with CORS...");
      try {
        await tryPing(true);
        new import_obsidian11.Notice(
          "Connection successful, but requires CORS to be enabled. Please enable CORS for this model once you add it above."
        );
        return true;
      } catch (error) {
        const msg = "\nwithout CORS Error: " + err2String(firstError) + "\nwith CORS Error: " + err2String(error);
        throw new Error(msg);
      }
    }
  }
};

// src/chainUtils.ts
async function getStandaloneQuestion(question, chatHistory) {
  const condenseQuestionTemplate = `Given the following conversation and a follow up question,
    summarize the conversation as context and keep the follow up question unchanged, in its original language.
    If the follow up question is unrelated to its preceding messages, return this follow up question directly.
    If it is related, then combine the summary and the follow up question to construct a standalone question.
    Make sure to keep any [[]] wrapped note titles in the question unchanged.
    If there's nothing in the chat history, just return the follow up question.

    Chat History:
    {chat_history}
    Follow Up Input: {question}
    Standalone question:`;
  const formattedChatHistory = chatHistory.map(([human, ai]) => `Human: ${human}
Assistant: ${ai}`).join("\n");
  const response = await ChatModelManager.getInstance().getChatModel().invoke([
    { role: "system", content: condenseQuestionTemplate },
    {
      role: "user",
      content: condenseQuestionTemplate.replace("{chat_history}", formattedChatHistory).replace("{question}", question)
    }
  ]);
  return response.content;
}

// src/tools/toolManager.ts
var import_obsidian12 = require("obsidian");
var getToolDescription = (tool2) => {
  switch (tool2) {
    case "@vault":
      return "Search through your vault for relevant information";
    case "@web":
      return "Search the web for information";
    case "@youtube":
      return "Get the transcript of a YouTube video. Example: @youtube <video_url>";
    case "@pomodoro":
      return "Start a pomodoro timer. Example: @pomodoro 25m";
    default:
      return "";
  }
};
var ToolManager = class {
  static async callTool(tool2, args) {
    try {
      if (!tool2) {
        throw new Error("Tool is undefined");
      }
      const result = await tool2.call(args);
      if (result === void 0 || result === null) {
        console.warn(`Tool ${tool2.name} returned null/undefined result`);
        return null;
      }
      return result;
    } catch (error) {
      console.error(`Error calling tool:`, error);
      if (error instanceof Error) {
        new import_obsidian12.Notice(error.message);
      } else {
        new import_obsidian12.Notice("An error occurred while executing the tool. Check console for details.");
      }
      return null;
    }
  }
};

// src/LLMProviders/chainRunner.ts
var import_obsidian14 = require("obsidian");

// src/search/hybridRetriever.ts
init_prompts3();

// node_modules/@langchain/core/dist/retrievers/index.js
init_manager();
init_base4();
init_config();
var BaseRetriever = class extends Runnable {
  /**
   * Constructs a new `BaseRetriever` instance with optional configuration fields.
   *
   * @param fields - Optional input configuration that can include `callbacks`,
   *                 `tags`, `metadata`, and `verbose` settings for custom retriever behavior.
   */
  constructor(fields) {
    super(fields);
    Object.defineProperty(this, "callbacks", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "tags", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "metadata", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "verbose", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.callbacks = fields?.callbacks;
    this.tags = fields?.tags ?? [];
    this.metadata = fields?.metadata ?? {};
    this.verbose = fields?.verbose ?? false;
  }
  /**
   * TODO: This should be an abstract method, but we'd like to avoid breaking
   * changes to people currently using subclassed custom retrievers.
   * Change it on next major release.
   */
  /**
   * Placeholder method for retrieving relevant documents based on a query.
   *
   * This method is intended to be implemented by subclasses and will be
   * converted to an abstract method in the next major release. Currently, it
   * throws an error if not implemented, ensuring that custom retrievers define
   * the specific retrieval logic.
   *
   * @param _query - The query string used to search for relevant documents.
   * @param _callbacks - (optional) Callback manager for managing callbacks
   *                     during retrieval.
   * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query.
   * @throws {Error} Throws an error indicating the method is not implemented.
   */
  _getRelevantDocuments(_query, _callbacks) {
    throw new Error("Not implemented!");
  }
  /**
   * Executes a retrieval operation.
   *
   * @param input - The query string used to search for relevant documents.
   * @param options - (optional) Configuration options for the retrieval run,
   *                  which may include callbacks, tags, and metadata.
   * @returns A promise that resolves to an array of `DocumentInterface` instances
   *          representing the most relevant documents to the query.
   */
  async invoke(input, options) {
    return this.getRelevantDocuments(input, ensureConfig(options));
  }
  /**
   * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
   *
   * Main method used to retrieve relevant documents. It takes a query
   * string and an optional configuration object, and returns a promise that
   * resolves to an array of `Document` objects. This method handles the
   * retrieval process, including starting and ending callbacks, and error
   * handling.
   * @param query The query string to retrieve relevant documents for.
   * @param config Optional configuration object for the retrieval process.
   * @returns A promise that resolves to an array of `Document` objects.
   */
  async getRelevantDocuments(query, config) {
    const parsedConfig = ensureConfig(parseCallbackConfigArg(config));
    const callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose });
    const runManager = await callbackManager_?.handleRetrieverStart(this.toJSON(), query, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName);
    try {
      const results = await this._getRelevantDocuments(query, runManager);
      await runManager?.handleRetrieverEnd(results);
      return results;
    } catch (error) {
      await runManager?.handleRetrieverError(error);
      throw error;
    }
  }
};

// src/search/hybridRetriever.ts
var HybridRetriever = class extends BaseRetriever {
  constructor(options) {
    super();
    this.options = options;
    this.lc_namespace = ["hybrid_retriever"];
    this.queryRewritePrompt = ChatPromptTemplate.fromTemplate(
      "Please write a passage to answer the question. If you don't know the answer, just make up a passage. \nQuestion: {question}\nPassage:"
    );
  }
  async getRelevantDocuments(query, config) {
    const noteTitles = extractNoteTitles(query);
    const explicitChunks = await this.getExplicitChunks(noteTitles);
    let rewrittenQuery = query;
    if (config?.runName !== "no_hyde") {
      rewrittenQuery = await this.rewriteQuery(query);
    }
    const oramaChunks = await this.getOramaChunks(
      rewrittenQuery,
      this.options.salientTerms,
      this.options.textWeight
    );
    const combinedChunks = this.filterAndFormatChunks(oramaChunks, explicitChunks);
    let finalChunks = combinedChunks;
    if (combinedChunks.length === 0) {
      if (getSettings().debug) {
        console.log("No chunks found for query:", query);
      }
      return finalChunks;
    }
    const maxOramaScore = combinedChunks.reduce((max2, chunk) => {
      const score = chunk.metadata.score;
      const isValidScore = typeof score === "number" && !isNaN(score);
      return isValidScore ? Math.max(max2, score) : max2;
    }, 0);
    const allScoresAreNaN = combinedChunks.every(
      (chunk) => typeof chunk.metadata.score !== "number" || isNaN(chunk.metadata.score)
    );
    const shouldRerank = this.options.useRerankerThreshold && (maxOramaScore < this.options.useRerankerThreshold || allScoresAreNaN);
    if (shouldRerank) {
      const rerankResponse = await BrevilabsClient.getInstance().rerank(
        query,
        // Limit the context length to 3000 characters to avoid overflowing the reranker
        combinedChunks.map((doc) => doc.pageContent.slice(0, 3e3))
      );
      finalChunks = rerankResponse.response.data.map((item) => ({
        ...combinedChunks[item.index],
        metadata: {
          ...combinedChunks[item.index].metadata,
          rerank_score: item.relevance_score
        }
      }));
    }
    if (getSettings().debug) {
      console.log("*** HYBRID RETRIEVER DEBUG INFO: ***");
      if (config?.runName !== "no_hyde") {
        console.log("\nOriginal Query: ", query);
        console.log("Rewritten Query: ", rewrittenQuery);
      }
      console.log("\nExplicit Chunks: ", explicitChunks);
      console.log("Orama Chunks: ", oramaChunks);
      console.log("Combined Chunks: ", combinedChunks);
      console.log("Max Orama Score: ", maxOramaScore);
      if (shouldRerank) {
        console.log("Reranked Chunks: ", finalChunks);
      } else {
        console.log("No reranking applied.");
      }
    }
    return finalChunks;
  }
  async rewriteQuery(query) {
    try {
      const promptResult = await this.queryRewritePrompt.format({ question: query });
      const chatModel = ChatModelManager.getInstance().getChatModel();
      const rewrittenQueryObject = await chatModel.invoke(promptResult);
      if (rewrittenQueryObject && "content" in rewrittenQueryObject) {
        return rewrittenQueryObject.content;
      }
      console.warn("Unexpected rewrittenQuery format. Falling back to original query.");
      return query;
    } catch (error) {
      console.error("Error in rewriteQuery:", error);
      return query;
    }
  }
  async getExplicitChunks(noteTitles) {
    const explicitChunks = [];
    for (const noteTitle of noteTitles) {
      const noteFile = await getNoteFileFromTitle(app.vault, noteTitle);
      const db = await VectorStoreManager.getInstance().getDb();
      const hits = await DBOperations.getDocsByPath(db, noteFile?.path ?? "");
      if (hits) {
        const matchingChunks = hits.map(
          (hit) => new Document2({
            pageContent: hit.document.content,
            metadata: {
              ...hit.document.metadata,
              score: hit.score,
              path: hit.document.path,
              mtime: hit.document.mtime,
              ctime: hit.document.ctime,
              title: hit.document.title,
              id: hit.document.id,
              embeddingModel: hit.document.embeddingModel,
              tags: hit.document.tags,
              extension: hit.document.extension,
              created_at: hit.document.created_at,
              nchars: hit.document.nchars
            }
          })
        );
        explicitChunks.push(...matchingChunks);
      }
    }
    return explicitChunks;
  }
  // Orama does not support OR for filters, so we need to manually combine the results from the two queries
  // https://github.com/orgs/askorama/discussions/670
  async getOramaChunks(query, salientTerms, textWeight) {
    let queryVector;
    try {
      queryVector = await this.convertQueryToVector(query);
    } catch (error) {
      console.error(
        "Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",
        error,
        "\nQuery:",
        query
      );
      throw error;
    }
    const db = await VectorStoreManager.getInstance().getDb();
    const searchParams = {
      similarity: this.options.minSimilarityScore,
      limit: this.options.maxK,
      includeVectors: true
    };
    if (salientTerms.length > 0) {
      let vectorWeight;
      if (!textWeight) {
        textWeight = 0.5;
      }
      vectorWeight = 1 - textWeight;
      let tagOnlyQuery = true;
      for (const term of salientTerms) {
        if (!term.startsWith("#")) {
          tagOnlyQuery = false;
          break;
        }
      }
      if (tagOnlyQuery) {
        if (getSettings().debug) {
          console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0.");
        }
        textWeight = 1;
        vectorWeight = 0;
      }
      searchParams.mode = "hybrid";
      searchParams.term = salientTerms.join(" ");
      searchParams.vector = {
        value: queryVector,
        property: "embedding"
      };
      searchParams.hybridWeights = {
        text: textWeight,
        vector: vectorWeight
      };
    } else {
      searchParams.mode = "vector";
      searchParams.vector = {
        value: queryVector,
        property: "embedding"
      };
    }
    if (this.options.timeRange) {
      const { startTime, endTime } = this.options.timeRange;
      const dateRange = this.generateDateRange(startTime, endTime);
      if (getSettings().debug) {
        console.log(
          "==== Daily note date range: ====",
          dateRange[0],
          dateRange[dateRange.length - 1]
        );
      }
      const dailyNoteResults = await this.getExplicitChunks(dateRange);
      const dailyNoteResultsWithContext = dailyNoteResults.map((doc) => ({
        ...doc,
        metadata: {
          ...doc.metadata,
          includeInContext: true
        }
      }));
      if (getSettings().debug) {
        console.log("==== Modified and created time range: ====", startTime, endTime);
      }
      searchParams.where = {
        ctime: { between: [startTime, endTime] },
        mtime: { between: [startTime, endTime] }
      };
      const timeIntervalResults = await search2(db, searchParams);
      const timeIntervalDocuments = timeIntervalResults.hits.map(
        (hit) => new Document2({
          pageContent: hit.document.content,
          metadata: {
            ...hit.document.metadata,
            score: hit.score,
            path: hit.document.path,
            mtime: hit.document.mtime,
            ctime: hit.document.ctime,
            title: hit.document.title,
            id: hit.document.id,
            embeddingModel: hit.document.embeddingModel,
            tags: hit.document.tags,
            extension: hit.document.extension,
            created_at: hit.document.created_at,
            nchars: hit.document.nchars
          }
        })
      );
      const combinedResults = [...dailyNoteResultsWithContext, ...timeIntervalDocuments];
      const uniqueResults = Array.from(new Set(combinedResults.map((doc) => doc.metadata.id))).map(
        (id) => combinedResults.find((doc) => doc.metadata.id === id)
      );
      return uniqueResults.filter((doc) => doc !== void 0);
    }
    if (getSettings().debug) {
      console.log("==== Orama Search Params: ====\n", searchParams);
    }
    const searchResults = await search2(db, searchParams);
    if (!searchResults || !searchResults.hits) {
      console.warn("Search results or hits are undefined");
      return [];
    }
    return searchResults.hits.map((hit) => {
      if (!hit || !hit.document) {
        console.warn("Invalid hit or document in search results");
        return null;
      }
      if (typeof hit.score !== "number" || isNaN(hit.score)) {
        console.warn("NaN/invalid score detected:", {
          score: hit.score,
          path: hit.document.path,
          title: hit.document.title
        });
      }
      return new Document2({
        pageContent: hit.document.content || "",
        // Add fallback for content
        metadata: {
          ...hit.document.metadata || {},
          // Add fallback for metadata
          score: hit.score,
          path: hit.document.path || "",
          mtime: hit.document.mtime,
          ctime: hit.document.ctime,
          title: hit.document.title || "",
          id: hit.document.id,
          embeddingModel: hit.document.embeddingModel,
          tags: hit.document.tags || [],
          extension: hit.document.extension,
          created_at: hit.document.created_at,
          nchars: hit.document.nchars
        }
      });
    }).filter((doc) => doc !== null);
  }
  async convertQueryToVector(query) {
    const embeddingsAPI = await EmbeddingManager.getInstance().getEmbeddingsAPI();
    const vector = await embeddingsAPI.embedQuery(query);
    if (vector.length === 0) {
      throw new Error("Query embedding returned an empty vector");
    }
    return vector;
  }
  generateDateRange(startTime, endTime) {
    const dateRange = [];
    const start = new Date(startTime);
    const end = new Date(endTime);
    const current = new Date(start);
    while (current <= end) {
      dateRange.push(current.toLocaleDateString("en-CA"));
      current.setDate(current.getDate() + 1);
    }
    return dateRange;
  }
  filterAndFormatChunks(oramaChunks, explicitChunks) {
    const threshold = this.options.minSimilarityScore;
    const filteredOramaChunks = oramaChunks.filter((chunk) => {
      const score = chunk.metadata.score;
      if (typeof score !== "number" || isNaN(score)) {
        return true;
      }
      return score >= threshold;
    });
    const uniqueChunks = new Set(explicitChunks.map((chunk) => chunk.pageContent));
    const combinedChunks = [...explicitChunks];
    for (const chunk of filteredOramaChunks) {
      const chunkContent = chunk.pageContent;
      if (!uniqueChunks.has(chunkContent)) {
        uniqueChunks.add(chunkContent);
        combinedChunks.push(chunk);
      }
    }
    return combinedChunks.map((chunk) => ({
      ...chunk,
      metadata: {
        ...chunk.metadata,
        includeInContext: true
      }
    }));
  }
};

// src/tools/SearchTools.ts
init_lib();
var localSearchTool = tool(
  async ({
    timeRange,
    query,
    salientTerms
  }) => {
    const indexEmpty = await VectorStoreManager.getInstance().isIndexEmpty();
    if (indexEmpty) {
      throw new CustomError(EMPTY_INDEX_ERROR_MESSAGE);
    }
    const returnAll = timeRange !== void 0;
    const maxSourceChunks = getSettings().maxSourceChunks < PLUS_MODE_DEFAULT_SOURCE_CHUNKS ? PLUS_MODE_DEFAULT_SOURCE_CHUNKS : getSettings().maxSourceChunks;
    if (getSettings().debug) {
      console.log("returnAll:", returnAll);
    }
    const hybridRetriever = new HybridRetriever({
      minSimilarityScore: returnAll ? 0 : 0.1,
      maxK: returnAll ? 1e3 : maxSourceChunks,
      salientTerms,
      timeRange: timeRange ? {
        startTime: timeRange.startTime.epoch,
        endTime: timeRange.endTime.epoch
      } : void 0,
      textWeight: TEXT_WEIGHT,
      returnAll,
      // Voyage AI reranker did worse than Orama in some cases, so only use it if
      // Orama did not return anything higher than this threshold
      useRerankerThreshold: 0.5
    });
    const documents = await hybridRetriever.getRelevantDocuments(query);
    const formattedResults = documents.map((doc) => ({
      title: doc.metadata.title,
      content: doc.pageContent,
      path: doc.metadata.path,
      score: doc.metadata.score,
      rerank_score: doc.metadata.rerank_score,
      includeInContext: doc.metadata.includeInContext
    }));
    return JSON.stringify(formattedResults);
  },
  {
    name: "localSearch",
    description: "Search for notes based on the time range and query",
    schema: z.object({
      timeRange: z.object({
        startTime: z.any(),
        endTime: z.any()
      }).optional(),
      query: z.string().describe("The search query"),
      salientTerms: z.array(z.string()).describe("List of salient terms extracted from the query")
    })
  }
);
var indexTool = tool(
  async () => {
    try {
      const indexedCount = await VectorStoreManager.getInstance().indexVaultToVectorStore();
      const indexResultPrompt = `Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`;
      return indexResultPrompt + JSON.stringify({
        success: true,
        message: indexedCount === 0 ? "No new files to index." : `Indexed ${indexedCount} files in the vault.`
      });
    } catch (error) {
      console.error("Error indexing vault:", error);
      return JSON.stringify({
        success: false,
        message: "An error occurred while indexing the vault."
      });
    }
  },
  {
    name: "indexVault",
    description: "Index the vault to the Copilot index"
  }
);
var webSearchTool = tool(
  async ({ query, chatHistory }) => {
    try {
      const standaloneQuestion = await getStandaloneQuestion(query, chatHistory);
      const response = await BrevilabsClient.getInstance().webSearch(standaloneQuestion);
      const citations = response.response.citations || [];
      const citationsList = citations.length > 0 ? "\n\nSources:\n" + citations.map((url, index2) => `[${index2 + 1}] ${url}`).join("\n") : "";
      return "Here are the web search results. Please provide a response based on this information and include source citations listed at the end of your response under the heading '#### Sources' as a list of markdown links. For each URL, create a descriptive title based on the domain and path and return it in the markdown format '- [title](url)':\n\n" + response.response.choices[0].message.content + citationsList;
    } catch (error) {
      console.error(`Error processing web search query ${query}:`, error);
      return "";
    }
  },
  {
    name: "webSearch",
    description: "Search the web for information",
    schema: z.object({
      query: z.string().describe("The search query"),
      chatHistory: z.array(z.tuple([z.string(), z.string()])).describe("Previous conversation turns")
    })
  }
);

// node_modules/chrono-node/dist/esm/results.js
var import_quarterOfYear = __toESM(require_quarterOfYear(), 1);
var import_dayjs2 = __toESM(require_dayjs_min(), 1);

// node_modules/chrono-node/dist/esm/types.js
var Meridiem;
(function(Meridiem2) {
  Meridiem2[Meridiem2["AM"] = 0] = "AM";
  Meridiem2[Meridiem2["PM"] = 1] = "PM";
})(Meridiem || (Meridiem = {}));
var Weekday;
(function(Weekday2) {
  Weekday2[Weekday2["SUNDAY"] = 0] = "SUNDAY";
  Weekday2[Weekday2["MONDAY"] = 1] = "MONDAY";
  Weekday2[Weekday2["TUESDAY"] = 2] = "TUESDAY";
  Weekday2[Weekday2["WEDNESDAY"] = 3] = "WEDNESDAY";
  Weekday2[Weekday2["THURSDAY"] = 4] = "THURSDAY";
  Weekday2[Weekday2["FRIDAY"] = 5] = "FRIDAY";
  Weekday2[Weekday2["SATURDAY"] = 6] = "SATURDAY";
})(Weekday || (Weekday = {}));
var Month;
(function(Month2) {
  Month2[Month2["JANUARY"] = 1] = "JANUARY";
  Month2[Month2["FEBRUARY"] = 2] = "FEBRUARY";
  Month2[Month2["MARCH"] = 3] = "MARCH";
  Month2[Month2["APRIL"] = 4] = "APRIL";
  Month2[Month2["MAY"] = 5] = "MAY";
  Month2[Month2["JUNE"] = 6] = "JUNE";
  Month2[Month2["JULY"] = 7] = "JULY";
  Month2[Month2["AUGUST"] = 8] = "AUGUST";
  Month2[Month2["SEPTEMBER"] = 9] = "SEPTEMBER";
  Month2[Month2["OCTOBER"] = 10] = "OCTOBER";
  Month2[Month2["NOVEMBER"] = 11] = "NOVEMBER";
  Month2[Month2["DECEMBER"] = 12] = "DECEMBER";
})(Month || (Month = {}));

// node_modules/chrono-node/dist/esm/utils/dayjs.js
function implyTheNextDay(component, targetDayJs) {
  targetDayJs = targetDayJs.add(1, "day");
  implySimilarDate(component, targetDayJs);
  implySimilarTime(component, targetDayJs);
}
function assignSimilarDate(component, targetDayJs) {
  component.assign("day", targetDayJs.date());
  component.assign("month", targetDayJs.month() + 1);
  component.assign("year", targetDayJs.year());
}
function assignSimilarTime(component, targetDayJs) {
  component.assign("hour", targetDayJs.hour());
  component.assign("minute", targetDayJs.minute());
  component.assign("second", targetDayJs.second());
  component.assign("millisecond", targetDayJs.millisecond());
  if (component.get("hour") < 12) {
    component.assign("meridiem", Meridiem.AM);
  } else {
    component.assign("meridiem", Meridiem.PM);
  }
}
function implySimilarDate(component, targetDayJs) {
  component.imply("day", targetDayJs.date());
  component.imply("month", targetDayJs.month() + 1);
  component.imply("year", targetDayJs.year());
}
function implySimilarTime(component, targetDayJs) {
  component.imply("hour", targetDayJs.hour());
  component.imply("minute", targetDayJs.minute());
  component.imply("second", targetDayJs.second());
  component.imply("millisecond", targetDayJs.millisecond());
}

// node_modules/chrono-node/dist/esm/timezone.js
var import_dayjs = __toESM(require_dayjs_min(), 1);
var TIMEZONE_ABBR_MAP = {
  ACDT: 630,
  ACST: 570,
  ADT: -180,
  AEDT: 660,
  AEST: 600,
  AFT: 270,
  AKDT: -480,
  AKST: -540,
  ALMT: 360,
  AMST: -180,
  AMT: -240,
  ANAST: 720,
  ANAT: 720,
  AQTT: 300,
  ART: -180,
  AST: -240,
  AWDT: 540,
  AWST: 480,
  AZOST: 0,
  AZOT: -60,
  AZST: 300,
  AZT: 240,
  BNT: 480,
  BOT: -240,
  BRST: -120,
  BRT: -180,
  BST: 60,
  BTT: 360,
  CAST: 480,
  CAT: 120,
  CCT: 390,
  CDT: -300,
  CEST: 120,
  CET: {
    timezoneOffsetDuringDst: 2 * 60,
    timezoneOffsetNonDst: 60,
    dstStart: (year) => getLastWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2),
    dstEnd: (year) => getLastWeekdayOfMonth(year, Month.OCTOBER, Weekday.SUNDAY, 3)
  },
  CHADT: 825,
  CHAST: 765,
  CKT: -600,
  CLST: -180,
  CLT: -240,
  COT: -300,
  CST: -360,
  CT: {
    timezoneOffsetDuringDst: -5 * 60,
    timezoneOffsetNonDst: -6 * 60,
    dstStart: (year) => getNthWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2, 2),
    dstEnd: (year) => getNthWeekdayOfMonth(year, Month.NOVEMBER, Weekday.SUNDAY, 1, 2)
  },
  CVT: -60,
  CXT: 420,
  ChST: 600,
  DAVT: 420,
  EASST: -300,
  EAST: -360,
  EAT: 180,
  ECT: -300,
  EDT: -240,
  EEST: 180,
  EET: 120,
  EGST: 0,
  EGT: -60,
  EST: -300,
  ET: {
    timezoneOffsetDuringDst: -4 * 60,
    timezoneOffsetNonDst: -5 * 60,
    dstStart: (year) => getNthWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2, 2),
    dstEnd: (year) => getNthWeekdayOfMonth(year, Month.NOVEMBER, Weekday.SUNDAY, 1, 2)
  },
  FJST: 780,
  FJT: 720,
  FKST: -180,
  FKT: -240,
  FNT: -120,
  GALT: -360,
  GAMT: -540,
  GET: 240,
  GFT: -180,
  GILT: 720,
  GMT: 0,
  GST: 240,
  GYT: -240,
  HAA: -180,
  HAC: -300,
  HADT: -540,
  HAE: -240,
  HAP: -420,
  HAR: -360,
  HAST: -600,
  HAT: -90,
  HAY: -480,
  HKT: 480,
  HLV: -210,
  HNA: -240,
  HNC: -360,
  HNE: -300,
  HNP: -480,
  HNR: -420,
  HNT: -150,
  HNY: -540,
  HOVT: 420,
  ICT: 420,
  IDT: 180,
  IOT: 360,
  IRDT: 270,
  IRKST: 540,
  IRKT: 540,
  IRST: 210,
  IST: 330,
  JST: 540,
  KGT: 360,
  KRAST: 480,
  KRAT: 480,
  KST: 540,
  KUYT: 240,
  LHDT: 660,
  LHST: 630,
  LINT: 840,
  MAGST: 720,
  MAGT: 720,
  MART: -510,
  MAWT: 300,
  MDT: -360,
  MESZ: 120,
  MEZ: 60,
  MHT: 720,
  MMT: 390,
  MSD: 240,
  MSK: 180,
  MST: -420,
  MT: {
    timezoneOffsetDuringDst: -6 * 60,
    timezoneOffsetNonDst: -7 * 60,
    dstStart: (year) => getNthWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2, 2),
    dstEnd: (year) => getNthWeekdayOfMonth(year, Month.NOVEMBER, Weekday.SUNDAY, 1, 2)
  },
  MUT: 240,
  MVT: 300,
  MYT: 480,
  NCT: 660,
  NDT: -90,
  NFT: 690,
  NOVST: 420,
  NOVT: 360,
  NPT: 345,
  NST: -150,
  NUT: -660,
  NZDT: 780,
  NZST: 720,
  OMSST: 420,
  OMST: 420,
  PDT: -420,
  PET: -300,
  PETST: 720,
  PETT: 720,
  PGT: 600,
  PHOT: 780,
  PHT: 480,
  PKT: 300,
  PMDT: -120,
  PMST: -180,
  PONT: 660,
  PST: -480,
  PT: {
    timezoneOffsetDuringDst: -7 * 60,
    timezoneOffsetNonDst: -8 * 60,
    dstStart: (year) => getNthWeekdayOfMonth(year, Month.MARCH, Weekday.SUNDAY, 2, 2),
    dstEnd: (year) => getNthWeekdayOfMonth(year, Month.NOVEMBER, Weekday.SUNDAY, 1, 2)
  },
  PWT: 540,
  PYST: -180,
  PYT: -240,
  RET: 240,
  SAMT: 240,
  SAST: 120,
  SBT: 660,
  SCT: 240,
  SGT: 480,
  SRT: -180,
  SST: -660,
  TAHT: -600,
  TFT: 300,
  TJT: 300,
  TKT: 780,
  TLT: 540,
  TMT: 300,
  TVT: 720,
  ULAT: 480,
  UTC: 0,
  UYST: -120,
  UYT: -180,
  UZT: 300,
  VET: -210,
  VLAST: 660,
  VLAT: 660,
  VUT: 660,
  WAST: 120,
  WAT: 60,
  WEST: 60,
  WESZ: 60,
  WET: 0,
  WEZ: 0,
  WFT: 720,
  WGST: -120,
  WGT: -180,
  WIB: 420,
  WIT: 540,
  WITA: 480,
  WST: 780,
  WT: 0,
  YAKST: 600,
  YAKT: 600,
  YAPT: 600,
  YEKST: 360,
  YEKT: 360
};
function getNthWeekdayOfMonth(year, month, weekday, n4, hour = 0) {
  let dayOfMonth = 0;
  let i3 = 0;
  while (i3 < n4) {
    dayOfMonth++;
    const date2 = new Date(year, month - 1, dayOfMonth);
    if (date2.getDay() === weekday)
      i3++;
  }
  return new Date(year, month - 1, dayOfMonth, hour);
}
function getLastWeekdayOfMonth(year, month, weekday, hour = 0) {
  const oneIndexedWeekday = weekday === 0 ? 7 : weekday;
  const date2 = new Date(year, month - 1 + 1, 1, 12);
  const firstWeekdayNextMonth = date2.getDay() === 0 ? 7 : date2.getDay();
  let dayDiff2;
  if (firstWeekdayNextMonth === oneIndexedWeekday)
    dayDiff2 = 7;
  else if (firstWeekdayNextMonth < oneIndexedWeekday)
    dayDiff2 = 7 + firstWeekdayNextMonth - oneIndexedWeekday;
  else
    dayDiff2 = firstWeekdayNextMonth - oneIndexedWeekday;
  date2.setDate(date2.getDate() - dayDiff2);
  return new Date(year, month - 1, date2.getDate(), hour);
}
function toTimezoneOffset(timezoneInput, date2, timezoneOverrides = {}) {
  if (timezoneInput == null) {
    return null;
  }
  if (typeof timezoneInput === "number") {
    return timezoneInput;
  }
  const matchedTimezone = timezoneOverrides[timezoneInput] ?? TIMEZONE_ABBR_MAP[timezoneInput];
  if (matchedTimezone == null) {
    return null;
  }
  if (typeof matchedTimezone == "number") {
    return matchedTimezone;
  }
  if (date2 == null) {
    return null;
  }
  if ((0, import_dayjs.default)(date2).isAfter(matchedTimezone.dstStart(date2.getFullYear())) && !(0, import_dayjs.default)(date2).isAfter(matchedTimezone.dstEnd(date2.getFullYear()))) {
    return matchedTimezone.timezoneOffsetDuringDst;
  }
  return matchedTimezone.timezoneOffsetNonDst;
}

// node_modules/chrono-node/dist/esm/results.js
import_dayjs2.default.extend(import_quarterOfYear.default);
var ReferenceWithTimezone = class {
  constructor(input) {
    input = input ?? new Date();
    if (input instanceof Date) {
      this.instant = input;
    } else {
      this.instant = input.instant ?? new Date();
      this.timezoneOffset = toTimezoneOffset(input.timezone, this.instant);
    }
  }
  getDateWithAdjustedTimezone() {
    return new Date(this.instant.getTime() + this.getSystemTimezoneAdjustmentMinute(this.instant) * 6e4);
  }
  getSystemTimezoneAdjustmentMinute(date2, overrideTimezoneOffset) {
    if (!date2 || date2.getTime() < 0) {
      date2 = new Date();
    }
    const currentTimezoneOffset = -date2.getTimezoneOffset();
    const targetTimezoneOffset = overrideTimezoneOffset ?? this.timezoneOffset ?? currentTimezoneOffset;
    return currentTimezoneOffset - targetTimezoneOffset;
  }
};
var ParsingComponents = class {
  constructor(reference, knownComponents) {
    this._tags = /* @__PURE__ */ new Set();
    this.reference = reference;
    this.knownValues = {};
    this.impliedValues = {};
    if (knownComponents) {
      for (const key in knownComponents) {
        this.knownValues[key] = knownComponents[key];
      }
    }
    const refDayJs = (0, import_dayjs2.default)(reference.instant);
    this.imply("day", refDayJs.date());
    this.imply("month", refDayJs.month() + 1);
    this.imply("year", refDayJs.year());
    this.imply("hour", 12);
    this.imply("minute", 0);
    this.imply("second", 0);
    this.imply("millisecond", 0);
  }
  get(component) {
    if (component in this.knownValues) {
      return this.knownValues[component];
    }
    if (component in this.impliedValues) {
      return this.impliedValues[component];
    }
    return null;
  }
  isCertain(component) {
    return component in this.knownValues;
  }
  getCertainComponents() {
    return Object.keys(this.knownValues);
  }
  imply(component, value) {
    if (component in this.knownValues) {
      return this;
    }
    this.impliedValues[component] = value;
    return this;
  }
  assign(component, value) {
    this.knownValues[component] = value;
    delete this.impliedValues[component];
    return this;
  }
  delete(component) {
    delete this.knownValues[component];
    delete this.impliedValues[component];
  }
  clone() {
    const component = new ParsingComponents(this.reference);
    component.knownValues = {};
    component.impliedValues = {};
    for (const key in this.knownValues) {
      component.knownValues[key] = this.knownValues[key];
    }
    for (const key in this.impliedValues) {
      component.impliedValues[key] = this.impliedValues[key];
    }
    return component;
  }
  isOnlyDate() {
    return !this.isCertain("hour") && !this.isCertain("minute") && !this.isCertain("second");
  }
  isOnlyTime() {
    return !this.isCertain("weekday") && !this.isCertain("day") && !this.isCertain("month") && !this.isCertain("year");
  }
  isOnlyWeekdayComponent() {
    return this.isCertain("weekday") && !this.isCertain("day") && !this.isCertain("month");
  }
  isDateWithUnknownYear() {
    return this.isCertain("month") && !this.isCertain("year");
  }
  isValidDate() {
    const date2 = this.dateWithoutTimezoneAdjustment();
    if (date2.getFullYear() !== this.get("year"))
      return false;
    if (date2.getMonth() !== this.get("month") - 1)
      return false;
    if (date2.getDate() !== this.get("day"))
      return false;
    if (this.get("hour") != null && date2.getHours() != this.get("hour"))
      return false;
    if (this.get("minute") != null && date2.getMinutes() != this.get("minute"))
      return false;
    return true;
  }
  toString() {
    return `[ParsingComponents {
            tags: ${JSON.stringify(Array.from(this._tags).sort())}, 
            knownValues: ${JSON.stringify(this.knownValues)}, 
            impliedValues: ${JSON.stringify(this.impliedValues)}}, 
            reference: ${JSON.stringify(this.reference)}]`;
  }
  dayjs() {
    return (0, import_dayjs2.default)(this.date());
  }
  date() {
    const date2 = this.dateWithoutTimezoneAdjustment();
    const timezoneAdjustment = this.reference.getSystemTimezoneAdjustmentMinute(date2, this.get("timezoneOffset"));
    return new Date(date2.getTime() + timezoneAdjustment * 6e4);
  }
  addTag(tag) {
    this._tags.add(tag);
    return this;
  }
  addTags(tags) {
    for (const tag of tags) {
      this._tags.add(tag);
    }
    return this;
  }
  tags() {
    return new Set(this._tags);
  }
  dateWithoutTimezoneAdjustment() {
    const date2 = new Date(this.get("year"), this.get("month") - 1, this.get("day"), this.get("hour"), this.get("minute"), this.get("second"), this.get("millisecond"));
    date2.setFullYear(this.get("year"));
    return date2;
  }
  static createRelativeFromReference(reference, fragments) {
    let date2 = (0, import_dayjs2.default)(reference.instant);
    for (const key in fragments) {
      date2 = date2.add(fragments[key], key);
    }
    const components2 = new ParsingComponents(reference);
    if (fragments["hour"] || fragments["minute"] || fragments["second"]) {
      assignSimilarTime(components2, date2);
      assignSimilarDate(components2, date2);
      if (reference.timezoneOffset !== null) {
        components2.assign("timezoneOffset", -reference.instant.getTimezoneOffset());
      }
    } else {
      implySimilarTime(components2, date2);
      if (reference.timezoneOffset !== null) {
        components2.imply("timezoneOffset", -reference.instant.getTimezoneOffset());
      }
      if (fragments["d"]) {
        components2.assign("day", date2.date());
        components2.assign("month", date2.month() + 1);
        components2.assign("year", date2.year());
      } else if (fragments["week"]) {
        components2.assign("day", date2.date());
        components2.assign("month", date2.month() + 1);
        components2.assign("year", date2.year());
        components2.imply("weekday", date2.day());
      } else {
        components2.imply("day", date2.date());
        if (fragments["month"]) {
          components2.assign("month", date2.month() + 1);
          components2.assign("year", date2.year());
        } else {
          components2.imply("month", date2.month() + 1);
          if (fragments["year"]) {
            components2.assign("year", date2.year());
          } else {
            components2.imply("year", date2.year());
          }
        }
      }
    }
    return components2;
  }
};
var ParsingResult = class {
  constructor(reference, index2, text, start, end) {
    this.reference = reference;
    this.refDate = reference.instant;
    this.index = index2;
    this.text = text;
    this.start = start || new ParsingComponents(reference);
    this.end = end;
  }
  clone() {
    const result = new ParsingResult(this.reference, this.index, this.text);
    result.start = this.start ? this.start.clone() : null;
    result.end = this.end ? this.end.clone() : null;
    return result;
  }
  date() {
    return this.start.date();
  }
  tags() {
    const combinedTags = new Set(this.start.tags());
    if (this.end) {
      for (const tag of this.end.tags()) {
        combinedTags.add(tag);
      }
    }
    return combinedTags;
  }
  toString() {
    const tags = Array.from(this.tags()).sort();
    return `[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(tags)} ...}]`;
  }
};

// node_modules/chrono-node/dist/esm/utils/pattern.js
function repeatedTimeunitPattern(prefix, singleTimeunitPattern, connectorPattern = "\\s{0,5},?\\s{0,5}") {
  const singleTimeunitPatternNoCapture = singleTimeunitPattern.replace(/\((?!\?)/g, "(?:");
  return `${prefix}${singleTimeunitPatternNoCapture}(?:${connectorPattern}${singleTimeunitPatternNoCapture}){0,10}`;
}
function extractTerms(dictionary) {
  let keys;
  if (dictionary instanceof Array) {
    keys = [...dictionary];
  } else if (dictionary instanceof Map) {
    keys = Array.from(dictionary.keys());
  } else {
    keys = Object.keys(dictionary);
  }
  return keys;
}
function matchAnyPattern(dictionary) {
  const joinedTerms = extractTerms(dictionary).sort((a3, b3) => b3.length - a3.length).join("|").replace(/\./g, "\\.");
  return `(?:${joinedTerms})`;
}

// node_modules/chrono-node/dist/esm/calculation/years.js
var import_dayjs4 = __toESM(require_dayjs_min(), 1);
function findMostLikelyADYear(yearNumber) {
  if (yearNumber < 100) {
    if (yearNumber > 50) {
      yearNumber = yearNumber + 1900;
    } else {
      yearNumber = yearNumber + 2e3;
    }
  }
  return yearNumber;
}
function findYearClosestToRef(refDate, day, month) {
  const refMoment = (0, import_dayjs4.default)(refDate);
  let dateMoment = refMoment;
  dateMoment = dateMoment.month(month - 1);
  dateMoment = dateMoment.date(day);
  dateMoment = dateMoment.year(refMoment.year());
  const nextYear = dateMoment.add(1, "y");
  const lastYear = dateMoment.add(-1, "y");
  if (Math.abs(nextYear.diff(refMoment)) < Math.abs(dateMoment.diff(refMoment))) {
    dateMoment = nextYear;
  } else if (Math.abs(lastYear.diff(refMoment)) < Math.abs(dateMoment.diff(refMoment))) {
    dateMoment = lastYear;
  }
  return dateMoment.year();
}

// node_modules/chrono-node/dist/esm/locales/en/constants.js
var WEEKDAY_DICTIONARY = {
  sunday: 0,
  sun: 0,
  "sun.": 0,
  monday: 1,
  mon: 1,
  "mon.": 1,
  tuesday: 2,
  tue: 2,
  "tue.": 2,
  wednesday: 3,
  wed: 3,
  "wed.": 3,
  thursday: 4,
  thurs: 4,
  "thurs.": 4,
  thur: 4,
  "thur.": 4,
  thu: 4,
  "thu.": 4,
  friday: 5,
  fri: 5,
  "fri.": 5,
  saturday: 6,
  sat: 6,
  "sat.": 6
};
var FULL_MONTH_NAME_DICTIONARY = {
  january: 1,
  february: 2,
  march: 3,
  april: 4,
  may: 5,
  june: 6,
  july: 7,
  august: 8,
  september: 9,
  october: 10,
  november: 11,
  december: 12
};
var MONTH_DICTIONARY = {
  ...FULL_MONTH_NAME_DICTIONARY,
  jan: 1,
  "jan.": 1,
  feb: 2,
  "feb.": 2,
  mar: 3,
  "mar.": 3,
  apr: 4,
  "apr.": 4,
  jun: 6,
  "jun.": 6,
  jul: 7,
  "jul.": 7,
  aug: 8,
  "aug.": 8,
  sep: 9,
  "sep.": 9,
  sept: 9,
  "sept.": 9,
  oct: 10,
  "oct.": 10,
  nov: 11,
  "nov.": 11,
  dec: 12,
  "dec.": 12
};
var INTEGER_WORD_DICTIONARY = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5,
  six: 6,
  seven: 7,
  eight: 8,
  nine: 9,
  ten: 10,
  eleven: 11,
  twelve: 12
};
var ORDINAL_WORD_DICTIONARY = {
  first: 1,
  second: 2,
  third: 3,
  fourth: 4,
  fifth: 5,
  sixth: 6,
  seventh: 7,
  eighth: 8,
  ninth: 9,
  tenth: 10,
  eleventh: 11,
  twelfth: 12,
  thirteenth: 13,
  fourteenth: 14,
  fifteenth: 15,
  sixteenth: 16,
  seventeenth: 17,
  eighteenth: 18,
  nineteenth: 19,
  twentieth: 20,
  "twenty first": 21,
  "twenty-first": 21,
  "twenty second": 22,
  "twenty-second": 22,
  "twenty third": 23,
  "twenty-third": 23,
  "twenty fourth": 24,
  "twenty-fourth": 24,
  "twenty fifth": 25,
  "twenty-fifth": 25,
  "twenty sixth": 26,
  "twenty-sixth": 26,
  "twenty seventh": 27,
  "twenty-seventh": 27,
  "twenty eighth": 28,
  "twenty-eighth": 28,
  "twenty ninth": 29,
  "twenty-ninth": 29,
  "thirtieth": 30,
  "thirty first": 31,
  "thirty-first": 31
};
var TIME_UNIT_DICTIONARY_NO_ABBR = {
  second: "second",
  seconds: "second",
  minute: "minute",
  minutes: "minute",
  hour: "hour",
  hours: "hour",
  day: "d",
  days: "d",
  week: "week",
  weeks: "week",
  month: "month",
  months: "month",
  quarter: "quarter",
  quarters: "quarter",
  year: "year",
  years: "year"
};
var TIME_UNIT_DICTIONARY = {
  s: "second",
  sec: "second",
  second: "second",
  seconds: "second",
  m: "minute",
  min: "minute",
  mins: "minute",
  minute: "minute",
  minutes: "minute",
  h: "hour",
  hr: "hour",
  hrs: "hour",
  hour: "hour",
  hours: "hour",
  d: "d",
  day: "d",
  days: "d",
  w: "w",
  week: "week",
  weeks: "week",
  mo: "month",
  mon: "month",
  mos: "month",
  month: "month",
  months: "month",
  qtr: "quarter",
  quarter: "quarter",
  quarters: "quarter",
  y: "year",
  yr: "year",
  year: "year",
  years: "year",
  ...TIME_UNIT_DICTIONARY_NO_ABBR
};
var NUMBER_PATTERN = `(?:${matchAnyPattern(INTEGER_WORD_DICTIONARY)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;
function parseNumberPattern(match2) {
  const num = match2.toLowerCase();
  if (INTEGER_WORD_DICTIONARY[num] !== void 0) {
    return INTEGER_WORD_DICTIONARY[num];
  } else if (num === "a" || num === "an" || num == "the") {
    return 1;
  } else if (num.match(/few/)) {
    return 3;
  } else if (num.match(/half/)) {
    return 0.5;
  } else if (num.match(/couple/)) {
    return 2;
  } else if (num.match(/several/)) {
    return 7;
  }
  return parseFloat(num);
}
var ORDINAL_NUMBER_PATTERN = `(?:${matchAnyPattern(ORDINAL_WORD_DICTIONARY)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;
function parseOrdinalNumberPattern(match2) {
  let num = match2.toLowerCase();
  if (ORDINAL_WORD_DICTIONARY[num] !== void 0) {
    return ORDINAL_WORD_DICTIONARY[num];
  }
  num = num.replace(/(?:st|nd|rd|th)$/i, "");
  return parseInt(num);
}
var YEAR_PATTERN = `(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9][0-9]|2[0-5])`;
function parseYear(match2) {
  if (/BE/i.test(match2)) {
    match2 = match2.replace(/BE/i, "");
    return parseInt(match2) - 543;
  }
  if (/BCE?/i.test(match2)) {
    match2 = match2.replace(/BCE?/i, "");
    return -parseInt(match2);
  }
  if (/(AD|CE)/i.test(match2)) {
    match2 = match2.replace(/(AD|CE)/i, "");
    return parseInt(match2);
  }
  const rawYearNumber = parseInt(match2);
  return findMostLikelyADYear(rawYearNumber);
}
var SINGLE_TIME_UNIT_PATTERN = `(${NUMBER_PATTERN})\\s{0,3}(${matchAnyPattern(TIME_UNIT_DICTIONARY)})`;
var SINGLE_TIME_UNIT_REGEX = new RegExp(SINGLE_TIME_UNIT_PATTERN, "i");
var SINGLE_TIME_UNIT_NO_ABBR_PATTERN = `(${NUMBER_PATTERN})\\s{0,3}(${matchAnyPattern(TIME_UNIT_DICTIONARY_NO_ABBR)})`;
var TIME_UNIT_CONNECTOR_PATTERN = `\\s{0,5},?(?:\\s*and)?\\s{0,5}`;
var TIME_UNITS_PATTERN = repeatedTimeunitPattern(`(?:(?:about|around)\\s{0,3})?`, SINGLE_TIME_UNIT_PATTERN, TIME_UNIT_CONNECTOR_PATTERN);
var TIME_UNITS_NO_ABBR_PATTERN = repeatedTimeunitPattern(`(?:(?:about|around)\\s{0,3})?`, SINGLE_TIME_UNIT_NO_ABBR_PATTERN, TIME_UNIT_CONNECTOR_PATTERN);
function parseTimeUnits(timeunitText) {
  const fragments = {};
  let remainingText = timeunitText;
  let match2 = SINGLE_TIME_UNIT_REGEX.exec(remainingText);
  while (match2) {
    collectDateTimeFragment(fragments, match2);
    remainingText = remainingText.substring(match2[0].length).trim();
    match2 = SINGLE_TIME_UNIT_REGEX.exec(remainingText);
  }
  if (Object.keys(fragments).length == 0) {
    return null;
  }
  return fragments;
}
function collectDateTimeFragment(fragments, match2) {
  if (match2[0].match(/^[a-zA-Z]+$/)) {
    return;
  }
  const num = parseNumberPattern(match2[1]);
  const unit = TIME_UNIT_DICTIONARY[match2[2].toLowerCase()];
  fragments[unit] = num;
}

// node_modules/chrono-node/dist/esm/common/parsers/AbstractParserWithWordBoundary.js
var AbstractParserWithWordBoundaryChecking = class {
  constructor() {
    this.cachedInnerPattern = null;
    this.cachedPattern = null;
  }
  innerPatternHasChange(context, currentInnerPattern) {
    return this.innerPattern(context) !== currentInnerPattern;
  }
  patternLeftBoundary() {
    return `(\\W|^)`;
  }
  pattern(context) {
    if (this.cachedInnerPattern) {
      if (!this.innerPatternHasChange(context, this.cachedInnerPattern)) {
        return this.cachedPattern;
      }
    }
    this.cachedInnerPattern = this.innerPattern(context);
    this.cachedPattern = new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`, this.cachedInnerPattern.flags);
    return this.cachedPattern;
  }
  extract(context, match2) {
    const header = match2[1] ?? "";
    match2.index = match2.index + header.length;
    match2[0] = match2[0].substring(header.length);
    for (let i3 = 2; i3 < match2.length; i3++) {
      match2[i3 - 1] = match2[i3];
    }
    return this.innerExtract(context, match2);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENTimeUnitWithinFormatParser.js
var PATTERN_WITH_OPTIONAL_PREFIX = new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${TIME_UNITS_PATTERN})(?=\\W|$)`, "i");
var PATTERN_WITH_PREFIX = new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${TIME_UNITS_PATTERN})(?=\\W|$)`, "i");
var PATTERN_WITH_PREFIX_STRICT = new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${TIME_UNITS_NO_ABBR_PATTERN})(?=\\W|$)`, "i");
var ENTimeUnitWithinFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(strictMode) {
    super();
    this.strictMode = strictMode;
  }
  innerPattern(context) {
    if (this.strictMode) {
      return PATTERN_WITH_PREFIX_STRICT;
    }
    return context.option.forwardDate ? PATTERN_WITH_OPTIONAL_PREFIX : PATTERN_WITH_PREFIX;
  }
  innerExtract(context, match2) {
    if (match2[0].match(/^for\s*the\s*\w+/)) {
      return null;
    }
    const timeUnits = parseTimeUnits(match2[1]);
    if (!timeUnits) {
      return null;
    }
    return ParsingComponents.createRelativeFromReference(context.reference, timeUnits);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENMonthNameLittleEndianParser.js
var PATTERN = new RegExp(`(?:on\\s{0,3})?(${ORDINAL_NUMBER_PATTERN})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)?\\s{0,3}(${ORDINAL_NUMBER_PATTERN}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${matchAnyPattern(MONTH_DICTIONARY)})(?:(?:-|/|,?\\s{0,3})(${YEAR_PATTERN}(?!\\w)))?(?=\\W|$)`, "i");
var DATE_GROUP = 1;
var DATE_TO_GROUP = 2;
var MONTH_NAME_GROUP = 3;
var YEAR_GROUP = 4;
var ENMonthNameLittleEndianParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN;
  }
  innerExtract(context, match2) {
    const result = context.createParsingResult(match2.index, match2[0]);
    const month = MONTH_DICTIONARY[match2[MONTH_NAME_GROUP].toLowerCase()];
    const day = parseOrdinalNumberPattern(match2[DATE_GROUP]);
    if (day > 31) {
      match2.index = match2.index + match2[DATE_GROUP].length;
      return null;
    }
    result.start.assign("month", month);
    result.start.assign("day", day);
    if (match2[YEAR_GROUP]) {
      const yearNumber = parseYear(match2[YEAR_GROUP]);
      result.start.assign("year", yearNumber);
    } else {
      const year = findYearClosestToRef(context.refDate, day, month);
      result.start.imply("year", year);
    }
    if (match2[DATE_TO_GROUP]) {
      const endDate = parseOrdinalNumberPattern(match2[DATE_TO_GROUP]);
      result.end = result.start.clone();
      result.end.assign("day", endDate);
    }
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENMonthNameMiddleEndianParser.js
var PATTERN2 = new RegExp(`(${matchAnyPattern(MONTH_DICTIONARY)})(?:-|/|\\s*,?\\s*)(${ORDINAL_NUMBER_PATTERN})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${ORDINAL_NUMBER_PATTERN})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${YEAR_PATTERN}))?(?=\\W|$)(?!\\:\\d)`, "i");
var MONTH_NAME_GROUP2 = 1;
var DATE_GROUP2 = 2;
var DATE_TO_GROUP2 = 3;
var YEAR_GROUP2 = 4;
var ENMonthNameMiddleEndianParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(shouldSkipYearLikeDate) {
    super();
    this.shouldSkipYearLikeDate = shouldSkipYearLikeDate;
  }
  innerPattern() {
    return PATTERN2;
  }
  innerExtract(context, match2) {
    const month = MONTH_DICTIONARY[match2[MONTH_NAME_GROUP2].toLowerCase()];
    const day = parseOrdinalNumberPattern(match2[DATE_GROUP2]);
    if (day > 31) {
      return null;
    }
    if (this.shouldSkipYearLikeDate) {
      if (!match2[DATE_TO_GROUP2] && !match2[YEAR_GROUP2] && match2[DATE_GROUP2].match(/^2[0-5]$/)) {
        return null;
      }
    }
    const components2 = context.createParsingComponents({
      day,
      month
    }).addTag("parser/ENMonthNameMiddleEndianParser");
    if (match2[YEAR_GROUP2]) {
      const year = parseYear(match2[YEAR_GROUP2]);
      components2.assign("year", year);
    } else {
      const year = findYearClosestToRef(context.refDate, day, month);
      components2.imply("year", year);
    }
    if (!match2[DATE_TO_GROUP2]) {
      return components2;
    }
    const endDate = parseOrdinalNumberPattern(match2[DATE_TO_GROUP2]);
    const result = context.createParsingResult(match2.index, match2[0]);
    result.start = components2;
    result.end = components2.clone();
    result.end.assign("day", endDate);
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENMonthNameParser.js
var PATTERN3 = new RegExp(`((?:in)\\s*)?(${matchAnyPattern(MONTH_DICTIONARY)})\\s*(?:[,-]?\\s*(${YEAR_PATTERN})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`, "i");
var PREFIX_GROUP = 1;
var MONTH_NAME_GROUP3 = 2;
var YEAR_GROUP3 = 3;
var ENMonthNameParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN3;
  }
  innerExtract(context, match2) {
    const monthName = match2[MONTH_NAME_GROUP3].toLowerCase();
    if (match2[0].length <= 3 && !FULL_MONTH_NAME_DICTIONARY[monthName]) {
      return null;
    }
    const result = context.createParsingResult(match2.index + (match2[PREFIX_GROUP] || "").length, match2.index + match2[0].length);
    result.start.imply("day", 1);
    result.start.addTag("parser/ENMonthNameParser");
    const month = MONTH_DICTIONARY[monthName];
    result.start.assign("month", month);
    if (match2[YEAR_GROUP3]) {
      const year = parseYear(match2[YEAR_GROUP3]);
      result.start.assign("year", year);
    } else {
      const year = findYearClosestToRef(context.refDate, 1, month);
      result.start.imply("year", year);
    }
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENYearMonthDayParser.js
var PATTERN4 = new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${matchAnyPattern(MONTH_DICTIONARY)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`, "i");
var YEAR_NUMBER_GROUP = 1;
var MONTH_NAME_GROUP4 = 2;
var MONTH_NUMBER_GROUP = 3;
var DATE_NUMBER_GROUP = 4;
var ENYearMonthDayParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(strictMonthDateOrder) {
    super();
    this.strictMonthDateOrder = strictMonthDateOrder;
  }
  innerPattern() {
    return PATTERN4;
  }
  innerExtract(context, match2) {
    const year = parseInt(match2[YEAR_NUMBER_GROUP]);
    let day = parseInt(match2[DATE_NUMBER_GROUP]);
    let month = match2[MONTH_NUMBER_GROUP] ? parseInt(match2[MONTH_NUMBER_GROUP]) : MONTH_DICTIONARY[match2[MONTH_NAME_GROUP4].toLowerCase()];
    if (month < 1 || month > 12) {
      if (this.strictMonthDateOrder) {
        return null;
      }
      if (day >= 1 && day <= 12) {
        [month, day] = [day, month];
      }
    }
    if (day < 1 || day > 31) {
      return null;
    }
    return {
      day,
      month,
      year
    };
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENSlashMonthFormatParser.js
var PATTERN5 = new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})", "i");
var MONTH_GROUP = 1;
var YEAR_GROUP4 = 2;
var ENSlashMonthFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN5;
  }
  innerExtract(context, match2) {
    const year = parseInt(match2[YEAR_GROUP4]);
    const month = parseInt(match2[MONTH_GROUP]);
    return context.createParsingComponents().imply("day", 1).assign("month", month).assign("year", year);
  }
};

// node_modules/chrono-node/dist/esm/common/parsers/AbstractTimeExpressionParser.js
function primaryTimePattern(leftBoundary, primaryPrefix, primarySuffix, flags) {
  return new RegExp(`${leftBoundary}${primaryPrefix}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${primarySuffix}`, flags);
}
function followingTimePatten(followingPhase, followingSuffix) {
  return new RegExp(`^(${followingPhase})(\\d{1,4})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${followingSuffix}`, "i");
}
var HOUR_GROUP = 2;
var MINUTE_GROUP = 3;
var SECOND_GROUP = 4;
var MILLI_SECOND_GROUP = 5;
var AM_PM_HOUR_GROUP = 6;
var AbstractTimeExpressionParser = class {
  constructor(strictMode = false) {
    this.cachedPrimaryPrefix = null;
    this.cachedPrimarySuffix = null;
    this.cachedPrimaryTimePattern = null;
    this.cachedFollowingPhase = null;
    this.cachedFollowingSuffix = null;
    this.cachedFollowingTimePatten = null;
    this.strictMode = strictMode;
  }
  patternFlags() {
    return "i";
  }
  primaryPatternLeftBoundary() {
    return `(^|\\s|T|\\b)`;
  }
  primarySuffix() {
    return `(?!/)(?=\\W|$)`;
  }
  followingSuffix() {
    return `(?!/)(?=\\W|$)`;
  }
  pattern(context) {
    return this.getPrimaryTimePatternThroughCache();
  }
  extract(context, match2) {
    const startComponents = this.extractPrimaryTimeComponents(context, match2);
    if (!startComponents) {
      if (match2[0].match(/^\d{4}/)) {
        match2.index += 4;
        return null;
      }
      match2.index += match2[0].length;
      return null;
    }
    const index2 = match2.index + match2[1].length;
    const text = match2[0].substring(match2[1].length);
    const result = context.createParsingResult(index2, text, startComponents);
    match2.index += match2[0].length;
    const remainingText = context.text.substring(match2.index);
    const followingPattern = this.getFollowingTimePatternThroughCache();
    const followingMatch = followingPattern.exec(remainingText);
    if (text.match(/^\d{3,4}/) && followingMatch) {
      if (followingMatch[0].match(/^\s*([+-])\s*\d{2,4}$/)) {
        return null;
      }
      if (followingMatch[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/)) {
        return null;
      }
    }
    if (!followingMatch || followingMatch[0].match(/^\s*([+-])\s*\d{3,4}$/)) {
      return this.checkAndReturnWithoutFollowingPattern(result);
    }
    result.end = this.extractFollowingTimeComponents(context, followingMatch, result);
    if (result.end) {
      result.text += followingMatch[0];
    }
    return this.checkAndReturnWithFollowingPattern(result);
  }
  extractPrimaryTimeComponents(context, match2, strict2 = false) {
    const components2 = context.createParsingComponents();
    let minute = 0;
    let meridiem = null;
    let hour = parseInt(match2[HOUR_GROUP]);
    if (hour > 100) {
      if (this.strictMode || match2[MINUTE_GROUP] != null) {
        return null;
      }
      minute = hour % 100;
      hour = Math.floor(hour / 100);
    }
    if (hour > 24) {
      return null;
    }
    if (match2[MINUTE_GROUP] != null) {
      if (match2[MINUTE_GROUP].length == 1 && !match2[AM_PM_HOUR_GROUP]) {
        return null;
      }
      minute = parseInt(match2[MINUTE_GROUP]);
    }
    if (minute >= 60) {
      return null;
    }
    if (hour > 12) {
      meridiem = Meridiem.PM;
    }
    if (match2[AM_PM_HOUR_GROUP] != null) {
      if (hour > 12)
        return null;
      const ampm = match2[AM_PM_HOUR_GROUP][0].toLowerCase();
      if (ampm == "a") {
        meridiem = Meridiem.AM;
        if (hour == 12) {
          hour = 0;
        }
      }
      if (ampm == "p") {
        meridiem = Meridiem.PM;
        if (hour != 12) {
          hour += 12;
        }
      }
    }
    components2.assign("hour", hour);
    components2.assign("minute", minute);
    if (meridiem !== null) {
      components2.assign("meridiem", meridiem);
    } else {
      if (hour < 12) {
        components2.imply("meridiem", Meridiem.AM);
      } else {
        components2.imply("meridiem", Meridiem.PM);
      }
    }
    if (match2[MILLI_SECOND_GROUP] != null) {
      const millisecond = parseInt(match2[MILLI_SECOND_GROUP].substring(0, 3));
      if (millisecond >= 1e3)
        return null;
      components2.assign("millisecond", millisecond);
    }
    if (match2[SECOND_GROUP] != null) {
      const second2 = parseInt(match2[SECOND_GROUP]);
      if (second2 >= 60)
        return null;
      components2.assign("second", second2);
    }
    return components2;
  }
  extractFollowingTimeComponents(context, match2, result) {
    const components2 = context.createParsingComponents();
    if (match2[MILLI_SECOND_GROUP] != null) {
      const millisecond = parseInt(match2[MILLI_SECOND_GROUP].substring(0, 3));
      if (millisecond >= 1e3)
        return null;
      components2.assign("millisecond", millisecond);
    }
    if (match2[SECOND_GROUP] != null) {
      const second2 = parseInt(match2[SECOND_GROUP]);
      if (second2 >= 60)
        return null;
      components2.assign("second", second2);
    }
    let hour = parseInt(match2[HOUR_GROUP]);
    let minute = 0;
    let meridiem = -1;
    if (match2[MINUTE_GROUP] != null) {
      minute = parseInt(match2[MINUTE_GROUP]);
    } else if (hour > 100) {
      minute = hour % 100;
      hour = Math.floor(hour / 100);
    }
    if (minute >= 60 || hour > 24) {
      return null;
    }
    if (hour >= 12) {
      meridiem = Meridiem.PM;
    }
    if (match2[AM_PM_HOUR_GROUP] != null) {
      if (hour > 12) {
        return null;
      }
      const ampm = match2[AM_PM_HOUR_GROUP][0].toLowerCase();
      if (ampm == "a") {
        meridiem = Meridiem.AM;
        if (hour == 12) {
          hour = 0;
          if (!components2.isCertain("day")) {
            components2.imply("day", components2.get("day") + 1);
          }
        }
      }
      if (ampm == "p") {
        meridiem = Meridiem.PM;
        if (hour != 12)
          hour += 12;
      }
      if (!result.start.isCertain("meridiem")) {
        if (meridiem == Meridiem.AM) {
          result.start.imply("meridiem", Meridiem.AM);
          if (result.start.get("hour") == 12) {
            result.start.assign("hour", 0);
          }
        } else {
          result.start.imply("meridiem", Meridiem.PM);
          if (result.start.get("hour") != 12) {
            result.start.assign("hour", result.start.get("hour") + 12);
          }
        }
      }
    }
    components2.assign("hour", hour);
    components2.assign("minute", minute);
    if (meridiem >= 0) {
      components2.assign("meridiem", meridiem);
    } else {
      const startAtPM = result.start.isCertain("meridiem") && result.start.get("hour") > 12;
      if (startAtPM) {
        if (result.start.get("hour") - 12 > hour) {
          components2.imply("meridiem", Meridiem.AM);
        } else if (hour <= 12) {
          components2.assign("hour", hour + 12);
          components2.assign("meridiem", Meridiem.PM);
        }
      } else if (hour > 12) {
        components2.imply("meridiem", Meridiem.PM);
      } else if (hour <= 12) {
        components2.imply("meridiem", Meridiem.AM);
      }
    }
    if (components2.date().getTime() < result.start.date().getTime()) {
      components2.imply("day", components2.get("day") + 1);
    }
    return components2;
  }
  checkAndReturnWithoutFollowingPattern(result) {
    if (result.text.match(/^\d$/)) {
      return null;
    }
    if (result.text.match(/^\d\d\d+$/)) {
      return null;
    }
    if (result.text.match(/\d[apAP]$/)) {
      return null;
    }
    const endingWithNumbers = result.text.match(/[^\d:.](\d[\d.]+)$/);
    if (endingWithNumbers) {
      const endingNumbers = endingWithNumbers[1];
      if (this.strictMode) {
        return null;
      }
      if (endingNumbers.includes(".") && !endingNumbers.match(/\d(\.\d{2})+$/)) {
        return null;
      }
      const endingNumberVal = parseInt(endingNumbers);
      if (endingNumberVal > 24) {
        return null;
      }
    }
    return result;
  }
  checkAndReturnWithFollowingPattern(result) {
    if (result.text.match(/^\d+-\d+$/)) {
      return null;
    }
    const endingWithNumbers = result.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);
    if (endingWithNumbers) {
      if (this.strictMode) {
        return null;
      }
      const startingNumbers = endingWithNumbers[1];
      const endingNumbers = endingWithNumbers[2];
      if (endingNumbers.includes(".") && !endingNumbers.match(/\d(\.\d{2})+$/)) {
        return null;
      }
      const endingNumberVal = parseInt(endingNumbers);
      const startingNumberVal = parseInt(startingNumbers);
      if (endingNumberVal > 24 || startingNumberVal > 24) {
        return null;
      }
    }
    return result;
  }
  getPrimaryTimePatternThroughCache() {
    const primaryPrefix = this.primaryPrefix();
    const primarySuffix = this.primarySuffix();
    if (this.cachedPrimaryPrefix === primaryPrefix && this.cachedPrimarySuffix === primarySuffix) {
      return this.cachedPrimaryTimePattern;
    }
    this.cachedPrimaryTimePattern = primaryTimePattern(this.primaryPatternLeftBoundary(), primaryPrefix, primarySuffix, this.patternFlags());
    this.cachedPrimaryPrefix = primaryPrefix;
    this.cachedPrimarySuffix = primarySuffix;
    return this.cachedPrimaryTimePattern;
  }
  getFollowingTimePatternThroughCache() {
    const followingPhase = this.followingPhase();
    const followingSuffix = this.followingSuffix();
    if (this.cachedFollowingPhase === followingPhase && this.cachedFollowingSuffix === followingSuffix) {
      return this.cachedFollowingTimePatten;
    }
    this.cachedFollowingTimePatten = followingTimePatten(followingPhase, followingSuffix);
    this.cachedFollowingPhase = followingPhase;
    this.cachedFollowingSuffix = followingSuffix;
    return this.cachedFollowingTimePatten;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENTimeExpressionParser.js
var ENTimeExpressionParser = class extends AbstractTimeExpressionParser {
  constructor(strictMode) {
    super(strictMode);
  }
  followingPhase() {
    return "\\s*(?:\\-|\\\u2013|\\~|\\\u301C|to|until|through|till|\\?)\\s*";
  }
  primaryPrefix() {
    return "(?:(?:at|from)\\s*)??";
  }
  primarySuffix() {
    return "(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)";
  }
  extractPrimaryTimeComponents(context, match2) {
    const components2 = super.extractPrimaryTimeComponents(context, match2);
    if (!components2) {
      return components2;
    }
    if (match2[0].endsWith("night")) {
      const hour = components2.get("hour");
      if (hour >= 6 && hour < 12) {
        components2.assign("hour", components2.get("hour") + 12);
        components2.assign("meridiem", Meridiem.PM);
      } else if (hour < 6) {
        components2.assign("meridiem", Meridiem.AM);
      }
    }
    if (match2[0].endsWith("afternoon")) {
      components2.assign("meridiem", Meridiem.PM);
      const hour = components2.get("hour");
      if (hour >= 0 && hour <= 6) {
        components2.assign("hour", components2.get("hour") + 12);
      }
    }
    if (match2[0].endsWith("morning")) {
      components2.assign("meridiem", Meridiem.AM);
      const hour = components2.get("hour");
      if (hour < 12) {
        components2.assign("hour", components2.get("hour"));
      }
    }
    return components2.addTag("parser/ENTimeExpressionParser");
  }
};

// node_modules/chrono-node/dist/esm/utils/timeunits.js
function reverseTimeUnits(timeUnits) {
  const reversed = {};
  for (const key in timeUnits) {
    reversed[key] = -timeUnits[key];
  }
  return reversed;
}
function addImpliedTimeUnits(components2, timeUnits) {
  const output = components2.clone();
  let date2 = components2.dayjs();
  for (const key in timeUnits) {
    date2 = date2.add(timeUnits[key], key);
  }
  if ("day" in timeUnits || "d" in timeUnits || "week" in timeUnits || "month" in timeUnits || "year" in timeUnits) {
    output.imply("day", date2.date());
    output.imply("month", date2.month() + 1);
    output.imply("year", date2.year());
  }
  if ("second" in timeUnits || "minute" in timeUnits || "hour" in timeUnits) {
    output.imply("second", date2.second());
    output.imply("minute", date2.minute());
    output.imply("hour", date2.hour());
  }
  return output;
}

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENTimeUnitAgoFormatParser.js
var PATTERN6 = new RegExp(`(${TIME_UNITS_PATTERN})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`, "i");
var STRICT_PATTERN = new RegExp(`(${TIME_UNITS_NO_ABBR_PATTERN})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`, "i");
var ENTimeUnitAgoFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(strictMode) {
    super();
    this.strictMode = strictMode;
  }
  innerPattern() {
    return this.strictMode ? STRICT_PATTERN : PATTERN6;
  }
  innerExtract(context, match2) {
    const timeUnits = parseTimeUnits(match2[1]);
    if (!timeUnits) {
      return null;
    }
    const outputTimeUnits = reverseTimeUnits(timeUnits);
    return ParsingComponents.createRelativeFromReference(context.reference, outputTimeUnits);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENTimeUnitLaterFormatParser.js
var PATTERN7 = new RegExp(`(${TIME_UNITS_PATTERN})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`, "i");
var STRICT_PATTERN2 = new RegExp(`(${TIME_UNITS_NO_ABBR_PATTERN})\\s{0,5}(later|after|from now)(?=\\W|$)`, "i");
var GROUP_NUM_TIMEUNITS = 1;
var ENTimeUnitLaterFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(strictMode) {
    super();
    this.strictMode = strictMode;
  }
  innerPattern() {
    return this.strictMode ? STRICT_PATTERN2 : PATTERN7;
  }
  innerExtract(context, match2) {
    const timeUnits = parseTimeUnits(match2[GROUP_NUM_TIMEUNITS]);
    if (!timeUnits) {
      return null;
    }
    return ParsingComponents.createRelativeFromReference(context.reference, timeUnits);
  }
};

// node_modules/chrono-node/dist/esm/common/abstractRefiners.js
var Filter = class {
  refine(context, results) {
    return results.filter((r4) => this.isValid(context, r4));
  }
};
var MergingRefiner = class {
  refine(context, results) {
    if (results.length < 2) {
      return results;
    }
    const mergedResults = [];
    let curResult = results[0];
    let nextResult = null;
    for (let i3 = 1; i3 < results.length; i3++) {
      nextResult = results[i3];
      const textBetween = context.text.substring(curResult.index + curResult.text.length, nextResult.index);
      if (!this.shouldMergeResults(textBetween, curResult, nextResult, context)) {
        mergedResults.push(curResult);
        curResult = nextResult;
      } else {
        const left = curResult;
        const right = nextResult;
        const mergedResult = this.mergeResults(textBetween, left, right, context);
        context.debug(() => {
          console.log(`${this.constructor.name} merged ${left} and ${right} into ${mergedResult}`);
        });
        curResult = mergedResult;
      }
    }
    if (curResult != null) {
      mergedResults.push(curResult);
    }
    return mergedResults;
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/AbstractMergeDateRangeRefiner.js
var AbstractMergeDateRangeRefiner = class extends MergingRefiner {
  shouldMergeResults(textBetween, currentResult, nextResult) {
    return !currentResult.end && !nextResult.end && textBetween.match(this.patternBetween()) != null;
  }
  mergeResults(textBetween, fromResult, toResult) {
    if (!fromResult.start.isOnlyWeekdayComponent() && !toResult.start.isOnlyWeekdayComponent()) {
      toResult.start.getCertainComponents().forEach((key) => {
        if (!fromResult.start.isCertain(key)) {
          fromResult.start.imply(key, toResult.start.get(key));
        }
      });
      fromResult.start.getCertainComponents().forEach((key) => {
        if (!toResult.start.isCertain(key)) {
          toResult.start.imply(key, fromResult.start.get(key));
        }
      });
    }
    if (fromResult.start.date().getTime() > toResult.start.date().getTime()) {
      let fromMoment = fromResult.start.dayjs();
      let toMoment = toResult.start.dayjs();
      if (toResult.start.isOnlyWeekdayComponent() && toMoment.add(7, "days").isAfter(fromMoment)) {
        toMoment = toMoment.add(7, "days");
        toResult.start.imply("day", toMoment.date());
        toResult.start.imply("month", toMoment.month() + 1);
        toResult.start.imply("year", toMoment.year());
      } else if (fromResult.start.isOnlyWeekdayComponent() && fromMoment.add(-7, "days").isBefore(toMoment)) {
        fromMoment = fromMoment.add(-7, "days");
        fromResult.start.imply("day", fromMoment.date());
        fromResult.start.imply("month", fromMoment.month() + 1);
        fromResult.start.imply("year", fromMoment.year());
      } else if (toResult.start.isDateWithUnknownYear() && toMoment.add(1, "years").isAfter(fromMoment)) {
        toMoment = toMoment.add(1, "years");
        toResult.start.imply("year", toMoment.year());
      } else if (fromResult.start.isDateWithUnknownYear() && fromMoment.add(-1, "years").isBefore(toMoment)) {
        fromMoment = fromMoment.add(-1, "years");
        fromResult.start.imply("year", fromMoment.year());
      } else {
        [toResult, fromResult] = [fromResult, toResult];
      }
    }
    const result = fromResult.clone();
    result.start = fromResult.start;
    result.end = toResult.start;
    result.index = Math.min(fromResult.index, toResult.index);
    if (fromResult.index < toResult.index) {
      result.text = fromResult.text + textBetween + toResult.text;
    } else {
      result.text = toResult.text + textBetween + fromResult.text;
    }
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/refiners/ENMergeDateRangeRefiner.js
var ENMergeDateRangeRefiner = class extends AbstractMergeDateRangeRefiner {
  patternBetween() {
    return /^\s*(to|-|–|until|through|till)\s*$/i;
  }
};

// node_modules/chrono-node/dist/esm/calculation/mergingCalculation.js
function mergeDateTimeResult(dateResult, timeResult) {
  const result = dateResult.clone();
  const beginDate = dateResult.start;
  const beginTime = timeResult.start;
  result.start = mergeDateTimeComponent(beginDate, beginTime);
  if (dateResult.end != null || timeResult.end != null) {
    const endDate = dateResult.end == null ? dateResult.start : dateResult.end;
    const endTime = timeResult.end == null ? timeResult.start : timeResult.end;
    const endDateTime = mergeDateTimeComponent(endDate, endTime);
    if (dateResult.end == null && endDateTime.date().getTime() < result.start.date().getTime()) {
      const nextDayJs = endDateTime.dayjs().add(1, "day");
      if (endDateTime.isCertain("day")) {
        assignSimilarDate(endDateTime, nextDayJs);
      } else {
        implySimilarDate(endDateTime, nextDayJs);
      }
    }
    result.end = endDateTime;
  }
  return result;
}
function mergeDateTimeComponent(dateComponent, timeComponent) {
  const dateTimeComponent = dateComponent.clone();
  if (timeComponent.isCertain("hour")) {
    dateTimeComponent.assign("hour", timeComponent.get("hour"));
    dateTimeComponent.assign("minute", timeComponent.get("minute"));
    if (timeComponent.isCertain("second")) {
      dateTimeComponent.assign("second", timeComponent.get("second"));
      if (timeComponent.isCertain("millisecond")) {
        dateTimeComponent.assign("millisecond", timeComponent.get("millisecond"));
      } else {
        dateTimeComponent.imply("millisecond", timeComponent.get("millisecond"));
      }
    } else {
      dateTimeComponent.imply("second", timeComponent.get("second"));
      dateTimeComponent.imply("millisecond", timeComponent.get("millisecond"));
    }
  } else {
    dateTimeComponent.imply("hour", timeComponent.get("hour"));
    dateTimeComponent.imply("minute", timeComponent.get("minute"));
    dateTimeComponent.imply("second", timeComponent.get("second"));
    dateTimeComponent.imply("millisecond", timeComponent.get("millisecond"));
  }
  if (timeComponent.isCertain("timezoneOffset")) {
    dateTimeComponent.assign("timezoneOffset", timeComponent.get("timezoneOffset"));
  }
  if (timeComponent.isCertain("meridiem")) {
    dateTimeComponent.assign("meridiem", timeComponent.get("meridiem"));
  } else if (timeComponent.get("meridiem") != null && dateTimeComponent.get("meridiem") == null) {
    dateTimeComponent.imply("meridiem", timeComponent.get("meridiem"));
  }
  if (dateTimeComponent.get("meridiem") == Meridiem.PM && dateTimeComponent.get("hour") < 12) {
    if (timeComponent.isCertain("hour")) {
      dateTimeComponent.assign("hour", dateTimeComponent.get("hour") + 12);
    } else {
      dateTimeComponent.imply("hour", dateTimeComponent.get("hour") + 12);
    }
  }
  dateTimeComponent.addTags(dateComponent.tags());
  dateTimeComponent.addTags(timeComponent.tags());
  return dateTimeComponent;
}

// node_modules/chrono-node/dist/esm/common/refiners/AbstractMergeDateTimeRefiner.js
var AbstractMergeDateTimeRefiner = class extends MergingRefiner {
  shouldMergeResults(textBetween, currentResult, nextResult) {
    return (currentResult.start.isOnlyDate() && nextResult.start.isOnlyTime() || nextResult.start.isOnlyDate() && currentResult.start.isOnlyTime()) && textBetween.match(this.patternBetween()) != null;
  }
  mergeResults(textBetween, currentResult, nextResult) {
    const result = currentResult.start.isOnlyDate() ? mergeDateTimeResult(currentResult, nextResult) : mergeDateTimeResult(nextResult, currentResult);
    result.index = currentResult.index;
    result.text = currentResult.text + textBetween + nextResult.text;
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/refiners/ENMergeDateTimeRefiner.js
var ENMergeDateTimeRefiner = class extends AbstractMergeDateTimeRefiner {
  patternBetween() {
    return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$");
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/ExtractTimezoneAbbrRefiner.js
var TIMEZONE_NAME_PATTERN = new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)", "i");
var ExtractTimezoneAbbrRefiner = class {
  constructor(timezoneOverrides) {
    this.timezoneOverrides = timezoneOverrides;
  }
  refine(context, results) {
    const timezoneOverrides = context.option.timezones ?? {};
    results.forEach((result) => {
      const suffix = context.text.substring(result.index + result.text.length);
      const match2 = TIMEZONE_NAME_PATTERN.exec(suffix);
      if (!match2) {
        return;
      }
      const timezoneAbbr = match2[1].toUpperCase();
      const refDate = result.start.date() ?? result.refDate ?? new Date();
      const tzOverrides = { ...this.timezoneOverrides, ...timezoneOverrides };
      const extractedTimezoneOffset = toTimezoneOffset(timezoneAbbr, refDate, tzOverrides);
      if (extractedTimezoneOffset == null) {
        return;
      }
      context.debug(() => {
        console.log(`Extracting timezone: '${timezoneAbbr}' into: ${extractedTimezoneOffset} for: ${result.start}`);
      });
      const currentTimezoneOffset = result.start.get("timezoneOffset");
      if (currentTimezoneOffset !== null && extractedTimezoneOffset != currentTimezoneOffset) {
        if (result.start.isCertain("timezoneOffset")) {
          return;
        }
        if (timezoneAbbr != match2[1]) {
          return;
        }
      }
      if (result.start.isOnlyDate()) {
        if (timezoneAbbr != match2[1]) {
          return;
        }
      }
      result.text += match2[0];
      if (!result.start.isCertain("timezoneOffset")) {
        result.start.assign("timezoneOffset", extractedTimezoneOffset);
      }
      if (result.end != null && !result.end.isCertain("timezoneOffset")) {
        result.end.assign("timezoneOffset", extractedTimezoneOffset);
      }
    });
    return results;
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/ExtractTimezoneOffsetRefiner.js
var TIMEZONE_OFFSET_PATTERN = new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?", "i");
var TIMEZONE_OFFSET_SIGN_GROUP = 1;
var TIMEZONE_OFFSET_HOUR_OFFSET_GROUP = 2;
var TIMEZONE_OFFSET_MINUTE_OFFSET_GROUP = 3;
var ExtractTimezoneOffsetRefiner = class {
  refine(context, results) {
    results.forEach(function(result) {
      if (result.start.isCertain("timezoneOffset")) {
        return;
      }
      const suffix = context.text.substring(result.index + result.text.length);
      const match2 = TIMEZONE_OFFSET_PATTERN.exec(suffix);
      if (!match2) {
        return;
      }
      context.debug(() => {
        console.log(`Extracting timezone: '${match2[0]}' into : ${result}`);
      });
      const hourOffset = parseInt(match2[TIMEZONE_OFFSET_HOUR_OFFSET_GROUP]);
      const minuteOffset = parseInt(match2[TIMEZONE_OFFSET_MINUTE_OFFSET_GROUP] || "0");
      let timezoneOffset = hourOffset * 60 + minuteOffset;
      if (timezoneOffset > 14 * 60) {
        return;
      }
      if (match2[TIMEZONE_OFFSET_SIGN_GROUP] === "-") {
        timezoneOffset = -timezoneOffset;
      }
      if (result.end != null) {
        result.end.assign("timezoneOffset", timezoneOffset);
      }
      result.start.assign("timezoneOffset", timezoneOffset);
      result.text += match2[0];
    });
    return results;
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/OverlapRemovalRefiner.js
var OverlapRemovalRefiner = class {
  refine(context, results) {
    if (results.length < 2) {
      return results;
    }
    const filteredResults = [];
    let prevResult = results[0];
    for (let i3 = 1; i3 < results.length; i3++) {
      const result = results[i3];
      if (result.index >= prevResult.index + prevResult.text.length) {
        filteredResults.push(prevResult);
        prevResult = result;
        continue;
      }
      let kept = null;
      let removed = null;
      if (result.text.length > prevResult.text.length) {
        kept = result;
        removed = prevResult;
      } else {
        kept = prevResult;
        removed = result;
      }
      context.debug(() => {
        console.log(`${this.constructor.name} remove ${removed} by ${kept}`);
      });
      prevResult = kept;
    }
    if (prevResult != null) {
      filteredResults.push(prevResult);
    }
    return filteredResults;
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/ForwardDateRefiner.js
var import_dayjs6 = __toESM(require_dayjs_min(), 1);
var ForwardDateRefiner = class {
  refine(context, results) {
    if (!context.option.forwardDate) {
      return results;
    }
    results.forEach((result) => {
      let refMoment = (0, import_dayjs6.default)(context.refDate);
      if (result.start.isOnlyTime() && refMoment.isAfter(result.start.dayjs())) {
        refMoment = refMoment.add(1, "day");
        implySimilarDate(result.start, refMoment);
        if (result.end && result.end.isOnlyTime()) {
          implySimilarDate(result.end, refMoment);
          if (result.start.dayjs().isAfter(result.end.dayjs())) {
            refMoment = refMoment.add(1, "day");
            implySimilarDate(result.end, refMoment);
          }
        }
        context.debug(() => {
          console.log(`${this.constructor.name} adjusted ${result} time result (${result.start})`);
        });
      }
      if (result.start.isOnlyWeekdayComponent() && refMoment.isAfter(result.start.dayjs())) {
        if (refMoment.day() >= result.start.get("weekday")) {
          refMoment = refMoment.day(result.start.get("weekday") + 7);
        } else {
          refMoment = refMoment.day(result.start.get("weekday"));
        }
        result.start.imply("day", refMoment.date());
        result.start.imply("month", refMoment.month() + 1);
        result.start.imply("year", refMoment.year());
        context.debug(() => {
          console.log(`${this.constructor.name} adjusted ${result} weekday (${result.start})`);
        });
        if (result.end && result.end.isOnlyWeekdayComponent()) {
          if (refMoment.day() > result.end.get("weekday")) {
            refMoment = refMoment.day(result.end.get("weekday") + 7);
          } else {
            refMoment = refMoment.day(result.end.get("weekday"));
          }
          result.end.imply("day", refMoment.date());
          result.end.imply("month", refMoment.month() + 1);
          result.end.imply("year", refMoment.year());
          context.debug(() => {
            console.log(`${this.constructor.name} adjusted ${result} weekday (${result.end})`);
          });
        }
      }
      if (result.start.isDateWithUnknownYear() && refMoment.isAfter(result.start.dayjs())) {
        for (let i3 = 0; i3 < 3 && refMoment.isAfter(result.start.dayjs()); i3++) {
          result.start.imply("year", result.start.get("year") + 1);
          context.debug(() => {
            console.log(`${this.constructor.name} adjusted ${result} year (${result.start})`);
          });
          if (result.end && !result.end.isCertain("year")) {
            result.end.imply("year", result.end.get("year") + 1);
            context.debug(() => {
              console.log(`${this.constructor.name} adjusted ${result} month (${result.start})`);
            });
          }
        }
      }
    });
    return results;
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/UnlikelyFormatFilter.js
var UnlikelyFormatFilter = class extends Filter {
  constructor(strictMode) {
    super();
    this.strictMode = strictMode;
  }
  isValid(context, result) {
    if (result.text.replace(" ", "").match(/^\d*(\.\d*)?$/)) {
      context.debug(() => {
        console.log(`Removing unlikely result '${result.text}'`);
      });
      return false;
    }
    if (!result.start.isValidDate()) {
      context.debug(() => {
        console.log(`Removing invalid result: ${result} (${result.start})`);
      });
      return false;
    }
    if (result.end && !result.end.isValidDate()) {
      context.debug(() => {
        console.log(`Removing invalid result: ${result} (${result.end})`);
      });
      return false;
    }
    if (this.strictMode) {
      return this.isStrictModeValid(context, result);
    }
    return true;
  }
  isStrictModeValid(context, result) {
    if (result.start.isOnlyWeekdayComponent()) {
      context.debug(() => {
        console.log(`(Strict) Removing weekday only component: ${result} (${result.end})`);
      });
      return false;
    }
    if (result.start.isOnlyTime() && (!result.start.isCertain("hour") || !result.start.isCertain("minute"))) {
      context.debug(() => {
        console.log(`(Strict) Removing uncertain time component: ${result} (${result.end})`);
      });
      return false;
    }
    return true;
  }
};

// node_modules/chrono-node/dist/esm/common/parsers/ISOFormatParser.js
var PATTERN8 = new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)", "i");
var YEAR_NUMBER_GROUP2 = 1;
var MONTH_NUMBER_GROUP2 = 2;
var DATE_NUMBER_GROUP2 = 3;
var HOUR_NUMBER_GROUP = 4;
var MINUTE_NUMBER_GROUP = 5;
var SECOND_NUMBER_GROUP = 6;
var MILLISECOND_NUMBER_GROUP = 7;
var TZD_GROUP = 8;
var TZD_HOUR_OFFSET_GROUP = 9;
var TZD_MINUTE_OFFSET_GROUP = 10;
var ISOFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN8;
  }
  innerExtract(context, match2) {
    const components2 = context.createParsingComponents({
      "year": parseInt(match2[YEAR_NUMBER_GROUP2]),
      "month": parseInt(match2[MONTH_NUMBER_GROUP2]),
      "day": parseInt(match2[DATE_NUMBER_GROUP2])
    });
    if (match2[HOUR_NUMBER_GROUP] != null) {
      components2.assign("hour", parseInt(match2[HOUR_NUMBER_GROUP]));
      components2.assign("minute", parseInt(match2[MINUTE_NUMBER_GROUP]));
      if (match2[SECOND_NUMBER_GROUP] != null) {
        components2.assign("second", parseInt(match2[SECOND_NUMBER_GROUP]));
      }
      if (match2[MILLISECOND_NUMBER_GROUP] != null) {
        components2.assign("millisecond", parseInt(match2[MILLISECOND_NUMBER_GROUP]));
      }
      if (match2[TZD_GROUP] != null) {
        let offset5 = 0;
        if (match2[TZD_HOUR_OFFSET_GROUP]) {
          const hourOffset = parseInt(match2[TZD_HOUR_OFFSET_GROUP]);
          let minuteOffset = 0;
          if (match2[TZD_MINUTE_OFFSET_GROUP] != null) {
            minuteOffset = parseInt(match2[TZD_MINUTE_OFFSET_GROUP]);
          }
          offset5 = hourOffset * 60;
          if (offset5 < 0) {
            offset5 -= minuteOffset;
          } else {
            offset5 += minuteOffset;
          }
        }
        components2.assign("timezoneOffset", offset5);
      }
    }
    return components2.addTag("parser/ISOFormatParser");
  }
};

// node_modules/chrono-node/dist/esm/common/refiners/MergeWeekdayComponentRefiner.js
var MergeWeekdayComponentRefiner = class extends MergingRefiner {
  mergeResults(textBetween, currentResult, nextResult) {
    const newResult = nextResult.clone();
    newResult.index = currentResult.index;
    newResult.text = currentResult.text + textBetween + newResult.text;
    newResult.start.assign("weekday", currentResult.start.get("weekday"));
    if (newResult.end) {
      newResult.end.assign("weekday", currentResult.start.get("weekday"));
    }
    return newResult;
  }
  shouldMergeResults(textBetween, currentResult, nextResult) {
    const weekdayThenNormalDate = currentResult.start.isOnlyWeekdayComponent() && !currentResult.start.isCertain("hour") && nextResult.start.isCertain("day");
    return weekdayThenNormalDate && textBetween.match(/^,?\s*$/) != null;
  }
};

// node_modules/chrono-node/dist/esm/configurations.js
function includeCommonConfiguration(configuration2, strictMode = false) {
  configuration2.parsers.unshift(new ISOFormatParser());
  configuration2.refiners.unshift(new MergeWeekdayComponentRefiner());
  configuration2.refiners.unshift(new ExtractTimezoneOffsetRefiner());
  configuration2.refiners.unshift(new OverlapRemovalRefiner());
  configuration2.refiners.push(new ExtractTimezoneAbbrRefiner());
  configuration2.refiners.push(new OverlapRemovalRefiner());
  configuration2.refiners.push(new ForwardDateRefiner());
  configuration2.refiners.push(new UnlikelyFormatFilter(strictMode));
  return configuration2;
}

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENCasualDateParser.js
var import_dayjs10 = __toESM(require_dayjs_min(), 1);

// node_modules/chrono-node/dist/esm/common/casualReferences.js
var import_dayjs8 = __toESM(require_dayjs_min(), 1);
function now(reference) {
  const targetDate = (0, import_dayjs8.default)(reference.instant);
  const component = new ParsingComponents(reference, {});
  assignSimilarDate(component, targetDate);
  assignSimilarTime(component, targetDate);
  if (reference.timezoneOffset !== null) {
    component.assign("timezoneOffset", targetDate.utcOffset());
  }
  component.addTag("casualReference/now");
  return component;
}
function today(reference) {
  const targetDate = (0, import_dayjs8.default)(reference.instant);
  const component = new ParsingComponents(reference, {});
  assignSimilarDate(component, targetDate);
  implySimilarTime(component, targetDate);
  component.addTag("casualReference/today");
  return component;
}
function yesterday(reference) {
  return theDayBefore(reference, 1).addTag("casualReference/yesterday");
}
function theDayBefore(reference, numDay) {
  return theDayAfter(reference, -numDay);
}
function tomorrow(reference) {
  return theDayAfter(reference, 1).addTag("casualReference/tomorrow");
}
function theDayAfter(reference, nDays) {
  let targetDate = (0, import_dayjs8.default)(reference.instant);
  const component = new ParsingComponents(reference, {});
  targetDate = targetDate.add(nDays, "day");
  assignSimilarDate(component, targetDate);
  implySimilarTime(component, targetDate);
  return component;
}
function tonight(reference, implyHour = 22) {
  const targetDate = (0, import_dayjs8.default)(reference.instant);
  const component = new ParsingComponents(reference, {});
  assignSimilarDate(component, targetDate);
  component.imply("hour", implyHour);
  component.imply("meridiem", Meridiem.PM);
  component.addTag("casualReference/tonight");
  return component;
}
function evening(reference, implyHour = 20) {
  const component = new ParsingComponents(reference, {});
  component.imply("meridiem", Meridiem.PM);
  component.imply("hour", implyHour);
  component.addTag("casualReference/evening");
  return component;
}
function midnight(reference) {
  const component = new ParsingComponents(reference, {});
  const targetDate = (0, import_dayjs8.default)(reference.instant);
  if (targetDate.hour() > 2) {
    implyTheNextDay(component, targetDate);
  }
  component.assign("hour", 0);
  component.imply("minute", 0);
  component.imply("second", 0);
  component.imply("millisecond", 0);
  component.addTag("casualReference/midnight");
  return component;
}
function morning(reference, implyHour = 6) {
  const component = new ParsingComponents(reference, {});
  component.imply("meridiem", Meridiem.AM);
  component.imply("hour", implyHour);
  component.imply("minute", 0);
  component.imply("second", 0);
  component.imply("millisecond", 0);
  component.addTag("casualReference/morning");
  return component;
}
function afternoon(reference, implyHour = 15) {
  const component = new ParsingComponents(reference, {});
  component.imply("meridiem", Meridiem.PM);
  component.imply("hour", implyHour);
  component.imply("minute", 0);
  component.imply("second", 0);
  component.imply("millisecond", 0);
  component.addTag("casualReference/afternoon");
  return component;
}
function noon(reference) {
  const component = new ParsingComponents(reference, {});
  component.imply("meridiem", Meridiem.AM);
  component.imply("hour", 12);
  component.imply("minute", 0);
  component.imply("second", 0);
  component.imply("millisecond", 0);
  component.addTag("casualReference/noon");
  return component;
}

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENCasualDateParser.js
var PATTERN9 = /(now|today|tonight|tomorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i;
var ENCasualDateParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern(context) {
    return PATTERN9;
  }
  innerExtract(context, match2) {
    let targetDate = (0, import_dayjs10.default)(context.refDate);
    const lowerText = match2[0].toLowerCase();
    let component = context.createParsingComponents();
    switch (lowerText) {
      case "now":
        component = now(context.reference);
        break;
      case "today":
        component = today(context.reference);
        break;
      case "yesterday":
        component = yesterday(context.reference);
        break;
      case "tomorrow":
      case "tmr":
      case "tmrw":
        component = tomorrow(context.reference);
        break;
      case "tonight":
        component = tonight(context.reference);
        break;
      default:
        if (lowerText.match(/last\s*night/)) {
          if (targetDate.hour() > 6) {
            targetDate = targetDate.add(-1, "day");
          }
          assignSimilarDate(component, targetDate);
          component.imply("hour", 0);
        }
        break;
    }
    component.addTag("parser/ENCasualDateParser");
    return component;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENCasualTimeParser.js
var PATTERN10 = /(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i;
var ENCasualTimeParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN10;
  }
  innerExtract(context, match2) {
    let component = null;
    switch (match2[1].toLowerCase()) {
      case "afternoon":
        component = afternoon(context.reference);
        break;
      case "evening":
      case "night":
        component = evening(context.reference);
        break;
      case "midnight":
        component = midnight(context.reference);
        break;
      case "morning":
        component = morning(context.reference);
        break;
      case "noon":
      case "midday":
        component = noon(context.reference);
        break;
    }
    if (component) {
      component.addTag("parser/ENCasualTimeParser");
    }
    return component;
  }
};

// node_modules/chrono-node/dist/esm/common/calculation/weekdays.js
function createParsingComponentsAtWeekday(reference, weekday, modifier) {
  const refDate = reference.getDateWithAdjustedTimezone();
  const daysToWeekday = getDaysToWeekday(refDate, weekday, modifier);
  let components2 = new ParsingComponents(reference);
  components2 = addImpliedTimeUnits(components2, { "day": daysToWeekday });
  components2.assign("weekday", weekday);
  return components2;
}
function getDaysToWeekday(refDate, weekday, modifier) {
  const refWeekday = refDate.getDay();
  switch (modifier) {
    case "this":
      return getDaysForwardToWeekday(refDate, weekday);
    case "last":
      return getBackwardDaysToWeekday(refDate, weekday);
    case "next":
      if (refWeekday == Weekday.SUNDAY) {
        return weekday == Weekday.SUNDAY ? 7 : weekday;
      }
      if (refWeekday == Weekday.SATURDAY) {
        if (weekday == Weekday.SATURDAY)
          return 7;
        if (weekday == Weekday.SUNDAY)
          return 8;
        return 1 + weekday;
      }
      if (weekday < refWeekday && weekday != Weekday.SUNDAY) {
        return getDaysForwardToWeekday(refDate, weekday);
      } else {
        return getDaysForwardToWeekday(refDate, weekday) + 7;
      }
  }
  return getDaysToWeekdayClosest(refDate, weekday);
}
function getDaysToWeekdayClosest(refDate, weekday) {
  const backward = getBackwardDaysToWeekday(refDate, weekday);
  const forward = getDaysForwardToWeekday(refDate, weekday);
  return forward < -backward ? forward : backward;
}
function getDaysForwardToWeekday(refDate, weekday) {
  const refWeekday = refDate.getDay();
  let forwardCount = weekday - refWeekday;
  if (forwardCount < 0) {
    forwardCount += 7;
  }
  return forwardCount;
}
function getBackwardDaysToWeekday(refDate, weekday) {
  const refWeekday = refDate.getDay();
  let backwardCount = weekday - refWeekday;
  if (backwardCount >= 0) {
    backwardCount -= 7;
  }
  return backwardCount;
}

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENWeekdayParser.js
var PATTERN11 = new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${matchAnyPattern(WEEKDAY_DICTIONARY)})(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(this|last|past|next)\\s*week)?(?=\\W|$)`, "i");
var PREFIX_GROUP2 = 1;
var WEEKDAY_GROUP = 2;
var POSTFIX_GROUP = 3;
var ENWeekdayParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN11;
  }
  innerExtract(context, match2) {
    const dayOfWeek2 = match2[WEEKDAY_GROUP].toLowerCase();
    const weekday = WEEKDAY_DICTIONARY[dayOfWeek2];
    const prefix = match2[PREFIX_GROUP2];
    const postfix = match2[POSTFIX_GROUP];
    let modifierWord = prefix || postfix;
    modifierWord = modifierWord || "";
    modifierWord = modifierWord.toLowerCase();
    let modifier = null;
    if (modifierWord == "last" || modifierWord == "past") {
      modifier = "last";
    } else if (modifierWord == "next") {
      modifier = "next";
    } else if (modifierWord == "this") {
      modifier = "this";
    }
    return createParsingComponentsAtWeekday(context.reference, weekday, modifier);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENRelativeDateFormatParser.js
var import_dayjs12 = __toESM(require_dayjs_min(), 1);
var PATTERN12 = new RegExp(`(this|last|past|next|after\\s*this)\\s*(${matchAnyPattern(TIME_UNIT_DICTIONARY)})(?=\\s*)(?=\\W|$)`, "i");
var MODIFIER_WORD_GROUP = 1;
var RELATIVE_WORD_GROUP = 2;
var ENRelativeDateFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  innerPattern() {
    return PATTERN12;
  }
  innerExtract(context, match2) {
    const modifier = match2[MODIFIER_WORD_GROUP].toLowerCase();
    const unitWord = match2[RELATIVE_WORD_GROUP].toLowerCase();
    const timeunit = TIME_UNIT_DICTIONARY[unitWord];
    if (modifier == "next" || modifier.startsWith("after")) {
      const timeUnits = {};
      timeUnits[timeunit] = 1;
      return ParsingComponents.createRelativeFromReference(context.reference, timeUnits);
    }
    if (modifier == "last" || modifier == "past") {
      const timeUnits = {};
      timeUnits[timeunit] = -1;
      return ParsingComponents.createRelativeFromReference(context.reference, timeUnits);
    }
    const components2 = context.createParsingComponents();
    let date2 = (0, import_dayjs12.default)(context.reference.instant);
    if (unitWord.match(/week/i)) {
      date2 = date2.add(-date2.get("d"), "d");
      components2.imply("day", date2.date());
      components2.imply("month", date2.month() + 1);
      components2.imply("year", date2.year());
    } else if (unitWord.match(/month/i)) {
      date2 = date2.add(-date2.date() + 1, "d");
      components2.imply("day", date2.date());
      components2.assign("year", date2.year());
      components2.assign("month", date2.month() + 1);
    } else if (unitWord.match(/year/i)) {
      date2 = date2.add(-date2.date() + 1, "d");
      date2 = date2.add(-date2.month(), "month");
      components2.imply("day", date2.date());
      components2.imply("month", date2.month() + 1);
      components2.assign("year", date2.year());
    }
    return components2;
  }
};

// node_modules/chrono-node/dist/esm/common/parsers/SlashDateFormatParser.js
var PATTERN13 = new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)", "i");
var OPENING_GROUP = 1;
var ENDING_GROUP = 5;
var FIRST_NUMBERS_GROUP = 2;
var SECOND_NUMBERS_GROUP = 3;
var YEAR_GROUP5 = 4;
var SlashDateFormatParser = class {
  constructor(littleEndian) {
    this.groupNumberMonth = littleEndian ? SECOND_NUMBERS_GROUP : FIRST_NUMBERS_GROUP;
    this.groupNumberDay = littleEndian ? FIRST_NUMBERS_GROUP : SECOND_NUMBERS_GROUP;
  }
  pattern() {
    return PATTERN13;
  }
  extract(context, match2) {
    const index2 = match2.index + match2[OPENING_GROUP].length;
    const indexEnd = match2.index + match2[0].length - match2[ENDING_GROUP].length;
    if (index2 > 0) {
      const textBefore = context.text.substring(0, index2);
      if (textBefore.match("\\d/?$")) {
        return;
      }
    }
    if (indexEnd < context.text.length) {
      const textAfter = context.text.substring(indexEnd);
      if (textAfter.match("^/?\\d")) {
        return;
      }
    }
    const text = context.text.substring(index2, indexEnd);
    if (text.match(/^\d\.\d$/) || text.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)) {
      return;
    }
    if (!match2[YEAR_GROUP5] && text.indexOf("/") < 0) {
      return;
    }
    const result = context.createParsingResult(index2, text);
    let month = parseInt(match2[this.groupNumberMonth]);
    let day = parseInt(match2[this.groupNumberDay]);
    if (month < 1 || month > 12) {
      if (month > 12) {
        if (day >= 1 && day <= 12 && month <= 31) {
          [day, month] = [month, day];
        } else {
          return null;
        }
      }
    }
    if (day < 1 || day > 31) {
      return null;
    }
    result.start.assign("day", day);
    result.start.assign("month", month);
    if (match2[YEAR_GROUP5]) {
      const rawYearNumber = parseInt(match2[YEAR_GROUP5]);
      const year = findMostLikelyADYear(rawYearNumber);
      result.start.assign("year", year);
    } else {
      const year = findYearClosestToRef(context.refDate, day, month);
      result.start.imply("year", year);
    }
    return result;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/parsers/ENTimeUnitCasualRelativeFormatParser.js
var PATTERN14 = new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${TIME_UNITS_PATTERN})(?=\\W|$)`, "i");
var PATTERN_NO_ABBR = new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${TIME_UNITS_NO_ABBR_PATTERN})(?=\\W|$)`, "i");
var ENTimeUnitCasualRelativeFormatParser = class extends AbstractParserWithWordBoundaryChecking {
  constructor(allowAbbreviations = true) {
    super();
    this.allowAbbreviations = allowAbbreviations;
  }
  innerPattern() {
    return this.allowAbbreviations ? PATTERN14 : PATTERN_NO_ABBR;
  }
  innerExtract(context, match2) {
    const prefix = match2[1].toLowerCase();
    let timeUnits = parseTimeUnits(match2[2]);
    if (!timeUnits) {
      return null;
    }
    switch (prefix) {
      case "last":
      case "past":
      case "-":
        timeUnits = reverseTimeUnits(timeUnits);
        break;
    }
    return ParsingComponents.createRelativeFromReference(context.reference, timeUnits);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/refiners/ENMergeRelativeAfterDateRefiner.js
function IsPositiveFollowingReference(result) {
  return result.text.match(/^[+-]/i) != null;
}
function IsNegativeFollowingReference(result) {
  return result.text.match(/^-/i) != null;
}
var ENMergeRelativeAfterDateRefiner = class extends MergingRefiner {
  shouldMergeResults(textBetween, currentResult, nextResult) {
    if (!textBetween.match(/^\s*$/i)) {
      return false;
    }
    return IsPositiveFollowingReference(nextResult) || IsNegativeFollowingReference(nextResult);
  }
  mergeResults(textBetween, currentResult, nextResult, context) {
    let timeUnits = parseTimeUnits(nextResult.text);
    if (IsNegativeFollowingReference(nextResult)) {
      timeUnits = reverseTimeUnits(timeUnits);
    }
    const components2 = ParsingComponents.createRelativeFromReference(new ReferenceWithTimezone(currentResult.start.date()), timeUnits);
    return new ParsingResult(currentResult.reference, currentResult.index, `${currentResult.text}${textBetween}${nextResult.text}`, components2);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/refiners/ENMergeRelativeFollowByDateRefiner.js
function hasImpliedEarlierReferenceDate(result) {
  return result.text.match(/\s+(before|from)$/i) != null;
}
function hasImpliedLaterReferenceDate(result) {
  return result.text.match(/\s+(after|since)$/i) != null;
}
var ENMergeRelativeFollowByDateRefiner = class extends MergingRefiner {
  patternBetween() {
    return /^\s*$/i;
  }
  shouldMergeResults(textBetween, currentResult, nextResult) {
    if (!textBetween.match(this.patternBetween())) {
      return false;
    }
    if (!hasImpliedEarlierReferenceDate(currentResult) && !hasImpliedLaterReferenceDate(currentResult)) {
      return false;
    }
    return !!nextResult.start.get("day") && !!nextResult.start.get("month") && !!nextResult.start.get("year");
  }
  mergeResults(textBetween, currentResult, nextResult) {
    let timeUnits = parseTimeUnits(currentResult.text);
    if (hasImpliedEarlierReferenceDate(currentResult)) {
      timeUnits = reverseTimeUnits(timeUnits);
    }
    const components2 = ParsingComponents.createRelativeFromReference(new ReferenceWithTimezone(nextResult.start.date()), timeUnits);
    return new ParsingResult(nextResult.reference, currentResult.index, `${currentResult.text}${textBetween}${nextResult.text}`, components2);
  }
};

// node_modules/chrono-node/dist/esm/locales/en/refiners/ENExtractYearSuffixRefiner.js
var YEAR_SUFFIX_PATTERN = new RegExp(`^\\s*(${YEAR_PATTERN})`, "i");
var YEAR_GROUP6 = 1;
var ENExtractYearSuffixRefiner = class {
  refine(context, results) {
    results.forEach(function(result) {
      if (!result.start.isDateWithUnknownYear()) {
        return;
      }
      const suffix = context.text.substring(result.index + result.text.length);
      const match2 = YEAR_SUFFIX_PATTERN.exec(suffix);
      if (!match2) {
        return;
      }
      context.debug(() => {
        console.log(`Extracting year: '${match2[0]}' into : ${result}`);
      });
      const year = parseYear(match2[YEAR_GROUP6]);
      if (result.end != null) {
        result.end.assign("year", year);
      }
      result.start.assign("year", year);
      result.text += match2[0];
    });
    return results;
  }
};

// node_modules/chrono-node/dist/esm/locales/en/configuration.js
var ENDefaultConfiguration = class {
  createCasualConfiguration(littleEndian = false) {
    const option = this.createConfiguration(false, littleEndian);
    option.parsers.push(new ENCasualDateParser());
    option.parsers.push(new ENCasualTimeParser());
    option.parsers.push(new ENMonthNameParser());
    option.parsers.push(new ENRelativeDateFormatParser());
    option.parsers.push(new ENTimeUnitCasualRelativeFormatParser());
    return option;
  }
  createConfiguration(strictMode = true, littleEndian = false) {
    const options = includeCommonConfiguration({
      parsers: [
        new SlashDateFormatParser(littleEndian),
        new ENTimeUnitWithinFormatParser(strictMode),
        new ENMonthNameLittleEndianParser(),
        new ENMonthNameMiddleEndianParser(littleEndian),
        new ENWeekdayParser(),
        new ENSlashMonthFormatParser(),
        new ENTimeExpressionParser(strictMode),
        new ENTimeUnitAgoFormatParser(strictMode),
        new ENTimeUnitLaterFormatParser(strictMode)
      ],
      refiners: [new ENMergeDateTimeRefiner()]
    }, strictMode);
    options.parsers.unshift(new ENYearMonthDayParser(strictMode));
    options.refiners.unshift(new ENMergeRelativeFollowByDateRefiner());
    options.refiners.unshift(new ENMergeRelativeAfterDateRefiner());
    options.refiners.unshift(new OverlapRemovalRefiner());
    options.refiners.push(new ENMergeDateTimeRefiner());
    options.refiners.push(new ENExtractYearSuffixRefiner());
    options.refiners.push(new ENMergeDateRangeRefiner());
    return options;
  }
};

// node_modules/chrono-node/dist/esm/chrono.js
var Chrono = class {
  constructor(configuration2) {
    this.defaultConfig = new ENDefaultConfiguration();
    configuration2 = configuration2 || this.defaultConfig.createCasualConfiguration();
    this.parsers = [...configuration2.parsers];
    this.refiners = [...configuration2.refiners];
  }
  clone() {
    return new Chrono({
      parsers: [...this.parsers],
      refiners: [...this.refiners]
    });
  }
  parseDate(text, referenceDate, option) {
    const results = this.parse(text, referenceDate, option);
    return results.length > 0 ? results[0].start.date() : null;
  }
  parse(text, referenceDate, option) {
    const context = new ParsingContext(text, referenceDate, option);
    let results = [];
    this.parsers.forEach((parser) => {
      const parsedResults = Chrono.executeParser(context, parser);
      results = results.concat(parsedResults);
    });
    results.sort((a3, b3) => {
      return a3.index - b3.index;
    });
    this.refiners.forEach(function(refiner) {
      results = refiner.refine(context, results);
    });
    return results;
  }
  static executeParser(context, parser) {
    const results = [];
    const pattern = parser.pattern(context);
    const originalText = context.text;
    let remainingText = context.text;
    let match2 = pattern.exec(remainingText);
    while (match2) {
      const index2 = match2.index + originalText.length - remainingText.length;
      match2.index = index2;
      const result = parser.extract(context, match2);
      if (!result) {
        remainingText = originalText.substring(match2.index + 1);
        match2 = pattern.exec(remainingText);
        continue;
      }
      let parsedResult = null;
      if (result instanceof ParsingResult) {
        parsedResult = result;
      } else if (result instanceof ParsingComponents) {
        parsedResult = context.createParsingResult(match2.index, match2[0]);
        parsedResult.start = result;
      } else {
        parsedResult = context.createParsingResult(match2.index, match2[0], result);
      }
      const parsedIndex = parsedResult.index;
      const parsedText = parsedResult.text;
      context.debug(() => console.log(`${parser.constructor.name} extracted (at index=${parsedIndex}) '${parsedText}'`));
      results.push(parsedResult);
      remainingText = originalText.substring(parsedIndex + parsedText.length);
      match2 = pattern.exec(remainingText);
    }
    return results;
  }
};
var ParsingContext = class {
  constructor(text, refDate, option) {
    this.text = text;
    this.reference = new ReferenceWithTimezone(refDate);
    this.option = option ?? {};
    this.refDate = this.reference.instant;
  }
  createParsingComponents(components2) {
    if (components2 instanceof ParsingComponents) {
      return components2;
    }
    return new ParsingComponents(this.reference, components2);
  }
  createParsingResult(index2, textOrEndIndex, startComponents, endComponents) {
    const text = typeof textOrEndIndex === "string" ? textOrEndIndex : this.text.substring(index2, textOrEndIndex);
    const start = startComponents ? this.createParsingComponents(startComponents) : null;
    const end = endComponents ? this.createParsingComponents(endComponents) : null;
    return new ParsingResult(this.reference, index2, text, start, end);
  }
  debug(block) {
    if (this.option.debug) {
      if (this.option.debug instanceof Function) {
        this.option.debug(block);
      } else {
        const handler = this.option.debug;
        handler.debug(block);
      }
    }
  }
};

// node_modules/chrono-node/dist/esm/locales/en/index.js
var configuration = new ENDefaultConfiguration();
var casual = new Chrono(configuration.createCasualConfiguration(false));
var strict = new Chrono(configuration.createConfiguration(true, false));
var GB = new Chrono(configuration.createCasualConfiguration(true));

// node_modules/chrono-node/dist/esm/index.js
var casual2 = casual;
function parse3(text, ref, option) {
  return casual2.parse(text, ref, option);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// src/tools/TimeTools.ts
var import_obsidian13 = require("obsidian");
init_lib();
async function getCurrentTime() {
  const now3 = new Date();
  const timezoneOffset = now3.getTimezoneOffset();
  const timezoneAbbr = new Intl.DateTimeFormat("en", { timeZoneName: "short" }).formatToParts(now3).find((part) => part.type === "timeZoneName")?.value || "Unknown";
  return {
    epoch: Math.floor(now3.getTime()),
    isoString: now3.toISOString(),
    userLocaleString: now3.toLocaleString(),
    localDateString: now3.toLocaleDateString("en-CA", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit"
    }),
    timezoneOffset: -timezoneOffset,
    // Invert the offset to match common conventions
    timezone: timezoneAbbr
  };
}
var getCurrentTimeTool = tool(async () => getCurrentTime(), {
  name: "getCurrentTime",
  description: "Get the current time in various formats, including timezone information",
  schema: z.object({})
  // No input required
});
var monthNames = {
  jan: 1,
  january: 1,
  feb: 2,
  february: 2,
  mar: 3,
  march: 3,
  apr: 4,
  april: 4,
  may: 5,
  jun: 6,
  june: 6,
  jul: 7,
  july: 7,
  aug: 8,
  august: 8,
  sep: 9,
  september: 9,
  oct: 10,
  october: 10,
  nov: 11,
  november: 11,
  dec: 12,
  december: 12
};
function handleRelativeTimeRange(input, now3) {
  const relativeMatch = input.match(
    /^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i
  );
  if (!relativeMatch)
    return void 0;
  const [, , amountStr, unit] = relativeMatch;
  const amount = parseInt(amountStr);
  if (amount <= 0) {
    return void 0;
  }
  const unitSingular = unit.replace(/s$/, "");
  const end = now3.startOf("day");
  const start = end.minus({ [unitSingular + "s"]: amount });
  return { start, end };
}
function handleSpecialTimeRanges(input, now3) {
  switch (input) {
    case "yesterday":
      return {
        start: now3.minus({ days: 1 }).startOf("day"),
        end: now3.minus({ days: 1 }).endOf("day")
      };
    case "last week":
      return {
        start: now3.minus({ weeks: 1 }).startOf("week"),
        end: now3.minus({ weeks: 1 }).endOf("week")
      };
    case "this week":
      return {
        start: now3.startOf("week"),
        end: now3.endOf("week")
      };
    case "next week":
      return {
        start: now3.plus({ weeks: 1 }).startOf("week"),
        end: now3.plus({ weeks: 1 }).endOf("week")
      };
    case "last month":
      return {
        start: now3.minus({ months: 1 }).startOf("month"),
        end: now3.minus({ months: 1 }).endOf("month")
      };
    case "this month":
      return {
        start: now3.startOf("month"),
        end: now3.endOf("month")
      };
    case "next month":
      return {
        start: now3.plus({ months: 1 }).startOf("month"),
        end: now3.plus({ months: 1 }).endOf("month")
      };
    case "last year":
      return {
        start: now3.minus({ years: 1 }).startOf("year"),
        end: now3.minus({ years: 1 }).endOf("year")
      };
    case "this year":
      return {
        start: now3.startOf("year"),
        end: now3.endOf("year")
      };
    case "next year":
      return {
        start: now3.plus({ years: 1 }).startOf("year"),
        end: now3.plus({ years: 1 }).endOf("year")
      };
    case "last quarter":
      return {
        start: now3.minus({ quarters: 1 }).startOf("quarter"),
        end: now3.minus({ quarters: 1 }).endOf("quarter")
      };
    case "this quarter":
      return {
        start: now3.startOf("quarter"),
        end: now3.endOf("quarter")
      };
    case "next quarter":
      return {
        start: now3.plus({ quarters: 1 }).startOf("quarter"),
        end: now3.plus({ quarters: 1 }).endOf("quarter")
      };
  }
  return void 0;
}
function handleWeekOf(input, now3) {
  const weekOfMatch = input.match(/(?:the\s+)?week\s+of\s+(.+)/i);
  if (!weekOfMatch)
    return void 0;
  const dateStr = weekOfMatch[1];
  const parsedDates = parse3(dateStr, now3.toJSDate(), { forwardDate: false });
  if (parsedDates.length === 0)
    return void 0;
  let start = DateTime.fromJSDate(parsedDates[0].start.date()).startOf("week");
  let end = start.endOf("week");
  if (start > now3) {
    start = start.minus({ years: 1 });
    end = end.minus({ years: 1 });
  }
  return { start, end };
}
function handleMonthName(input, now3) {
  const monthMatch = input.match(
    /^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|september|oct|october|nov|november|dec|december)$/i
  );
  if (!monthMatch)
    return void 0;
  const monthNum = monthNames[monthMatch[1]];
  let year = now3.year;
  if (monthNum > now3.month) {
    year--;
  }
  let start = DateTime.fromObject({
    year,
    month: monthNum,
    day: 1
  });
  let end = start.endOf("month");
  if (start > now3) {
    start = start.minus({ years: 1 });
    end = end.minus({ years: 1 });
  }
  return { start, end };
}
function handleYear(input, now3) {
  const yearMatch = input.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);
  if (!yearMatch)
    return void 0;
  const year = parseInt(yearMatch[1]);
  let start = DateTime.fromObject({ year, month: 1, day: 1 });
  let end = DateTime.fromObject({ year, month: 12, day: 31 });
  if (start > now3) {
    start = start.minus({ years: 1 });
    end = end.minus({ years: 1 });
  }
  return { start, end };
}
function handleQuarter(input, now3) {
  const quarterYearMatch = input.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/);
  const quarterOnlyMatch = input.match(/^(?:q|Q)(\d{1})$/);
  let quarter;
  let year;
  if (quarterYearMatch) {
    quarter = parseInt(quarterYearMatch[1] || quarterYearMatch[4]);
    year = parseInt(quarterYearMatch[2] || quarterYearMatch[3]);
  } else if (quarterOnlyMatch) {
    quarter = parseInt(quarterOnlyMatch[1]);
    year = now3.year;
    const currentQuarter = Math.floor((now3.month - 1) / 3) + 1;
    if (quarter > currentQuarter) {
      year--;
    }
  } else {
    return void 0;
  }
  if (quarter < 1 || quarter > 4)
    return void 0;
  const startMonth = (quarter - 1) * 3 + 1;
  let start = DateTime.fromObject({
    year,
    month: startMonth,
    day: 1
  }).startOf("day");
  let end = start.plus({ months: 3 }).minus({ days: 1 }).endOf("day");
  if (start > now3) {
    start = start.minus({ years: 1 });
    end = end.minus({ years: 1 });
  }
  return { start, end };
}
function handleMonthYear(input, now3) {
  const monthYearMatch = input.match(
    /^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i
  );
  if (!monthYearMatch)
    return void 0;
  const monthNum = monthNames[monthYearMatch[1].toLowerCase()];
  const year = parseInt(monthYearMatch[2]);
  let start = DateTime.fromObject({
    year,
    month: monthNum,
    day: 1
  }).startOf("day");
  let end = start.endOf("month");
  if (start > now3) {
    start = start.minus({ years: 1 });
    end = end.minus({ years: 1 });
  }
  return { start, end };
}
function getTimeRangeMs(timeExpression) {
  const now3 = DateTime.now();
  const normalizedInput = timeExpression.toLowerCase().replace("@vault", "").trim();
  const result = handleRelativeTimeRange(normalizedInput, now3) || handleSpecialTimeRanges(normalizedInput, now3) || handleWeekOf(normalizedInput, now3) || handleMonthName(normalizedInput, now3) || handleMonthYear(normalizedInput, now3) || handleQuarter(normalizedInput, now3) || handleYear(normalizedInput, now3);
  if (result) {
    return {
      startTime: convertToTimeInfo(result.start),
      endTime: convertToTimeInfo(result.end)
    };
  }
  const parsedDates = parse3(timeExpression, now3.toJSDate(), { forwardDate: false });
  if (parsedDates.length > 0) {
    const start = DateTime.fromJSDate(parsedDates[0].start.date()).startOf("day");
    const end = parsedDates[0].end ? DateTime.fromJSDate(parsedDates[0].end.date()).endOf("day") : start.endOf("day");
    if (start > now3) {
      start.minus({ years: 1 });
      end.minus({ years: 1 });
    }
    return {
      startTime: convertToTimeInfo(start),
      endTime: convertToTimeInfo(end)
    };
  }
  console.warn(`Unable to parse time expression: ${timeExpression}`);
  return void 0;
}
function convertToTimeInfo(dateTime) {
  const jsDate = dateTime.toJSDate();
  const timezoneOffset = jsDate.getTimezoneOffset();
  const timezoneAbbr = new Intl.DateTimeFormat("en", { timeZoneName: "short" }).formatToParts(jsDate).find((part) => part.type === "timeZoneName")?.value || "Unknown";
  return {
    epoch: Math.floor(jsDate.getTime()),
    isoString: jsDate.toISOString(),
    userLocaleString: jsDate.toLocaleString(),
    localDateString: jsDate.toLocaleDateString("en-CA", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit"
    }),
    timezoneOffset: -timezoneOffset,
    timezone: timezoneAbbr
  };
}
var getTimeRangeMsTool = tool(
  async ({ timeExpression }) => getTimeRangeMs(timeExpression),
  {
    name: "getTimeRangeMs",
    description: "Get a time range in milliseconds based on a natural language time expression",
    schema: z.object({
      timeExpression: z.string().describe(
        "A natural language time expression (e.g., 'last week', 'from July 1 to July 15')"
      )
    })
  }
);
function getTimeInfoByEpoch(epoch) {
  const epochMs = epoch.toString().length === 10 ? epoch * 1e3 : epoch;
  const dateTime = DateTime.fromMillis(epochMs);
  return convertToTimeInfo(dateTime);
}
var getTimeInfoByEpochTool = tool(
  async ({ epoch }) => getTimeInfoByEpoch(epoch),
  {
    name: "getTimeInfoByEpoch",
    description: "Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",
    schema: z.object({
      epoch: z.number().describe("Unix timestamp in seconds or milliseconds")
    })
  }
);
function parseTimeInterval(interval) {
  const match2 = interval.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?)$/i);
  if (!match2) {
    throw new Error(`Invalid time interval format: ${interval}`);
  }
  const value = parseInt(match2[1], 10);
  const unit = match2[2].toLowerCase();
  switch (unit) {
    case "s":
    case "sec":
    case "second":
    case "seconds":
      return value * 1e3;
    case "m":
    case "min":
    case "minute":
    case "minutes":
      return value * 60 * 1e3;
    case "h":
    case "hr":
    case "hour":
    case "hours":
      return value * 60 * 60 * 1e3;
    default:
      throw new Error(`Unsupported time unit: ${unit}`);
  }
}
async function startPomodoro(interval = "25min") {
  const duration = parseTimeInterval(interval);
  return new Promise((resolve) => {
    setTimeout(() => {
      new import_obsidian13.Notice(`Pomodoro timer (${interval}) completed! Take a break!`);
      resolve();
    }, duration);
  });
}
var pomodoroTool = tool(
  async ({ interval = "25min" }) => {
    startPomodoro(interval);
    return `Pomodoro timer started. It will end in ${interval}.`;
  },
  {
    name: "startPomodoro",
    description: "Start a Pomodoro timer with a customizable interval",
    schema: z.object({
      interval: z.string().optional().describe("Time interval (e.g., '25min', '5s', '1h'). Default is 25min.")
    })
  }
);

// src/tools/YoutubeTools.ts
init_lib();
var simpleYoutubeTranscriptionTool = tool(
  async ({ url }) => {
    try {
      const response = await BrevilabsClient.getInstance().youtube4llm(url);
      if (!response.response.transcript) {
        return JSON.stringify({
          success: false,
          message: "Transcript not available. Only English videos with the auto transcript option turned on are supported at the moment"
        });
      }
      return JSON.stringify({
        success: true,
        transcript: response.response.transcript,
        elapsed_time_ms: response.elapsed_time_ms
      });
    } catch (error) {
      console.error(`Error transcribing YouTube video ${url}:`, error);
      return JSON.stringify({
        success: false,
        message: "An error occurred while transcribing the YouTube video."
      });
    }
  },
  {
    name: "youtubeTranscription",
    description: "Get the transcript of a YouTube video",
    schema: z.object({
      url: z.string().describe("The YouTube video URL"),
      brevilabsClient: z.any().describe("The BrevilabsClient instance")
    })
  }
);

// node_modules/@langchain/core/dist/memory.js
var BaseMemory = class {
};
var getValue = (values, key) => {
  if (key !== void 0) {
    return values[key];
  }
  const keys = Object.keys(values);
  if (keys.length === 1) {
    return values[keys[0]];
  }
};
var getInputValue = (inputValues, inputKey) => {
  const value = getValue(inputValues, inputKey);
  if (!value) {
    const keys = Object.keys(inputValues);
    throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`);
  }
  return value;
};
var getOutputValue = (outputValues, outputKey) => {
  const value = getValue(outputValues, outputKey);
  if (!value && value !== "") {
    const keys = Object.keys(outputValues);
    throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`);
  }
  return value;
};

// node_modules/@langchain/core/dist/chat_history.js
init_serializable();
init_messages2();
var BaseListChatMessageHistory = class extends Serializable {
  /**
   * This is a convenience method for adding a human message string to the store.
   * Please note that this is a convenience method. Code should favor the
   * bulk addMessages interface instead to save on round-trips to the underlying
   * persistence layer.
   * This method may be deprecated in a future release.
   */
  addUserMessage(message) {
    return this.addMessage(new HumanMessage(message));
  }
  /** @deprecated Use addAIMessage instead */
  addAIChatMessage(message) {
    return this.addMessage(new AIMessage(message));
  }
  /**
   * This is a convenience method for adding an AI message string to the store.
   * Please note that this is a convenience method. Code should favor the bulk
   * addMessages interface instead to save on round-trips to the underlying
   * persistence layer.
   * This method may be deprecated in a future release.
   */
  addAIMessage(message) {
    return this.addMessage(new AIMessage(message));
  }
  /**
   * Add a list of messages.
   *
   * Implementations should override this method to handle bulk addition of messages
   * in an efficient manner to avoid unnecessary round-trips to the underlying store.
   *
   * @param messages - A list of BaseMessage objects to store.
   */
  async addMessages(messages) {
    for (const message of messages) {
      await this.addMessage(message);
    }
  }
  /**
   * Remove all messages from the store.
   */
  clear() {
    throw new Error("Not implemented.");
  }
};
var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory {
  constructor(messages) {
    super(...arguments);
    Object.defineProperty(this, "lc_namespace", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: ["langchain", "stores", "message", "in_memory"]
    });
    Object.defineProperty(this, "messages", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: []
    });
    this.messages = messages ?? [];
  }
  /**
   * Method to get all the messages stored in the ChatMessageHistory
   * instance.
   * @returns Array of stored BaseMessage instances.
   */
  async getMessages() {
    return this.messages;
  }
  /**
   * Method to add a new message to the ChatMessageHistory instance.
   * @param message The BaseMessage instance to add.
   * @returns A promise that resolves when the message has been added.
   */
  async addMessage(message) {
    this.messages.push(message);
  }
  /**
   * Method to clear all the messages from the ChatMessageHistory instance.
   * @returns A promise that resolves when all messages have been cleared.
   */
  async clear() {
    this.messages = [];
  }
};

// node_modules/langchain/dist/memory/chat_memory.js
var BaseChatMemory = class extends BaseMemory {
  constructor(fields) {
    super();
    Object.defineProperty(this, "chatHistory", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "returnMessages", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: false
    });
    Object.defineProperty(this, "inputKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, "outputKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: void 0
    });
    this.chatHistory = fields?.chatHistory ?? new InMemoryChatMessageHistory();
    this.returnMessages = fields?.returnMessages ?? this.returnMessages;
    this.inputKey = fields?.inputKey ?? this.inputKey;
    this.outputKey = fields?.outputKey ?? this.outputKey;
  }
  /**
   * Method to add user and AI messages to the chat history in sequence.
   * @param inputValues The input values from the user.
   * @param outputValues The output values from the AI.
   * @returns Promise that resolves when the context has been saved.
   */
  async saveContext(inputValues, outputValues) {
    await this.chatHistory.addUserMessage(getInputValue(inputValues, this.inputKey));
    await this.chatHistory.addAIChatMessage(getOutputValue(outputValues, this.outputKey));
  }
  /**
   * Method to clear the chat history.
   * @returns Promise that resolves when the chat history has been cleared.
   */
  async clear() {
    await this.chatHistory.clear();
  }
};

// node_modules/langchain/dist/memory/summary.js
init_llm_chain();

// node_modules/langchain/dist/memory/prompt.js
init_prompts3();

// node_modules/langchain/dist/memory/buffer_window_memory.js
var BufferWindowMemory = class extends BaseChatMemory {
  constructor(fields) {
    super({
      returnMessages: fields?.returnMessages ?? false,
      chatHistory: fields?.chatHistory,
      inputKey: fields?.inputKey,
      outputKey: fields?.outputKey
    });
    Object.defineProperty(this, "humanPrefix", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "Human"
    });
    Object.defineProperty(this, "aiPrefix", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "AI"
    });
    Object.defineProperty(this, "memoryKey", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: "history"
    });
    Object.defineProperty(this, "k", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5
    });
    this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix;
    this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix;
    this.memoryKey = fields?.memoryKey ?? this.memoryKey;
    this.k = fields?.k ?? this.k;
  }
  get memoryKeys() {
    return [this.memoryKey];
  }
  /**
   * Method to load the memory variables. Retrieves the chat messages from
   * the history, slices the last 'k' messages, and stores them in the
   * memory under the memoryKey. If the returnMessages property is set to
   * true, the method returns the messages as they are. Otherwise, it
   * returns a string representation of the messages.
   * @param _values InputValues object.
   * @returns Promise that resolves to a MemoryVariables object.
   */
  async loadMemoryVariables(_values) {
    const messages = await this.chatHistory.getMessages();
    if (this.returnMessages) {
      const result2 = {
        [this.memoryKey]: messages.slice(-this.k * 2)
      };
      return result2;
    }
    const result = {
      [this.memoryKey]: getBufferString(messages.slice(-this.k * 2), this.humanPrefix, this.aiPrefix)
    };
    return result;
  }
};

// node_modules/@langchain/core/load/serializable.js
init_serializable();

// node_modules/langchain/dist/memory/entity_memory.js
init_llm_chain();

// src/LLMProviders/memoryManager.ts
var MemoryManager = class {
  constructor() {
    this.initMemory();
    subscribeToSettingsChange(() => this.initMemory());
  }
  static getInstance() {
    if (!MemoryManager.instance) {
      MemoryManager.instance = new MemoryManager();
    }
    return MemoryManager.instance;
  }
  initMemory() {
    const chatContextTurns = getSettings().contextTurns;
    this.memory = new BufferWindowMemory({
      k: chatContextTurns * 2,
      memoryKey: "history",
      inputKey: "input",
      returnMessages: true
    });
    if (this.debug) {
      console.log("Memory initialized with context turns:", chatContextTurns);
    }
  }
  getMemory() {
    return this.memory;
  }
  async clearChatMemory() {
    if (this.debug)
      console.log("Clearing chat memory");
    await this.memory.clear();
  }
  async loadMemoryVariables() {
    const variables = await this.memory.loadMemoryVariables({});
    if (this.debug)
      console.log("Loaded memory variables:", variables);
    return variables;
  }
  async saveContext(input, output) {
    if (this.debug)
      console.log("Saving to memory - Input:", input, "Output:", output);
    await this.memory.saveContext(input, output);
  }
};

// src/LLMProviders/intentAnalyzer.ts
var COPILOT_TOOL_NAMES = ["@vault", "@web", "@youtube", "@pomodoro"];
var IntentAnalyzer = class {
  static async analyzeIntent(originalMessage) {
    try {
      const brocaResponse = await BrevilabsClient.getInstance().broca(originalMessage);
      if (!brocaResponse?.response) {
        throw new Error(brocaResponse?.detail || "Broca API call failed");
      }
      const brocaToolCalls = brocaResponse.response.tool_calls;
      const salientTerms = brocaResponse.response.salience_terms;
      const processedToolCalls = [];
      let timeRange;
      for (const brocaToolCall of brocaToolCalls) {
        const tool2 = this.tools.find((t3) => t3.name === brocaToolCall.tool);
        if (tool2) {
          const args = brocaToolCall.args || {};
          if (tool2.name === "getTimeRangeMs") {
            timeRange = await ToolManager.callTool(tool2, args);
          }
          processedToolCalls.push({ tool: tool2, args });
        }
      }
      await this.processAtCommands(originalMessage, processedToolCalls, {
        timeRange,
        salientTerms
      });
      return processedToolCalls;
    } catch (error) {
      console.error("Error in intent analysis:", error);
      throw error;
    }
  }
  static async processAtCommands(originalMessage, processedToolCalls, context) {
    const message = originalMessage.toLowerCase();
    const { timeRange, salientTerms } = context;
    if (message.includes("@vault") && (salientTerms.length > 0 || timeRange)) {
      const cleanQuery = this.removeAtCommands(originalMessage);
      processedToolCalls.push({
        tool: localSearchTool,
        args: {
          timeRange: timeRange || void 0,
          query: cleanQuery,
          salientTerms
        }
      });
    }
    if (message.includes("@web")) {
      const cleanQuery = this.removeAtCommands(originalMessage);
      const memory = MemoryManager.getInstance().getMemory();
      const memoryVariables = await memory.loadMemoryVariables({});
      const chatHistory = extractChatHistory(memoryVariables);
      processedToolCalls.push({
        tool: webSearchTool,
        args: {
          query: cleanQuery,
          chatHistory
        }
      });
    }
    if (message.includes("@pomodoro")) {
      const pomodoroMatch = originalMessage.match(/@pomodoro\s+(\S+)/i);
      const interval = pomodoroMatch ? pomodoroMatch[1] : "25min";
      processedToolCalls.push({
        tool: pomodoroTool,
        args: { interval }
      });
    }
    if (message.includes("@youtube")) {
      const youtubeUrl = extractYoutubeUrl(originalMessage);
      if (youtubeUrl) {
        processedToolCalls.push({
          tool: simpleYoutubeTranscriptionTool,
          args: {
            url: youtubeUrl
          }
        });
      }
    }
  }
  static removeAtCommands(message) {
    return message.split(" ").filter((word) => !COPILOT_TOOL_NAMES.includes(word.toLowerCase())).join(" ").trim();
  }
};
IntentAnalyzer.tools = [
  getCurrentTimeTool,
  getTimeInfoByEpochTool,
  getTimeRangeMsTool,
  localSearchTool,
  indexTool,
  pomodoroTool,
  webSearchTool,
  simpleYoutubeTranscriptionTool
];

// src/LLMProviders/chainRunner.ts
var BaseChainRunner = class {
  constructor(chainManager) {
    this.chainManager = chainManager;
  }
  async handleResponse(fullAIResponse, userMessage, abortController, addMessage, updateCurrentAiMessage, debug4, sources) {
    if (fullAIResponse && abortController.signal.reason !== "new-chat" /* NEW_CHAT */) {
      await this.chainManager.memoryManager.getMemory().saveContext({ input: userMessage.message }, { output: fullAIResponse });
      addMessage({
        message: fullAIResponse,
        sender: AI_SENDER,
        isVisible: true,
        timestamp: formatDateTime(new Date()),
        sources
      });
    }
    updateCurrentAiMessage("");
    if (debug4) {
      console.log(
        "==== Chat Memory ====\n",
        this.chainManager.memoryManager.getMemory().chatHistory.messages.map(
          (m3) => m3.content
        )
      );
      console.log("==== Final AI Response ====\n", fullAIResponse);
    }
    return fullAIResponse;
  }
  async handleError(error, debug4, addMessage, updateCurrentAiMessage) {
    if (debug4)
      console.error("Error during LLM invocation:", error);
    const errorData = error?.response?.data?.error || error;
    const errorCode = errorData?.code || error;
    let errorMessage = "";
    if (error?.message?.includes("Invalid license key")) {
      errorMessage = "Invalid Copilot Plus license key. Please check your license key in settings.";
    } else if (errorCode === "model_not_found") {
      errorMessage = "You do not have access to this model or the model does not exist, please check with your API provider.";
    } else {
      errorMessage = `${errorCode}`;
    }
    console.error(errorData);
    if (addMessage && updateCurrentAiMessage) {
      updateCurrentAiMessage("");
      addMessage({
        message: errorMessage,
        sender: AI_SENDER,
        isVisible: true,
        timestamp: formatDateTime(new Date())
      });
    } else {
      new import_obsidian14.Notice(errorMessage);
      console.error(errorData);
    }
  }
};
var LLMChainRunner = class extends BaseChainRunner {
  async run(userMessage, abortController, updateCurrentAiMessage, addMessage, options) {
    const { debug: debug4 = false } = options;
    let fullAIResponse = "";
    try {
      const chain = ChainManager.getChain();
      const chatStream = await chain.stream({
        input: userMessage.message
      });
      for await (const chunk of chatStream) {
        if (abortController.signal.aborted)
          break;
        fullAIResponse += chunk.content;
        updateCurrentAiMessage(fullAIResponse);
      }
    } catch (error) {
      await this.handleError(error, debug4, addMessage, updateCurrentAiMessage);
    }
    return this.handleResponse(
      fullAIResponse,
      userMessage,
      abortController,
      addMessage,
      updateCurrentAiMessage,
      debug4
    );
  }
};
var VaultQAChainRunner = class extends BaseChainRunner {
  async run(userMessage, abortController, updateCurrentAiMessage, addMessage, options) {
    const { debug: debug4 = false } = options;
    let fullAIResponse = "";
    try {
      const indexEmpty = await this.chainManager.vectorStoreManager.isIndexEmpty();
      if (indexEmpty) {
        return this.handleResponse(
          EMPTY_INDEX_ERROR_MESSAGE,
          userMessage,
          abortController,
          addMessage,
          updateCurrentAiMessage,
          debug4
        );
      }
      const memory = this.chainManager.memoryManager.getMemory();
      const memoryVariables = await memory.loadMemoryVariables({});
      const chatHistory = extractChatHistory(memoryVariables);
      const qaStream = await ChainManager.getRetrievalChain().stream({
        question: userMessage.message,
        chat_history: chatHistory
      });
      for await (const chunk of qaStream) {
        if (abortController.signal.aborted)
          break;
        fullAIResponse += chunk.content;
        updateCurrentAiMessage(fullAIResponse);
      }
      fullAIResponse = this.addSourcestoResponse(fullAIResponse);
    } catch (error) {
      await this.handleError(error, debug4, addMessage, updateCurrentAiMessage);
    }
    return this.handleResponse(
      fullAIResponse,
      userMessage,
      abortController,
      addMessage,
      updateCurrentAiMessage,
      debug4
    );
  }
  addSourcestoResponse(response) {
    const docTitles = extractUniqueTitlesFromDocs(ChainManager.retrievedDocuments);
    if (docTitles.length > 0) {
      const markdownLinks = docTitles.map(
        (title) => `- [${title}](obsidian://open?vault=${encodeURIComponent(this.chainManager.app.vault.getName())}&file=${encodeURIComponent(
          title
        )})`
      ).join("\n");
      response += "\n\n#### Sources:\n" + markdownLinks;
    }
    return response;
  }
};
var CopilotPlusChainRunner = class extends BaseChainRunner {
  isYoutubeOnlyMessage(message) {
    const trimmedMessage = message.trim();
    const hasYoutubeCommand = trimmedMessage.includes("@youtube");
    const youtubeUrl = extractYoutubeUrl(trimmedMessage);
    const words = trimmedMessage.split(/\s+/).filter((word) => word !== "@youtube" && word.length > 0);
    return hasYoutubeCommand && youtubeUrl !== null && words.length === 1;
  }
  async processImageUrls(urls) {
    try {
      const imageUrls = await Promise.all(
        urls.map(async (url) => {
          if (await ImageProcessor.isImageUrl(url)) {
            return await ImageProcessor.convertToBase64(url, this.chainManager.app.vault);
          }
          return null;
        })
      );
      return imageUrls.filter((item) => item !== null);
    } catch (error) {
      console.error("Error processing image URLs:", error);
      return [];
    }
  }
  async processExistingImages(content) {
    try {
      const imageContent = await Promise.all(
        content.filter(
          (item) => item.type === "image_url" && !!item.image_url?.url
        ).map(async (item) => {
          return await ImageProcessor.convertToBase64(
            item.image_url.url,
            this.chainManager.app.vault
          );
        })
      );
      return imageContent;
    } catch (error) {
      console.error("Error processing images:", error);
      throw error;
    }
  }
  async buildMessageContent(textContent, userMessage) {
    const content = [
      {
        type: "text",
        text: textContent
      }
    ];
    if (userMessage.context?.urls && userMessage.context.urls.length > 0) {
      const imageContents = await this.processImageUrls(userMessage.context.urls);
      content.push(...imageContents);
    }
    if (userMessage.content && userMessage.content.length > 0) {
      const imageContents = await this.processExistingImages(userMessage.content);
      content.push(...imageContents);
    }
    return content;
  }
  async streamMultimodalResponse(textContent, userMessage, abortController, updateCurrentAiMessage, debug4) {
    const memory = this.chainManager.memoryManager.getMemory();
    const memoryVariables = await memory.loadMemoryVariables({});
    const chatHistory = extractChatHistory(memoryVariables);
    const messages = [];
    let fullSystemMessage = getSystemPrompt();
    if (chatHistory.length > 0) {
      fullSystemMessage += "\n\nThe following is the relevant conversation history. Use this context to maintain consistency in your responses:";
    }
    if (fullSystemMessage) {
      messages.push({
        role: "system",
        content: `${fullSystemMessage}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`
      });
    }
    for (const [human, ai] of chatHistory) {
      messages.push({ role: "user", content: human });
      messages.push({ role: "assistant", content: ai });
    }
    const content = await this.buildMessageContent(textContent, userMessage);
    messages.push({
      role: "user",
      content
    });
    if (debug4) {
      console.log("==== Final Request to AI ====\n", messages);
    }
    let fullAIResponse = "";
    const chatStream = await this.chainManager.chatModelManager.getChatModel().stream(messages);
    for await (const chunk of chatStream) {
      if (abortController.signal.aborted)
        break;
      fullAIResponse += chunk.content;
      updateCurrentAiMessage(fullAIResponse);
    }
    return fullAIResponse;
  }
  async run(userMessage, abortController, updateCurrentAiMessage, addMessage, options) {
    const { debug: debug4 = false, updateLoadingMessage } = options;
    let fullAIResponse = "";
    let sources = [];
    try {
      if (this.isYoutubeOnlyMessage(userMessage.message)) {
        const url = extractYoutubeUrl(userMessage.message);
        const failMessage = "Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";
        if (url) {
          try {
            const response = await BrevilabsClient.getInstance().youtube4llm(url);
            if (response.response.transcript) {
              return this.handleResponse(
                response.response.transcript,
                userMessage,
                abortController,
                addMessage,
                updateCurrentAiMessage,
                debug4
              );
            }
            return this.handleResponse(
              failMessage,
              userMessage,
              abortController,
              addMessage,
              updateCurrentAiMessage,
              debug4
            );
          } catch (error) {
            console.error("Error processing YouTube video:", error);
            return this.handleResponse(
              failMessage,
              userMessage,
              abortController,
              addMessage,
              updateCurrentAiMessage,
              debug4
            );
          }
        }
      }
      if (debug4)
        console.log("==== Step 1: Analyzing intent ====");
      let toolCalls;
      try {
        const messageForAnalysis = userMessage.originalMessage || userMessage.message;
        toolCalls = await IntentAnalyzer.analyzeIntent(messageForAnalysis);
      } catch (error) {
        return this.handleResponse(
          getApiErrorMessage(error),
          userMessage,
          abortController,
          addMessage,
          updateCurrentAiMessage,
          debug4
        );
      }
      const cleanedUserMessage = userMessage.message.split(" ").filter((word) => !COPILOT_TOOL_NAMES.includes(word.toLowerCase())).join(" ").trim();
      const toolOutputs = await this.executeToolCalls(toolCalls, debug4, updateLoadingMessage);
      const localSearchResult = toolOutputs.find(
        (output) => output.tool === "localSearch" && output.output && output.output.length > 0
      );
      if (localSearchResult) {
        if (debug4)
          console.log("==== Step 2: Processing local search results ====");
        const documents = JSON.parse(localSearchResult.output);
        const memory = this.chainManager.memoryManager.getMemory();
        const memoryVariables = await memory.loadMemoryVariables({});
        const chatHistory = extractChatHistory(memoryVariables);
        if (debug4)
          console.log("==== Step 3: Condensing Question ====");
        const standaloneQuestion = await getStandaloneQuestion(cleanedUserMessage, chatHistory);
        if (debug4)
          console.log("Condensed standalone question: ", standaloneQuestion);
        if (debug4)
          console.log("==== Step 4: Preparing context ====");
        const timeExpression = this.getTimeExpression(toolCalls);
        const context = this.prepareLocalSearchResult(documents, timeExpression);
        const currentTimeOutputs = toolOutputs.filter((output) => output.tool === "getCurrentTime");
        const enhancedQuestion = this.prepareEnhancedUserMessage(
          standaloneQuestion,
          currentTimeOutputs
        );
        if (debug4)
          console.log(context);
        if (debug4)
          console.log("==== Step 5: Invoking QA Chain ====");
        const qaPrompt = await this.chainManager.promptManager.getQAPrompt({
          question: enhancedQuestion,
          context,
          systemMessage: ""
          // System prompt is added separately in streamMultimodalResponse
        });
        fullAIResponse = await this.streamMultimodalResponse(
          qaPrompt,
          userMessage,
          abortController,
          updateCurrentAiMessage,
          debug4
        );
        sources = this.getSources(documents);
      } else {
        const enhancedUserMessage = this.prepareEnhancedUserMessage(
          cleanedUserMessage,
          toolOutputs
        );
        if (debug4) {
          console.log("No local search results. Using standard LLM Chain.");
          console.log("Enhanced user message:", enhancedUserMessage);
        }
        fullAIResponse = await this.streamMultimodalResponse(
          enhancedUserMessage,
          userMessage,
          abortController,
          updateCurrentAiMessage,
          debug4
        );
      }
    } catch (error) {
      updateLoadingMessage?.(LOADING_MESSAGES.DEFAULT);
      await this.handleError(error, debug4, addMessage, updateCurrentAiMessage);
    }
    return this.handleResponse(
      fullAIResponse,
      userMessage,
      abortController,
      addMessage,
      updateCurrentAiMessage,
      debug4,
      sources
    );
  }
  getSources(documents) {
    if (!documents || !Array.isArray(documents)) {
      console.warn("No valid documents provided to getSources");
      return [];
    }
    return this.sortUniqueDocsByScore(documents);
  }
  sortUniqueDocsByScore(documents) {
    const uniqueDocs = /* @__PURE__ */ new Map();
    for (const doc of documents) {
      if (!doc.title || !doc?.score && !doc?.rerank_score) {
        console.warn("Invalid document structure:", doc);
        continue;
      }
      const currentDoc = uniqueDocs.get(doc.title);
      const isReranked = doc && "rerank_score" in doc;
      const docScore = isReranked ? doc.rerank_score : doc.score;
      if (!currentDoc || docScore > (currentDoc.score ?? 0)) {
        uniqueDocs.set(doc.title, {
          title: doc.title,
          score: docScore,
          isReranked
        });
      }
    }
    return Array.from(uniqueDocs.values()).sort((a3, b3) => (b3.score ?? 0) - (a3.score ?? 0));
  }
  async executeToolCalls(toolCalls, debug4, updateLoadingMessage) {
    const toolOutputs = [];
    for (const toolCall of toolCalls) {
      if (debug4) {
        console.log(`==== Step 2: Calling tool: ${toolCall.tool.name} ====`);
      }
      if (toolCall.tool.name === "localSearch") {
        updateLoadingMessage?.(LOADING_MESSAGES.READING_FILES);
      } else if (toolCall.tool.name === "webSearch") {
        updateLoadingMessage?.(LOADING_MESSAGES.SEARCHING_WEB);
      }
      const output = await ToolManager.callTool(toolCall.tool, toolCall.args);
      toolOutputs.push({ tool: toolCall.tool.name, output });
    }
    return toolOutputs;
  }
  prepareEnhancedUserMessage(userMessage, toolOutputs) {
    let context = "";
    if (toolOutputs.length > 0) {
      const validOutputs = toolOutputs.filter((output) => output.output != null);
      if (validOutputs.length > 0) {
        context = "\n\n# Additional context:\n\n" + validOutputs.map((output) => `# ${output.tool}
${JSON.stringify(output.output)}`).join("\n\n");
      }
    }
    return `User message: ${userMessage}${context}`;
  }
  getTimeExpression(toolCalls) {
    const timeRangeCall = toolCalls.find((call) => call.tool.name === "getTimeRangeMs");
    return timeRangeCall ? timeRangeCall.args.timeExpression : "";
  }
  prepareLocalSearchResult(documents, timeExpression) {
    const includedDocs = documents.filter((doc) => doc.includeInContext);
    const totalLength = includedDocs.reduce((sum, doc) => sum + doc.content.length, 0);
    let truncatedDocs = includedDocs;
    if (totalLength > MAX_CHARS_FOR_LOCAL_SEARCH_CONTEXT) {
      const truncationRatio = MAX_CHARS_FOR_LOCAL_SEARCH_CONTEXT / totalLength;
      console.log("Truncating documents to fit context length. Truncation ratio:", truncationRatio);
      truncatedDocs = includedDocs.map((doc) => ({
        ...doc,
        content: doc.content.slice(0, Math.floor(doc.content.length * truncationRatio))
      }));
    }
    const formattedDocs = truncatedDocs.map((doc) => `Note in Vault: ${doc.content}`).join("\n\n");
    return timeExpression ? `Local Search Result for ${timeExpression}:
${formattedDocs}` : `Local Search Result:
${formattedDocs}`;
  }
};

// src/LLMProviders/chainManager.ts
init_prompts3();
var import_obsidian15 = require("obsidian");

// src/LLMProviders/promptManager.ts
init_prompts3();
var PromptManager = class {
  constructor() {
    this.initChatPrompt();
    this.initQAPrompt();
    subscribeToSettingsChange(() => {
      this.initChatPrompt();
      this.initQAPrompt();
    });
  }
  static getInstance() {
    if (!PromptManager.instance) {
      PromptManager.instance = new PromptManager();
    }
    return PromptManager.instance;
  }
  initChatPrompt() {
    const escapedSystemMessage = this.escapeTemplateString(getSystemPrompt());
    this.chatPrompt = ChatPromptTemplate.fromMessages([
      SystemMessagePromptTemplate.fromTemplate(escapedSystemMessage),
      new MessagesPlaceholder("history"),
      HumanMessagePromptTemplate.fromTemplate("{input}")
    ]);
  }
  initQAPrompt() {
    const qaTemplate = `{system_message}

Answer the question with as detailed as possible based only on the following context:
{context}

Question: {question}
`;
    this.qaPrompt = ChatPromptTemplate.fromMessages([
      SystemMessagePromptTemplate.fromTemplate(qaTemplate)
    ]);
  }
  // Add this new method to escape curly braces
  escapeTemplateString(str2) {
    return str2.replace(/\{/g, "{{").replace(/\}/g, "}}");
  }
  getChatPrompt() {
    return this.chatPrompt;
  }
  async getQAPrompt({
    question,
    context,
    systemMessage
  }) {
    const promptResult = await this.qaPrompt.format({
      question,
      context,
      system_message: systemMessage
    });
    return promptResult;
  }
};

// src/LLMProviders/chainManager.ts
var _ChainManager = class {
  constructor(app2, vectorStoreManager) {
    this.app = app2;
    this.vectorStoreManager = vectorStoreManager;
    this.memoryManager = MemoryManager.getInstance();
    this.chatModelManager = ChatModelManager.getInstance();
    this.promptManager = PromptManager.getInstance();
    this.initialize();
    subscribeToModelKeyChange(async () => await this.createChainWithNewModel());
    subscribeToChainTypeChange(
      () => this.setChain(getChainType(), {
        refreshIndex: getSettings().indexVaultToVectorStore === "ON MODE SWITCH" /* ON_MODE_SWITCH */ && (getChainType() === "vault_qa" /* VAULT_QA_CHAIN */ || getChainType() === "copilot_plus" /* COPILOT_PLUS_CHAIN */)
      })
    );
    subscribeToSettingsChange(async () => await this.createChainWithNewModel());
  }
  async initialize() {
    await this.createChainWithNewModel();
  }
  static getChain() {
    return _ChainManager.chain;
  }
  static getRetrievalChain() {
    return _ChainManager.retrievalChain;
  }
  validateChainType(chainType) {
    if (chainType === void 0 || chainType === null)
      throw new Error("No chain type set");
  }
  validateChatModel() {
    if (!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())) {
      const errorMsg = "Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";
      new import_obsidian15.Notice(errorMsg);
      throw new Error(errorMsg);
    }
  }
  validateChainInitialization() {
    if (!_ChainManager.chain || !isSupportedChain(_ChainManager.chain)) {
      console.error("Chain is not initialized properly, re-initializing chain: ", getChainType());
      this.setChain(getChainType());
    }
  }
  static storeRetrieverDocuments(documents) {
    _ChainManager.retrievedDocuments = documents;
  }
  /**
   * Update the active model and create a new chain with the specified model
   * name.
   */
  async createChainWithNewModel() {
    let newModelKey = getModelKey();
    try {
      let customModel = findCustomModel(newModelKey, getSettings().activeModels);
      if (!customModel) {
        console.error("Resetting default model. No model configuration found for: ", newModelKey);
        customModel = BUILTIN_CHAT_MODELS[0];
        newModelKey = customModel.name + "|" + customModel.provider;
      }
      await this.chatModelManager.setChatModel(customModel);
      this.setChain(getChainType());
      logInfo(`Setting model to ${newModelKey}`);
    } catch (error) {
      logError(`createChainWithNewModel failed: ${error}`);
      logInfo(`modelKey: ${newModelKey}`);
    }
  }
  async setChain(chainType, options = {}) {
    if (!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())) {
      console.error("setChain failed: No chat model set.");
      return;
    }
    this.validateChainType(chainType);
    const chatModel = this.chatModelManager.getChatModel();
    const memory = this.memoryManager.getMemory();
    const chatPrompt = this.promptManager.getChatPrompt();
    switch (chainType) {
      case "llm_chain" /* LLM_CHAIN */: {
        _ChainManager.chain = chainFactory_default.createNewLLMChain({
          llm: chatModel,
          memory,
          prompt: options.prompt || chatPrompt,
          abortController: options.abortController
        });
        setChainType("llm_chain" /* LLM_CHAIN */);
        break;
      }
      case "vault_qa" /* VAULT_QA_CHAIN */: {
        await this.initializeQAChain(options);
        const retriever = new HybridRetriever({
          minSimilarityScore: 0.01,
          maxK: getSettings().maxSourceChunks,
          salientTerms: []
        });
        _ChainManager.retrievalChain = chainFactory_default.createConversationalRetrievalChain(
          {
            llm: chatModel,
            retriever,
            systemMessage: getSystemPrompt()
          },
          _ChainManager.storeRetrieverDocuments.bind(_ChainManager),
          getSettings().debug
        );
        setChainType("vault_qa" /* VAULT_QA_CHAIN */);
        if (getSettings().debug) {
          console.log("New Vault QA chain with hybrid retriever created for entire vault");
          console.log("Set chain:", "vault_qa" /* VAULT_QA_CHAIN */);
        }
        break;
      }
      case "copilot_plus" /* COPILOT_PLUS_CHAIN */: {
        await this.initializeQAChain(options);
        _ChainManager.chain = chainFactory_default.createNewLLMChain({
          llm: chatModel,
          memory,
          prompt: options.prompt || chatPrompt,
          abortController: options.abortController
        });
        setChainType("copilot_plus" /* COPILOT_PLUS_CHAIN */);
        break;
      }
      default:
        this.validateChainType(chainType);
        break;
    }
  }
  getChainRunner() {
    const chainType = getChainType();
    switch (chainType) {
      case "llm_chain" /* LLM_CHAIN */:
        return new LLMChainRunner(this);
      case "vault_qa" /* VAULT_QA_CHAIN */:
        return new VaultQAChainRunner(this);
      case "copilot_plus" /* COPILOT_PLUS_CHAIN */:
        return new CopilotPlusChainRunner(this);
      default:
        throw new Error(`Unsupported chain type: ${chainType}`);
    }
  }
  async initializeQAChain(options) {
    if (options.refreshIndex) {
      await this.vectorStoreManager.indexVaultToVectorStore();
    }
  }
  async runChain(userMessage, abortController, updateCurrentAiMessage, addMessage, options = {}) {
    const { debug: debug4 = false, ignoreSystemMessage = false } = options;
    if (debug4)
      console.log("==== Step 0: Initial user message ====\n", userMessage);
    this.validateChatModel();
    this.validateChainInitialization();
    const chatModel = this.chatModelManager.getChatModel();
    const modelName = chatModel.modelName || chatModel.model || "";
    const isO1Model = modelName.startsWith("o1");
    if (ignoreSystemMessage || isO1Model) {
      let effectivePrompt = ChatPromptTemplate.fromMessages([
        new MessagesPlaceholder("history"),
        HumanMessagePromptTemplate.fromTemplate("{input}")
      ]);
      if (isO1Model) {
        effectivePrompt = ChatPromptTemplate.fromMessages([
          [AI_SENDER, getSystemPrompt() || ""],
          effectivePrompt
        ]);
      }
      this.setChain(getChainType(), {
        prompt: effectivePrompt
      });
    }
    const chainRunner = this.getChainRunner();
    return await chainRunner.run(
      userMessage,
      abortController,
      updateCurrentAiMessage,
      addMessage,
      options
    );
  }
  async updateMemoryWithLoadedMessages(messages) {
    await this.memoryManager.clearChatMemory();
    for (let i3 = 0; i3 < messages.length; i3 += 2) {
      const userMsg = messages[i3];
      const aiMsg = messages[i3 + 1];
      if (userMsg && aiMsg && userMsg.sender === USER_SENDER) {
        await this.memoryManager.getMemory().saveContext({ input: userMsg.message }, { output: aiMsg.message });
      }
    }
  }
};
var ChainManager = _ChainManager;
ChainManager.retrievedDocuments = [];

// src/chatUtils.ts
function parseChatContent(content) {
  const lines = content.split("\n");
  const messages = [];
  let currentSender = "";
  let currentMessage = "";
  let currentTimestamp = "";
  for (const line of lines) {
    if (line.startsWith("**user**:") || line.startsWith("**ai**:")) {
      if (currentSender && currentMessage) {
        messages.push({
          sender: currentSender === USER_SENDER ? USER_SENDER : AI_SENDER,
          message: currentMessage.trim(),
          isVisible: true,
          timestamp: currentTimestamp ? stringToFormattedDateTime(currentTimestamp) : null
        });
      }
      currentSender = line.startsWith("**user**:") ? USER_SENDER : AI_SENDER;
      currentMessage = line.substring(line.indexOf(":") + 1).trim();
      currentTimestamp = "";
    } else if (line.startsWith("[Timestamp:")) {
      currentTimestamp = line.substring(11, line.length - 1).trim();
    } else {
      currentMessage += "\n" + line;
    }
  }
  if (currentSender && currentMessage) {
    messages.push({
      sender: currentSender === USER_SENDER ? USER_SENDER : AI_SENDER,
      message: currentMessage.trim(),
      isVisible: true,
      timestamp: currentTimestamp ? stringToFormattedDateTime(currentTimestamp) : null
    });
  }
  return messages;
}
async function updateChatMemory(messages, memoryManager) {
  await memoryManager.clearChatMemory();
  for (let i3 = 0; i3 < messages.length - 1; i3++) {
    const msg = messages[i3];
    if (msg.sender === USER_SENDER) {
      const nextMsg = messages[i3 + 1];
      if (nextMsg?.sender === AI_SENDER) {
        await memoryManager.getMemory().saveContext({ input: msg.message }, { output: nextMsg.message });
      }
    }
  }
}

// src/commands/promptUtils.ts
function fixGrammarSpellingSelectionPrompt(selectedText) {
  return `<instruction>Fix the grammar and spelling of the text below. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.</instruction>

<text>${selectedText}</text>`;
}
function summarizePrompt(selectedText) {
  return `<instruction>Create a bullet-point summary of the text below. Identify the input language and respond in the same language. Each bullet point should capture a key point. Return only the bullet-point summary.</instruction>

<text>${selectedText}</text>`;
}
function tocPrompt(selectedText) {
  return `<instruction>Generate a hierarchical table of contents for the text below. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Maintain the original language. Return only the table of contents.</instruction>

<text>${selectedText}</text>`;
}
function glossaryPrompt(selectedText) {
  return `<instruction>Create a glossary of important terms, concepts, and phrases from the text below. Format each entry as "Term: Definition". Sort entries alphabetically. Maintain the original language. Return only the glossary.</instruction>

<text>${selectedText}</text>`;
}
function simplifyPrompt(selectedText) {
  return `<instruction>Simplify the text below to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original language and key concepts. Return only the simplified text.</instruction>

<text>${selectedText}</text>`;
}
function emojifyPrompt(selectedText) {
  return `<instruction>Add relevant emojis to enhance the text below. Follow these rules:
    1. Insert emojis at natural breaks in the text
    2. Never place two emojis next to each other
    3. Keep all original text unchanged
    4. Choose emojis that match the context and tone
    Return only the emojified text.</instruction>

<text>${selectedText}</text>`;
}
function removeUrlsFromSelectionPrompt(selectedText) {
  return `<instruction>Remove all URLs from the text below. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.</instruction>

<text>${selectedText}</text>`;
}
function rewriteTweetSelectionPrompt(selectedText) {
  return `<instruction>Rewrite the text below as a single tweet with these requirements:
    1. Maximum 280 characters
    2. Use concise, impactful language
    3. Maintain the core message
    4. Keep the original language
    Return only the tweet text.</instruction>

<text>${selectedText}</text>`;
}
function rewriteTweetThreadSelectionPrompt(selectedText) {
  return `<instruction>Convert the text below into a Twitter thread following these rules:
    1. Each tweet must be under 240 characters
    2. Start with "THREAD START" on its own line
    3. Separate tweets with "

---

"
    4. End with "THREAD END" on its own line
    5. Make content engaging and clear
    6. Maintain the original language
    Return only the formatted thread.</instruction>

<text>${selectedText}</text>`;
}
function rewriteShorterSelectionPrompt(selectedText) {
  return `<instruction>Reduce the text below to half its length while preserving these elements:
    1. Main ideas and key points
    2. Essential details
    3. Original tone and style
    4. Original language
    Return only the shortened text.</instruction>

<text>${selectedText}</text>`;
}
function rewriteLongerSelectionPrompt(selectedText) {
  return `<instruction>Expand the text below to twice its length by:
    1. Adding relevant details and examples
    2. Elaborating on key points
    3. Maintaining the original tone and style
    4. Keeping the original language
    Return only the expanded text.</instruction>

<text>${selectedText}</text>`;
}
function eli5SelectionPrompt(selectedText) {
  return `<instruction>Explain the text below in simple terms that a 5-year-old would understand:
    1. Use basic vocabulary
    2. Include simple analogies
    3. Break down complex concepts
    4. Keep the original language
    Return only the simplified explanation.</instruction>

<text>${selectedText}</text>`;
}
function rewritePressReleaseSelectionPrompt(selectedText) {
  return `<instruction>Transform the text below into a professional press release:
    1. Use formal, journalistic style
    2. Include headline and dateline
    3. Follow inverted pyramid structure
    4. Maintain the original language
    Return only the press release format.</instruction>

<text>${selectedText}</text>`;
}
function translateSelectionPrompt(selectedText, language) {
  return `<instruction>Translate the text below into ${language}:
    1. Preserve the meaning and tone
    2. Maintain appropriate cultural context
    3. Keep formatting and structure
    Return only the translated text.</instruction>

<text>${selectedText}</text>`;
}
function changeToneSelectionPrompt(selectedText, tone) {
  return `<instruction>Rewrite the text below in a ${tone} tone while:
    1. Keeping the original meaning
    2. Maintaining the original language
    3. Adjusting word choice and phrasing
    4. Preserving key information
    Return only the rewritten text.</instruction>

<text>${selectedText}</text>`;
}
var COMMAND_PROMPT_MAP = {
  [COMMAND_IDS.FIX_GRAMMAR]: fixGrammarSpellingSelectionPrompt,
  [COMMAND_IDS.SUMMARIZE]: summarizePrompt,
  [COMMAND_IDS.GENERATE_TOC]: tocPrompt,
  [COMMAND_IDS.GENERATE_GLOSSARY]: glossaryPrompt,
  [COMMAND_IDS.SIMPLIFY]: simplifyPrompt,
  [COMMAND_IDS.EMOJIFY]: emojifyPrompt,
  [COMMAND_IDS.REMOVE_URLS]: removeUrlsFromSelectionPrompt,
  [COMMAND_IDS.REWRITE_TWEET]: rewriteTweetSelectionPrompt,
  [COMMAND_IDS.REWRITE_TWEET_THREAD]: rewriteTweetThreadSelectionPrompt,
  [COMMAND_IDS.MAKE_SHORTER]: rewriteShorterSelectionPrompt,
  [COMMAND_IDS.MAKE_LONGER]: rewriteLongerSelectionPrompt,
  [COMMAND_IDS.ELI5]: eli5SelectionPrompt,
  [COMMAND_IDS.PRESS_RELEASE]: rewritePressReleaseSelectionPrompt,
  [COMMAND_IDS.TRANSLATE]: translateSelectionPrompt,
  [COMMAND_IDS.CHANGE_TONE]: changeToneSelectionPrompt
};

// src/components/modals/AddPromptModal.tsx
var import_obsidian16 = require("obsidian");
var AddPromptModal = class extends import_obsidian16.Modal {
  constructor(app2, onSave, initialTitle = "", initialPrompt = "", disabledTitle) {
    super(app2);
    this.contentEl.createEl("h2", { text: "User Custom Prompt" });
    const formContainer = this.contentEl.createEl("div", { cls: "copilot-command-modal" });
    const titleContainer = formContainer.createEl("div", {
      cls: "copilot-command-input-container"
    });
    titleContainer.createEl("h3", { text: "Title", cls: "copilot-command-header" });
    titleContainer.createEl("p", {
      text: "The title of the prompt, must be unique.",
      cls: "copilot-command-input-description"
    });
    const titleField = titleContainer.createEl("input", { type: "text" });
    if (disabledTitle) {
      titleField.setAttribute("disabled", "true");
    }
    if (initialTitle) {
      titleField.value = initialTitle;
    }
    const promptContainer = formContainer.createEl("div", {
      cls: "copilot-command-input-container"
    });
    promptContainer.createEl("h3", { text: "Prompt", cls: "copilot-command-header" });
    const promptDescFragment = createFragment((frag) => {
      frag.createEl("strong", { text: "- {} represents the selected text (not required). " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {[[Note Title]]} represents a note. " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {activeNote} represents the active note. " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {FolderPath} represents a folder of notes. " });
      frag.createEl("br");
      frag.createEl("strong", {
        text: "- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "
      });
      frag.createEl("br");
      frag.createEl("br");
      frag.appendText("Tip: turn on debug mode to show the processed prompt in the chat window.");
      frag.createEl("br");
      frag.createEl("br");
    });
    promptContainer.appendChild(promptDescFragment);
    const promptField = promptContainer.createEl("textarea");
    if (initialPrompt) {
      promptField.value = initialPrompt;
    }
    const descFragment = createFragment((frag) => {
      frag.appendText(
        "Save the prompt to the local prompt library. You can then use it with the Copilot command: "
      );
      frag.createEl("strong", { text: "Apply custom prompt to selection." });
      frag.createEl("br");
      frag.appendText("Check out the ");
      frag.createEl("a", {
        href: "https://github.com/f/awesome-chatgpt-prompts",
        text: "awesome chatGPT prompts"
      }).setAttr("target", "_blank");
      frag.appendText(" for inspiration.");
    });
    const descContainer = promptContainer.createEl("p", {
      cls: "copilot-command-input-description"
    });
    descContainer.appendChild(descFragment);
    const saveButtonContainer = formContainer.createEl("div", {
      cls: "copilot-command-save-btn-container"
    });
    const saveButton = saveButtonContainer.createEl("button", {
      text: "Save",
      cls: "copilot-command-save-btn"
    });
    saveButton.addEventListener("click", () => {
      if (titleField.value && promptField.value) {
        onSave(titleField.value, promptField.value);
        this.close();
      } else {
        new import_obsidian16.Notice("Please fill in both fields: Title and Prompt.");
      }
    });
  }
};

// src/components/modals/AdhocPromptModal.tsx
var import_obsidian17 = require("obsidian");
var AdhocPromptModal = class extends import_obsidian17.Modal {
  constructor(app2, onSubmit) {
    super(app2);
    this.placeholderText = "Please enter your custom ad-hoc prompt here, press enter to send.";
    this.onSubmit = onSubmit;
  }
  onOpen() {
    const { contentEl } = this;
    const promptDescFragment = createFragment((frag) => {
      frag.createEl("strong", { text: "- {} represents the selected text (not required). " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {[[Note Title]]} represents a note. " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {activeNote} represents the active note. " });
      frag.createEl("br");
      frag.createEl("strong", { text: "- {FolderPath} represents a folder of notes. " });
      frag.createEl("br");
      frag.createEl("strong", {
        text: "- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "
      });
      frag.createEl("br");
      frag.createEl("br");
      frag.appendText("Tip: turn on debug mode to show the processed prompt in the chat window.");
      frag.createEl("br");
      frag.createEl("br");
    });
    contentEl.appendChild(promptDescFragment);
    const textareaEl = contentEl.createEl("textarea", {
      attr: { placeholder: this.placeholderText }
    });
    textareaEl.style.width = "100%";
    textareaEl.style.height = "100px";
    textareaEl.style.padding = "10px";
    textareaEl.style.resize = "vertical";
    textareaEl.addEventListener("input", (evt) => {
      this.result = evt.target.value;
    });
    textareaEl.addEventListener("keydown", (evt) => {
      if (evt.key === "Enter" && !evt.shiftKey) {
        evt.preventDefault();
        this.close();
        this.onSubmit(this.result);
      }
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/components/modals/DebugSearchModal.tsx
var import_obsidian18 = require("obsidian");
var DebugSearchModal = class extends import_obsidian18.Modal {
  constructor(app2, plugin) {
    super(app2);
    this.plugin = plugin;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h2", { text: "Debug: Search OramaDB" });
    const descEl = contentEl.createEl("p");
    descEl.innerHTML = 'Enter a JSON search params object. Example:<br><pre>{<br>  "term": "#tag",<br>  "mode": "hybrid",<br>  "limit": 10,<br>  "includeVectors": true<br>}</pre>';
    this.searchInput = contentEl.createEl("textarea", {
      attr: {
        placeholder: "Enter search params JSON...",
        rows: "10",
        style: "width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"
      }
    });
    const buttonContainer = contentEl.createEl("div", {
      cls: "search-button-container"
    });
    const searchButton = buttonContainer.createEl("button", {
      text: "Search",
      cls: "mod-cta"
    });
    searchButton.addEventListener("click", async () => {
      try {
        const searchParams = JSON.parse(this.searchInput.value);
        if (searchParams.vector?.value && !Array.isArray(searchParams.vector.value)) {
          searchParams.vector.value = Object.values(searchParams.vector.value);
        }
        const db = await this.plugin.vectorStoreManager.getDb();
        if (!db) {
          new import_obsidian18.Notice("Database not found");
          return;
        }
        const searchResults = await search2(db, searchParams);
        const content = [
          "## Search Parameters",
          "```json",
          JSON.stringify(searchParams, null, 2),
          "```",
          "",
          "## Results",
          `Total hits: ${searchResults.hits.length}`,
          "",
          "### Hits",
          "```json",
          JSON.stringify(searchResults.hits, null, 2),
          "```"
        ].join("\n");
        const fileName = `OramaDB-Debug-Search.md`;
        const existingFile = this.app.vault.getAbstractFileByPath(fileName);
        if (existingFile instanceof import_obsidian18.TFile) {
          await this.app.vault.modify(existingFile, content);
        } else {
          await this.app.vault.create(fileName, content);
        }
        const file = this.app.vault.getAbstractFileByPath(fileName);
        if (file instanceof import_obsidian18.TFile) {
          await this.app.workspace.getLeaf().openFile(file);
          this.close();
        }
      } catch (error) {
        console.error("Error in debug search:", error);
        new import_obsidian18.Notice("Error executing search. Check console for details.");
      }
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/components/modals/InlineEditModal.tsx
var import_obsidian19 = require("obsidian");
var import_react5 = __toESM(require_react());
var import_client4 = __toESM(require_client());
function InlineEditModalContent({
  originalText,
  promptMessage,
  chainManager,
  commandId,
  onInsert,
  onReplace,
  onClose
}) {
  const [aiCurrentMessage, setAiCurrentMessage] = (0, import_react5.useState)(null);
  const [processedMessage, setProcessedMessage] = (0, import_react5.useState)(null);
  const commandName = COMMAND_NAMES[commandId];
  const handleAddMessage = (0, import_react5.useCallback)((message) => {
    setProcessedMessage(message.message);
  }, []);
  (0, import_react5.useEffect)(() => {
    const abortController = new AbortController();
    async function stream() {
      let fullAIResponse = "";
      const chatStream = await ChatModelManager.getInstance().getChatModel().stream(promptMessage.message);
      for await (const chunk of chatStream) {
        if (abortController?.signal.aborted)
          break;
        fullAIResponse += chunk.content;
        setAiCurrentMessage(fullAIResponse);
      }
      if (!abortController?.signal.aborted) {
        setProcessedMessage(fullAIResponse);
      }
    }
    stream();
    return () => {
      abortController.abort();
    };
  }, [promptMessage, chainManager, handleAddMessage]);
  return /* @__PURE__ */ import_react5.default.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ import_react5.default.createElement("div", { className: "max-h-60 overflow-y-auto text-muted whitespace-pre-wrap" }, originalText), commandName && /* @__PURE__ */ import_react5.default.createElement("div", { className: "text-normal flex items-center gap-2 font-bold" }, /* @__PURE__ */ import_react5.default.createElement(PenLine, { className: "w-4 h-4" }), commandName), /* @__PURE__ */ import_react5.default.createElement("div", { className: "relative group" }, /* @__PURE__ */ import_react5.default.createElement(
    "textarea",
    {
      className: "w-full h-60 text-text peer",
      value: processedMessage ?? aiCurrentMessage ?? "loading...",
      disabled: processedMessage == null,
      onChange: (e3) => setProcessedMessage(e3.target.value)
    }
  ), processedMessage && /* @__PURE__ */ import_react5.default.createElement(
    "button",
    {
      className: "absolute top-2 right-2 opacity-0 peer-focus-visible:!opacity-0 group-hover:opacity-100 transition-opacity",
      onClick: () => {
        navigator.clipboard.writeText(processedMessage);
        new import_obsidian19.Notice("Copied to clipboard");
      }
    },
    /* @__PURE__ */ import_react5.default.createElement(Copy, { className: "w-4 h-4 text-muted-foreground hover:text-accent" })
  )), /* @__PURE__ */ import_react5.default.createElement("div", { className: "flex justify-end gap-2" }, /* @__PURE__ */ import_react5.default.createElement("button", { onClick: onClose }, "Close"), /* @__PURE__ */ import_react5.default.createElement(
    "button",
    {
      disabled: processedMessage == null,
      className: "!bg-interactive-accent !text-on-accent cursor-pointer",
      onClick: () => onInsert(processedMessage ?? "")
    },
    "Insert"
  ), /* @__PURE__ */ import_react5.default.createElement(
    "button",
    {
      disabled: processedMessage == null,
      className: "!bg-interactive-accent !text-on-accent cursor-pointer",
      onClick: () => onReplace(processedMessage ?? "")
    },
    "Replace"
  )));
}
var InlineEditModal = class extends import_obsidian19.Modal {
  constructor(app2, configs) {
    super(app2);
    this.configs = configs;
  }
  onOpen() {
    const { contentEl } = this;
    this.root = (0, import_client4.createRoot)(contentEl);
    const { selectedText, commandId, promptMessage, chainManager } = this.configs;
    const handleInsert = (message) => {
      insertIntoEditor(message);
      this.close();
    };
    const handleReplace = (message) => {
      insertIntoEditor(message, true);
      this.close();
    };
    const handleClose = () => {
      this.close();
    };
    this.root.render(
      /* @__PURE__ */ import_react5.default.createElement(
        InlineEditModalContent,
        {
          originalText: selectedText,
          promptMessage,
          chainManager,
          commandId,
          onInsert: handleInsert,
          onReplace: handleReplace,
          onClose: handleClose
        }
      )
    );
  }
  onClose() {
    this.root.unmount();
  }
};

// src/components/modals/LanguageModal.tsx
var import_obsidian20 = require("obsidian");
var LANGUAGES = [
  { code: "en", name: "English" },
  { code: "zh", name: "Chinese" },
  { code: "ja", name: "Japanese" },
  { code: "ko", name: "Korean" },
  { code: "es", name: "Spanish" },
  { code: "fr", name: "French" },
  { code: "de", name: "German" },
  { code: "it", name: "Italian" },
  { code: "pt", name: "Portuguese" },
  { code: "ru", name: "Russian" },
  { code: "ar", name: "Arabic" },
  { code: "bn", name: "Bengali" },
  { code: "cs", name: "Czech" },
  { code: "da", name: "Danish" },
  { code: "el", name: "Greek" },
  { code: "fi", name: "Finnish" },
  { code: "he", name: "Hebrew" },
  { code: "hi", name: "Hindi" },
  { code: "hu", name: "Hungarian" },
  { code: "id", name: "Indonesian" },
  { code: "ms", name: "Malay" },
  { code: "nl", name: "Dutch" },
  { code: "no", name: "Norwegian" },
  { code: "pl", name: "Polish" },
  { code: "sv", name: "Swedish" },
  { code: "th", name: "Thai" },
  { code: "tr", name: "Turkish" },
  { code: "uk", name: "Ukrainian" },
  { code: "vi", name: "Vietnamese" },
  { code: "af", name: "Afrikaans" },
  { code: "bg", name: "Bulgarian" },
  { code: "ca", name: "Catalan" },
  { code: "et", name: "Estonian" },
  { code: "fa", name: "Persian" },
  { code: "fil", name: "Filipino" },
  { code: "hr", name: "Croatian" },
  { code: "is", name: "Icelandic" },
  { code: "lt", name: "Lithuanian" },
  { code: "lv", name: "Latvian" },
  { code: "ro", name: "Romanian" },
  { code: "sk", name: "Slovak" },
  { code: "sl", name: "Slovenian" },
  { code: "sr", name: "Serbian" },
  { code: "sw", name: "Swahili" },
  { code: "ta", name: "Tamil" },
  { code: "te", name: "Telugu" },
  { code: "ur", name: "Urdu" },
  { code: "zu", name: "Zulu" },
  { code: "mn", name: "Mongolian" },
  { code: "ne", name: "Nepali" },
  { code: "pa", name: "Punjabi" },
  { code: "si", name: "Sinhala" }
];
var LanguageModal = class extends import_obsidian20.FuzzySuggestModal {
  constructor(app2, onChooseLanguage) {
    super(app2);
    this.onChooseLanguage = onChooseLanguage;
  }
  getItems() {
    return LANGUAGES;
  }
  getItemText(language) {
    return language.name;
  }
  onChooseItem(language, evt) {
    this.onChooseLanguage(language.name);
  }
};

// src/components/modals/ListPromptModal.tsx
var import_obsidian21 = require("obsidian");
var ListPromptModal = class extends import_obsidian21.FuzzySuggestModal {
  constructor(app2, promptTitles, onChoosePromptTitle, descriptions = []) {
    super(app2);
    this.promptTitles = promptTitles;
    this.onChoosePromptTitle = onChoosePromptTitle;
    this.descriptions = descriptions;
  }
  getItems() {
    return this.promptTitles;
  }
  getItemText(promptTitle) {
    const index2 = this.promptTitles.indexOf(promptTitle);
    const description = this.descriptions[index2];
    return description ? `${promptTitle} - ${description}` : promptTitle;
  }
  onChooseItem(promptTitle, evt) {
    const actualTitle = promptTitle.split(" - ")[0];
    this.onChoosePromptTitle(actualTitle);
  }
};

// src/components/modals/OramaSearchModal.tsx
var import_obsidian22 = require("obsidian");
var OramaSearchModal = class extends import_obsidian22.Modal {
  constructor(app2, plugin) {
    super(app2);
    this.plugin = plugin;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h2", { text: "Inspect Copilot Index by Note Paths" });
    this.searchInput = contentEl.createEl("textarea", {
      attr: {
        placeholder: "Enter note paths as markdown list:\n- [[Note 1]]\n- [[Note 2]]",
        rows: "10",
        style: "width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"
      }
    });
    const buttonContainer = contentEl.createEl("div", { cls: "search-button-container" });
    const searchButton = buttonContainer.createEl("button", {
      text: "Show Index Data",
      cls: "mod-cta"
    });
    searchButton.addEventListener("click", async () => {
      const input = this.searchInput.value;
      const notePaths = extractNoteTitles(input);
      if (notePaths.length === 0) {
        new import_obsidian22.Notice("No valid note paths found. Use format: - [[Note Name]]");
        return;
      }
      try {
        const dbOps = await this.plugin.vectorStoreManager.getDbOps();
        const results = await dbOps.getDocsJsonByPaths(notePaths);
        const fileName = `CopilotDB-Search-Results.md`;
        const content = [
          "## Searched Paths",
          ...notePaths.map((path) => `- [[${path}]]`),
          "",
          "## Index Data",
          "```json",
          JSON.stringify(results, null, 2),
          "```"
        ].join("\n");
        const existingFile = this.app.vault.getAbstractFileByPath(fileName);
        if (existingFile) {
          await this.app.vault.modify(existingFile, content);
        } else {
          await this.app.vault.create(fileName, content);
        }
        const file = this.app.vault.getAbstractFileByPath(fileName);
        if (file) {
          await this.app.workspace.getLeaf().openFile(file);
        }
        this.close();
      } catch (error) {
        console.error("Error searching DB:", error);
        new import_obsidian22.Notice("Error searching database. Check console for details.");
      }
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/components/modals/RemoveFromIndexModal.tsx
var import_obsidian23 = require("obsidian");
var RemoveFromIndexModal = class extends import_obsidian23.Modal {
  constructor(app2, onSubmit) {
    super(app2);
    this.filePaths = "";
    this.onSubmit = onSubmit;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.createEl("h2", { text: "Remove Files from Copilot Index" });
    const container = contentEl.createDiv({ cls: "remove-files-container" });
    new import_obsidian23.Setting(container).setName("File paths").setDesc(
      "Paste the markdown list of file paths to remove from the index. You can get the list by running the command `List all indexed files`."
    ).setClass("remove-files-setting").addTextArea(
      (text) => text.setPlaceholder("- [[path/to/file1.md]]\n- [[path/to/file2.md]]").setValue(this.filePaths).onChange((value) => {
        this.filePaths = value;
      })
    );
    new import_obsidian23.Setting(container).addButton(
      (btn) => btn.setButtonText("Remove").setCta().onClick(() => {
        const paths = this.filePaths.split("\n").map((line) => {
          const match2 = line.match(/\[\[(.*?)\]\]/);
          return match2 ? match2[1].trim() : "";
        }).filter((p3) => p3.length > 0);
        this.onSubmit(paths);
        this.close();
      })
    );
    contentEl.createEl("style", {
      text: `
        .remove-files-container {
          width: 100%;
          margin-top: 12px;
        }
        .remove-files-setting {
          display: block;
        }
        .remove-files-setting .setting-item-control {
          padding: 0;
        }
        .remove-files-setting textarea {
          width: 100%;
          height: 300px;
          margin-top: 12px;
        }
        .remove-files-setting textarea::placeholder {
          opacity: 0.5;
        }
      `
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/components/modals/ToneModal.tsx
var import_obsidian24 = require("obsidian");
var TONES = ["Professional", "Casual", "Straightforward", "Confident", "Friendly"];
var ToneModal = class extends import_obsidian24.FuzzySuggestModal {
  constructor(app2, onChooseTone) {
    super(app2);
    this.onChooseTone = onChooseTone;
  }
  getItems() {
    return TONES;
  }
  getItemText(tone) {
    return tone;
  }
  onChooseItem(tone, evt) {
    this.onChooseTone(tone);
  }
};

// src/promptUsageStrategy.ts
var TimestampUsageStrategy = class {
  get usageData() {
    return getSettings().promptUsageTimestamps;
  }
  recordUsage(promptTitle) {
    updateSetting("promptUsageTimestamps", { ...this.usageData, [promptTitle]: Date.now() });
  }
  updateUsage(oldTitle, newTitle) {
    const newUsageData = { ...this.usageData };
    newUsageData[newTitle] = newUsageData[oldTitle];
    delete newUsageData[oldTitle];
    updateSetting("promptUsageTimestamps", newUsageData);
  }
  removeUnusedPrompts(existingPromptTitles) {
    const newUsageData = { ...this.usageData };
    for (const key of Object.keys(newUsageData)) {
      if (!existingPromptTitles.includes(key)) {
        delete newUsageData[key];
      }
    }
    updateSetting("promptUsageTimestamps", newUsageData);
  }
  compare(aKey, bKey) {
    return (this.usageData[aKey] || 0) - (this.usageData[bKey] || 0);
  }
};

// src/customPromptProcessor.ts
var import_obsidian25 = require("obsidian");
var CustomPromptProcessor = class {
  constructor(vault) {
    this.vault = vault;
    this.lastProcessedPrompt = null;
    this.usageStrategy = new TimestampUsageStrategy();
  }
  get customPromptsFolder() {
    return getSettings().customPromptsFolder;
  }
  static getInstance(vault) {
    if (!CustomPromptProcessor.instance) {
      CustomPromptProcessor.instance = new CustomPromptProcessor(vault);
    }
    return CustomPromptProcessor.instance;
  }
  recordPromptUsage(title) {
    this.usageStrategy.recordUsage(title);
  }
  async getAllPrompts() {
    const folder = this.customPromptsFolder;
    const files = this.vault.getFiles().filter((file) => file.path.startsWith(folder) && file.extension === "md");
    const prompts = [];
    for (const file of files) {
      const content = await this.vault.read(file);
      prompts.push({
        title: file.basename,
        content
      });
    }
    this.usageStrategy.removeUnusedPrompts(prompts.map((prompt) => prompt.title));
    return prompts.sort((a3, b3) => this.usageStrategy.compare(b3.title, a3.title) || 0);
  }
  async getPrompt(title) {
    const filePath = `${this.customPromptsFolder}/${title}.md`;
    const file = this.vault.getAbstractFileByPath(filePath);
    if (file instanceof import_obsidian25.TFile) {
      const content = await this.vault.read(file);
      return { title, content };
    }
    return null;
  }
  async savePrompt(title, content) {
    const folderPath = (0, import_obsidian25.normalizePath)(this.customPromptsFolder);
    const filePath = `${folderPath}/${title}.md`;
    const folderExists = await this.vault.adapter.exists(folderPath);
    if (!folderExists) {
      await this.vault.createFolder(folderPath);
    }
    await this.vault.create(filePath, content);
  }
  async updatePrompt(originTitle, newTitle, content) {
    const filePath = `${this.customPromptsFolder}/${originTitle}.md`;
    const file = this.vault.getAbstractFileByPath(filePath);
    if (file instanceof import_obsidian25.TFile) {
      if (originTitle !== newTitle) {
        const newFilePath = `${this.customPromptsFolder}/${newTitle}.md`;
        const newFileExists = this.vault.getAbstractFileByPath(newFilePath);
        if (newFileExists) {
          throw new CustomError(
            "Error saving custom prompt. Please check if the title already exists."
          );
        }
        this.usageStrategy.updateUsage(originTitle, newTitle);
        await this.vault.rename(file, newFilePath);
      }
      await this.vault.modify(file, content);
    }
  }
  async deletePrompt(title) {
    const filePath = `${this.customPromptsFolder}/${title}.md`;
    const file = this.vault.getAbstractFileByPath(filePath);
    if (file instanceof import_obsidian25.TFile) {
      this.usageStrategy.removeUnusedPrompts([title]);
      await this.vault.delete(file);
    }
  }
  /**
   * Extract variables and get their content.
   *
   * @param {CustomPrompt} doc - the custom prompt to process
   * @return {Promise<string[]>} the processed custom prompt
   */
  async extractVariablesFromPrompt(customPrompt, activeNote) {
    const variablesWithContent = [];
    const variableRegex = /\{([^}]+)\}/g;
    let match2;
    while ((match2 = variableRegex.exec(customPrompt)) !== null) {
      const variableName = match2[1].trim();
      const notes = [];
      if (variableName.toLowerCase() === "activenote") {
        if (activeNote) {
          const content = await getFileContent(activeNote, this.vault);
          if (content) {
            notes.push({ name: getFileName(activeNote), content });
          }
        } else {
          new import_obsidian25.Notice("No active note found.");
        }
      } else if (variableName.startsWith("#")) {
        const tagNames = variableName.slice(1).split(",").map((tag) => tag.trim());
        const noteFiles = await getNotesFromTags(this.vault, tagNames);
        for (const file of noteFiles) {
          const content = await getFileContent(file, this.vault);
          if (content) {
            notes.push({ name: getFileName(file), content });
          }
        }
      } else {
        const processedVariableName = processVariableNameForNotePath(variableName);
        const noteFiles = await getNotesFromPath(this.vault, processedVariableName);
        for (const file of noteFiles) {
          const content = await getFileContent(file, this.vault);
          if (content) {
            notes.push({ name: getFileName(file), content });
          }
        }
      }
      if (notes.length > 0) {
        const markdownContent = notes.map((note) => `## ${note.name}

${note.content}`).join("\n\n");
        variablesWithContent.push(markdownContent);
      } else {
        console.warn(`No notes found for variable: ${variableName}`);
      }
    }
    return variablesWithContent;
  }
  // TODO: return the processed variables along with the processed prompt and
  // remove getProcessedVariables
  async processCustomPrompt(customPrompt, selectedText, activeNote) {
    this.lastProcessedPrompt = customPrompt;
    const variablesWithContent = await this.extractVariablesFromPrompt(customPrompt, activeNote);
    let processedPrompt = customPrompt;
    const matches = [...processedPrompt.matchAll(/\{([^}]+)\}/g)];
    let additionalInfo = "";
    let activeNoteContent = null;
    if (processedPrompt.includes("{}")) {
      processedPrompt = processedPrompt.replace(/\{\}/g, "{selectedText}");
      if (selectedText) {
        additionalInfo += `selectedText:

 ${selectedText}`;
      } else if (activeNote) {
        activeNoteContent = await getFileContent(activeNote, this.vault);
        additionalInfo += `selectedText (entire active note):

 ${activeNoteContent}`;
      } else {
        additionalInfo += `selectedText:

 (No selected text or active note available)`;
      }
    }
    for (let i3 = 0; i3 < variablesWithContent.length; i3++) {
      if (matches[i3]) {
        const varname = matches[i3][1];
        if (varname.toLowerCase() === "activenote" && activeNoteContent) {
          continue;
        }
        additionalInfo += `

${varname}:

${variablesWithContent[i3]}`;
      }
    }
    const noteTitles = extractNoteTitles(processedPrompt);
    for (const noteTitle of noteTitles) {
      if (!matches.some((match2) => match2[1].includes(`[[${noteTitle}]]`))) {
        const noteFile = await getNoteFileFromTitle(this.vault, noteTitle);
        if (noteFile) {
          const noteContent = await getFileContent(noteFile, this.vault);
          additionalInfo += `

[[${noteTitle}]]:

${noteContent}`;
        }
      }
    }
    return processedPrompt + "\n\n" + additionalInfo;
  }
  // TODO: remove this
  async getProcessedVariables() {
    const processedVars = /* @__PURE__ */ new Set();
    const matches = this.lastProcessedPrompt?.matchAll(/\{([^}]+)\}/g) || [];
    for (const match2 of matches) {
      processedVars.add(match2[1]);
    }
    const noteTitles = extractNoteTitles(this.lastProcessedPrompt || "");
    for (const title of noteTitles) {
      processedVars.add(`[[${title}]]`);
    }
    return processedVars;
  }
};

// src/commands/index.ts
var import_obsidian26 = require("obsidian");
function isCommandEnabled(id) {
  const commandSettings = getSettings().enabledCommands[id];
  return commandSettings?.enabled !== false;
}
function addCommand(plugin, id, callback) {
  if (isCommandEnabled(id)) {
    plugin.addCommand({
      id,
      name: COMMAND_NAMES[id],
      callback
    });
  }
}
function addEditorCommand(plugin, id, callback) {
  if (isCommandEnabled(id)) {
    plugin.addCommand({
      id,
      name: COMMAND_NAMES[id],
      editorCallback: callback
    });
  }
}
function addCheckCommand(plugin, id, callback) {
  if (isCommandEnabled(id)) {
    plugin.addCommand({
      id,
      name: COMMAND_NAMES[id],
      checkCallback: callback
    });
  }
}
async function processInlineEditCommand(plugin, editor, commandId, eventSubtype) {
  const selectedText = editor.getSelection().trim();
  if (!selectedText) {
    return;
  }
  const promptFn = COMMAND_PROMPT_MAP[commandId];
  const messageWithPrompt = await promptFn(selectedText, eventSubtype);
  const promptMessage = {
    message: messageWithPrompt,
    sender: USER_SENDER,
    isVisible: false,
    timestamp: formatDateTime(new Date())
  };
  if (selectedText) {
    new InlineEditModal(app, {
      selectedText,
      commandId,
      promptMessage,
      chainManager: plugin.chainManager
    }).open();
  }
}
function registerBuiltInCommands(plugin) {
  DISABLEABLE_COMMANDS.forEach((id) => {
    plugin.removeCommand(id);
  });
  const promptProcessor = CustomPromptProcessor.getInstance(plugin.app.vault);
  addEditorCommand(plugin, COMMAND_IDS.FIX_GRAMMAR, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.FIX_GRAMMAR);
  });
  addEditorCommand(plugin, COMMAND_IDS.SUMMARIZE, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.SUMMARIZE);
  });
  addEditorCommand(plugin, COMMAND_IDS.GENERATE_TOC, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.GENERATE_TOC);
  });
  addEditorCommand(plugin, COMMAND_IDS.GENERATE_GLOSSARY, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.GENERATE_GLOSSARY);
  });
  addEditorCommand(plugin, COMMAND_IDS.SIMPLIFY, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.SIMPLIFY);
  });
  addEditorCommand(plugin, COMMAND_IDS.EMOJIFY, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.EMOJIFY);
  });
  addEditorCommand(plugin, COMMAND_IDS.REMOVE_URLS, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.REMOVE_URLS);
  });
  addEditorCommand(plugin, COMMAND_IDS.REWRITE_TWEET, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.REWRITE_TWEET);
  });
  addEditorCommand(plugin, COMMAND_IDS.REWRITE_TWEET_THREAD, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.REWRITE_TWEET_THREAD);
  });
  addEditorCommand(plugin, COMMAND_IDS.MAKE_SHORTER, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.MAKE_SHORTER);
  });
  addEditorCommand(plugin, COMMAND_IDS.MAKE_LONGER, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.MAKE_LONGER);
  });
  addEditorCommand(plugin, COMMAND_IDS.ELI5, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.ELI5);
  });
  addEditorCommand(plugin, COMMAND_IDS.PRESS_RELEASE, (editor) => {
    processInlineEditCommand(plugin, editor, COMMAND_IDS.PRESS_RELEASE);
  });
  addEditorCommand(plugin, COMMAND_IDS.TRANSLATE, (editor) => {
    new LanguageModal(plugin.app, (language) => {
      if (!language) {
        new import_obsidian26.Notice("Please select a language.");
        return;
      }
      processInlineEditCommand(plugin, editor, COMMAND_IDS.TRANSLATE, language);
    }).open();
  });
  addEditorCommand(plugin, COMMAND_IDS.CHANGE_TONE, (editor) => {
    new ToneModal(plugin.app, (tone) => {
      if (!tone) {
        new import_obsidian26.Notice("Please select a tone.");
        return;
      }
      processInlineEditCommand(plugin, editor, COMMAND_IDS.CHANGE_TONE, tone);
    }).open();
  });
  addEditorCommand(plugin, COMMAND_IDS.COUNT_WORD_AND_TOKENS_SELECTION, async (editor) => {
    const selectedText = await editor.getSelection();
    const wordCount = selectedText.split(" ").length;
    const tokenCount = await plugin.chainManager.chatModelManager.countTokens(selectedText);
    new import_obsidian26.Notice(`Selected text contains ${wordCount} words and ${tokenCount} tokens.`);
  });
  addCommand(plugin, COMMAND_IDS.COUNT_TOTAL_VAULT_TOKENS, async () => {
    try {
      const allContent = await getAllQAMarkdownContent(plugin.app);
      const totalTokens = await plugin.chainManager.chatModelManager.countTokens(allContent);
      new import_obsidian26.Notice(`Total tokens in your vault: ${totalTokens}`);
    } catch (error) {
      console.error("Error counting tokens: ", error);
      new import_obsidian26.Notice("An error occurred while counting tokens.");
    }
  });
  addCommand(plugin, COMMAND_IDS.TOGGLE_COPILOT_CHAT_WINDOW, () => {
    plugin.toggleView();
  });
  addCommand(plugin, COMMAND_IDS.OPEN_COPILOT_CHAT_WINDOW, () => {
    plugin.activateView();
  });
  addCommand(plugin, COMMAND_IDS.ADD_CUSTOM_PROMPT, () => {
    new AddPromptModal(plugin.app, async (title, prompt) => {
      try {
        await promptProcessor.savePrompt(title, prompt);
        new import_obsidian26.Notice("Custom prompt saved successfully.");
      } catch (e3) {
        new import_obsidian26.Notice("Error saving custom prompt. Please check if the title already exists.");
        console.error(e3);
      }
    }).open();
  });
  addCommand(plugin, COMMAND_IDS.APPLY_CUSTOM_PROMPT, async () => {
    const prompts = await promptProcessor.getAllPrompts();
    const promptTitles = prompts.map((p3) => p3.title);
    new ListPromptModal(plugin.app, promptTitles, async (promptTitle) => {
      if (!promptTitle) {
        new import_obsidian26.Notice("Please select a prompt title.");
        return;
      }
      try {
        const prompt = await promptProcessor.getPrompt(promptTitle);
        if (!prompt) {
          new import_obsidian26.Notice(`No prompt found with the title "${promptTitle}".`);
          return;
        }
        plugin.processCustomPrompt(COMMAND_IDS.APPLY_CUSTOM_PROMPT, prompt.content);
      } catch (err) {
        console.error(err);
        new import_obsidian26.Notice("An error occurred.");
      }
    }).open();
  });
  addCommand(plugin, COMMAND_IDS.APPLY_ADHOC_PROMPT, async () => {
    const modal = new AdhocPromptModal(plugin.app, async (adhocPrompt) => {
      try {
        plugin.processCustomPrompt(COMMAND_IDS.APPLY_ADHOC_PROMPT, adhocPrompt);
      } catch (err) {
        console.error(err);
        new import_obsidian26.Notice("An error occurred.");
      }
    });
    modal.open();
  });
  addCheckCommand(plugin, COMMAND_IDS.DELETE_CUSTOM_PROMPT, (checking) => {
    if (checking) {
      return true;
    }
    promptProcessor.getAllPrompts().then((prompts) => {
      const promptTitles = prompts.map((p3) => p3.title);
      new ListPromptModal(plugin.app, promptTitles, async (promptTitle) => {
        if (!promptTitle) {
          new import_obsidian26.Notice("Please select a prompt title.");
          return;
        }
        try {
          await promptProcessor.deletePrompt(promptTitle);
          new import_obsidian26.Notice(`Prompt "${promptTitle}" has been deleted.`);
        } catch (err) {
          console.error(err);
          new import_obsidian26.Notice("An error occurred while deleting the prompt.");
        }
      }).open();
    });
    return true;
  });
  addCheckCommand(plugin, COMMAND_IDS.EDIT_CUSTOM_PROMPT, (checking) => {
    if (checking) {
      return true;
    }
    promptProcessor.getAllPrompts().then((prompts) => {
      const promptTitles = prompts.map((p3) => p3.title);
      new ListPromptModal(plugin.app, promptTitles, async (promptTitle) => {
        if (!promptTitle) {
          new import_obsidian26.Notice("Please select a prompt title.");
          return;
        }
        try {
          const prompt = await promptProcessor.getPrompt(promptTitle);
          if (prompt) {
            new AddPromptModal(
              plugin.app,
              async (title, newPrompt) => {
                try {
                  await promptProcessor.updatePrompt(promptTitle, title, newPrompt);
                  new import_obsidian26.Notice(`Prompt "${title}" has been updated.`);
                } catch (err) {
                  console.error(err);
                  if (err instanceof CustomError) {
                    new import_obsidian26.Notice(err.message);
                  } else {
                    new import_obsidian26.Notice("An error occurred.");
                  }
                }
              },
              prompt.title,
              prompt.content,
              false
            ).open();
          } else {
            new import_obsidian26.Notice(`No prompt found with the title "${promptTitle}".`);
          }
        } catch (err) {
          console.error(err);
          new import_obsidian26.Notice("An error occurred.");
        }
      }).open();
    });
    return true;
  });
  addCommand(plugin, COMMAND_IDS.CLEAR_LOCAL_COPILOT_INDEX, async () => {
    await plugin.vectorStoreManager.clearIndex();
  });
  addCommand(plugin, COMMAND_IDS.GARBAGE_COLLECT_COPILOT_INDEX, async () => {
    try {
      const removedDocs = await plugin.vectorStoreManager.garbageCollectVectorStore();
      new import_obsidian26.Notice(`${removedDocs} documents removed from Copilot index.`);
    } catch (err) {
      console.error("Error garbage collecting the Copilot index:", err);
      new import_obsidian26.Notice("An error occurred while garbage collecting the Copilot index.");
    }
  });
  addCommand(plugin, COMMAND_IDS.INDEX_VAULT_TO_COPILOT_INDEX, async () => {
    try {
      const indexedFileCount = await plugin.vectorStoreManager.indexVaultToVectorStore();
      new import_obsidian26.Notice(`${indexedFileCount} vault files indexed to Copilot index.`);
    } catch (err) {
      console.error("Error indexing vault to Copilot index:", err);
      new import_obsidian26.Notice("An error occurred while indexing vault to Copilot index.");
    }
  });
  addCommand(plugin, COMMAND_IDS.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX, async () => {
    try {
      const indexedFileCount = await plugin.vectorStoreManager.indexVaultToVectorStore(true);
      new import_obsidian26.Notice(`${indexedFileCount} vault files re-indexed to Copilot index.`);
    } catch (err) {
      console.error("Error re-indexing vault to Copilot index:", err);
      new import_obsidian26.Notice("An error occurred while re-indexing vault to Copilot index.");
    }
  });
  addCommand(plugin, COMMAND_IDS.LOAD_COPILOT_CHAT_CONVERSATION, () => {
    plugin.loadCopilotChatHistory();
  });
  addCommand(plugin, COMMAND_IDS.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS, () => {
    new OramaSearchModal(plugin.app, plugin).open();
  });
  addCommand(plugin, COMMAND_IDS.SEARCH_ORAMA_DB, () => {
    new DebugSearchModal(plugin.app, plugin).open();
  });
  addCommand(plugin, COMMAND_IDS.LIST_INDEXED_FILES, async () => {
    try {
      const indexedFiles = await plugin.vectorStoreManager.getIndexedFiles();
      const indexedFilePaths = new Set(indexedFiles);
      const allMarkdownFiles = plugin.app.vault.getMarkdownFiles();
      const emptyFiles = /* @__PURE__ */ new Set();
      const unindexedFiles = /* @__PURE__ */ new Set();
      const filesWithoutEmbeddings = /* @__PURE__ */ new Set();
      const dbOps = await plugin.vectorStoreManager.getDbOps();
      for (const file2 of allMarkdownFiles) {
        const content2 = await plugin.app.vault.cachedRead(file2);
        if (!content2 || content2.trim().length === 0) {
          emptyFiles.add(file2.path);
        } else if (!indexedFilePaths.has(file2.path)) {
          unindexedFiles.add(file2.path);
        } else {
          const hasEmbeddings = await dbOps.hasEmbeddings(file2.path);
          if (!hasEmbeddings) {
            filesWithoutEmbeddings.add(file2.path);
          }
        }
      }
      if (indexedFiles.length === 0 && emptyFiles.size === 0 && unindexedFiles.size === 0) {
        new import_obsidian26.Notice("No files found to list.");
        return;
      }
      const content = [
        "# Copilot Files Status",
        `- Indexed files: ${indexedFiles.length}`,
        `	- Files missing embeddings: ${filesWithoutEmbeddings.size}`,
        `- Unindexed files: ${unindexedFiles.size}`,
        `- Empty files: ${emptyFiles.size}`,
        "",
        "## Indexed Files",
        ...indexedFiles.map((file2) => {
          const noEmbedding = filesWithoutEmbeddings.has(file2);
          return `- [[${file2}]]${noEmbedding ? " *(embedding missing)*" : ""}`;
        }),
        "",
        "## Unindexed Files",
        ...unindexedFiles.size > 0 ? Array.from(unindexedFiles).sort().map((file2) => `- [[${file2}]]`) : ["No unindexed files found."],
        "",
        "## Empty Files",
        ...emptyFiles.size > 0 ? Array.from(emptyFiles).sort().map((file2) => `- [[${file2}]]`) : ["No empty files found."]
      ].join("\n");
      const fileName = `Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g, "-")}.md`;
      const filePath = `${fileName}`;
      const existingFile = plugin.app.vault.getAbstractFileByPath(filePath);
      if (existingFile instanceof import_obsidian26.TFile) {
        await plugin.app.vault.modify(existingFile, content);
      } else {
        await plugin.app.vault.create(filePath, content);
      }
      const file = plugin.app.vault.getAbstractFileByPath(filePath);
      if (file instanceof import_obsidian26.TFile) {
        await plugin.app.workspace.getLeaf().openFile(file);
        new import_obsidian26.Notice(`Listed ${indexedFiles.length} indexed files`);
      }
    } catch (error) {
      console.error("Error listing indexed files:", error);
      new import_obsidian26.Notice("Failed to list indexed files.");
    }
  });
  addCommand(plugin, COMMAND_IDS.REMOVE_FILES_FROM_COPILOT_INDEX, async () => {
    new RemoveFromIndexModal(plugin.app, async (filePaths) => {
      const dbOps = await plugin.vectorStoreManager.getDbOps();
      try {
        for (const path of filePaths) {
          await dbOps.removeDocs(path);
        }
        await dbOps.saveDB();
        new import_obsidian26.Notice(`Successfully removed ${filePaths.length} files from the index.`);
      } catch (err) {
        console.error("Error removing files from index:", err);
        new import_obsidian26.Notice("An error occurred while removing files from the index.");
      }
    }).open();
  });
  addCommand(plugin, COMMAND_IDS.CLEAR_COPILOT_CACHE, async () => {
    try {
      await plugin.fileParserManager.clearPDFCache();
      new import_obsidian26.Notice("Copilot cache cleared successfully");
    } catch (error) {
      console.error("Error clearing Copilot cache:", error);
      new import_obsidian26.Notice("Failed to clear Copilot cache");
    }
  });
}

// src/components/chat-components/ChatControls.tsx
var import_react10 = __toESM(require_react());

// node_modules/@radix-ui/react-dropdown-menu/dist/index.mjs
var React44 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React6 = __toESM(require_react(), 1);
function setRef2(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs2(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef2(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef2(refs[i3], null);
          }
        }
      };
    }
  };
}

// node_modules/@radix-ui/react-context/dist/index.mjs
var React7 = __toESM(require_react(), 1);
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
function createContext22(rootComponentName, defaultContext) {
  const Context2 = React7.createContext(defaultContext);
  const Provider5 = (props) => {
    const { children, ...context } = props;
    const value = React7.useMemo(() => context, Object.values(context));
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Context2.Provider, { value, children });
  };
  Provider5.displayName = rootComponentName + "Provider";
  function useContext22(consumerName) {
    const context = React7.useContext(Context2);
    if (context)
      return context;
    if (defaultContext !== void 0)
      return defaultContext;
    throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
  }
  return [Provider5, useContext22];
}
function createContextScope(scopeName, createContextScopeDeps = []) {
  let defaultContexts = [];
  function createContext32(rootComponentName, defaultContext) {
    const BaseContext = React7.createContext(defaultContext);
    const index2 = defaultContexts.length;
    defaultContexts = [...defaultContexts, defaultContext];
    const Provider5 = (props) => {
      const { scope, children, ...context } = props;
      const Context2 = scope?.[scopeName]?.[index2] || BaseContext;
      const value = React7.useMemo(() => context, Object.values(context));
      return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Context2.Provider, { value, children });
    };
    Provider5.displayName = rootComponentName + "Provider";
    function useContext22(consumerName, scope) {
      const Context2 = scope?.[scopeName]?.[index2] || BaseContext;
      const context = React7.useContext(Context2);
      if (context)
        return context;
      if (defaultContext !== void 0)
        return defaultContext;
      throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
    }
    return [Provider5, useContext22];
  }
  const createScope2 = () => {
    const scopeContexts = defaultContexts.map((defaultContext) => {
      return React7.createContext(defaultContext);
    });
    return function useScope(scope) {
      const contexts = scope?.[scopeName] || scopeContexts;
      return React7.useMemo(
        () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),
        [scope, contexts]
      );
    };
  };
  createScope2.scopeName = scopeName;
  return [createContext32, composeContextScopes(createScope2, ...createContextScopeDeps)];
}
function composeContextScopes(...scopes) {
  const baseScope = scopes[0];
  if (scopes.length === 1)
    return baseScope;
  const createScope2 = () => {
    const scopeHooks = scopes.map((createScope22) => ({
      useScope: createScope22(),
      scopeName: createScope22.scopeName
    }));
    return function useComposedScopes(overrideScopes) {
      const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => {
        const scopeProps = useScope(overrideScopes);
        const currentScope = scopeProps[`__scope${scopeName}`];
        return { ...nextScopes2, ...currentScope };
      }, {});
      return React7.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);
    };
  };
  createScope2.scopeName = baseScope.scopeName;
  return createScope2;
}

// node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs
var React9 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-use-callback-ref/dist/index.mjs
var React8 = __toESM(require_react(), 1);
function useCallbackRef(callback) {
  const callbackRef = React8.useRef(callback);
  React8.useEffect(() => {
    callbackRef.current = callback;
  });
  return React8.useMemo(() => (...args) => callbackRef.current?.(...args), []);
}

// node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs
function useControllableState({
  prop,
  defaultProp,
  onChange = () => {
  }
}) {
  const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });
  const isControlled = prop !== void 0;
  const value = isControlled ? prop : uncontrolledProp;
  const handleChange = useCallbackRef(onChange);
  const setValue = React9.useCallback(
    (nextValue) => {
      if (isControlled) {
        const setter = nextValue;
        const value2 = typeof nextValue === "function" ? setter(prop) : nextValue;
        if (value2 !== prop)
          handleChange(value2);
      } else {
        setUncontrolledProp(nextValue);
      }
    },
    [isControlled, prop, setUncontrolledProp, handleChange]
  );
  return [value, setValue];
}
function useUncontrolledState({
  defaultProp,
  onChange
}) {
  const uncontrolledState = React9.useState(defaultProp);
  const [value] = uncontrolledState;
  const prevValueRef = React9.useRef(value);
  const handleChange = useCallbackRef(onChange);
  React9.useEffect(() => {
    if (prevValueRef.current !== value) {
      handleChange(value);
      prevValueRef.current = value;
    }
  }, [value, prevValueRef, handleChange]);
  return uncontrolledState;
}

// node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React11 = __toESM(require_react(), 1);
var ReactDOM = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-slot/dist/index.mjs
var React10 = __toESM(require_react(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var Slot2 = React10.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React10.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable2);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React10.Children.count(newElement) > 1)
          return React10.Children.only(null);
        return React10.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SlotClone2, { ...slotProps, ref: forwardedRef, children: React10.isValidElement(newElement) ? React10.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(SlotClone2, { ...slotProps, ref: forwardedRef, children });
});
Slot2.displayName = "Slot";
var SlotClone2 = React10.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React10.isValidElement(children)) {
    const childrenRef = getElementRef2(children);
    return React10.cloneElement(children, {
      ...mergeProps2(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs2(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React10.Children.count(children) > 1 ? React10.Children.only(null) : null;
});
SlotClone2.displayName = "SlotClone";
var Slottable2 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children });
};
function isSlottable2(child) {
  return React10.isValidElement(child) && child.type === Slottable2;
}
function mergeProps2(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef2(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-dropdown-menu/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var NODES = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive = NODES.reduce((primitive, node) => {
  const Node3 = React11.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot2 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});

// node_modules/@radix-ui/react-menu/dist/index.mjs
var React43 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers2(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-collection/dist/index.mjs
var import_react6 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React12 = __toESM(require_react(), 1);
function setRef3(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs3(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef3(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef3(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs2(...refs) {
  return React12.useCallback(composeRefs3(...refs), refs);
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-slot/dist/index.mjs
var React13 = __toESM(require_react(), 1);
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var Slot3 = React13.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React13.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable3);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React13.Children.count(newElement) > 1)
          return React13.Children.only(null);
        return React13.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SlotClone3, { ...slotProps, ref: forwardedRef, children: React13.isValidElement(newElement) ? React13.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SlotClone3, { ...slotProps, ref: forwardedRef, children });
});
Slot3.displayName = "Slot";
var SlotClone3 = React13.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React13.isValidElement(children)) {
    const childrenRef = getElementRef3(children);
    return React13.cloneElement(children, {
      ...mergeProps3(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs3(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React13.Children.count(children) > 1 ? React13.Children.only(null) : null;
});
SlotClone3.displayName = "SlotClone";
var Slottable3 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_jsx_runtime5.Fragment, { children });
};
function isSlottable3(child) {
  return React13.isValidElement(child) && child.type === Slottable3;
}
function mergeProps3(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef3(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-collection/dist/index.mjs
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
"use client";
function createCollection(name) {
  const PROVIDER_NAME2 = name + "CollectionProvider";
  const [createCollectionContext, createCollectionScope5] = createContextScope(PROVIDER_NAME2);
  const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(
    PROVIDER_NAME2,
    { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }
  );
  const CollectionProvider = (props) => {
    const { scope, children } = props;
    const ref = import_react6.default.useRef(null);
    const itemMap = import_react6.default.useRef(/* @__PURE__ */ new Map()).current;
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(CollectionProviderImpl, { scope, itemMap, collectionRef: ref, children });
  };
  CollectionProvider.displayName = PROVIDER_NAME2;
  const COLLECTION_SLOT_NAME = name + "CollectionSlot";
  const CollectionSlot = import_react6.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children } = props;
      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
      const composedRefs = useComposedRefs2(forwardedRef, context.collectionRef);
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Slot3, { ref: composedRefs, children });
    }
  );
  CollectionSlot.displayName = COLLECTION_SLOT_NAME;
  const ITEM_SLOT_NAME = name + "CollectionItemSlot";
  const ITEM_DATA_ATTR = "data-radix-collection-item";
  const CollectionItemSlot = import_react6.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children, ...itemData } = props;
      const ref = import_react6.default.useRef(null);
      const composedRefs = useComposedRefs2(forwardedRef, ref);
      const context = useCollectionContext(ITEM_SLOT_NAME, scope);
      import_react6.default.useEffect(() => {
        context.itemMap.set(ref, { ref, ...itemData });
        return () => void context.itemMap.delete(ref);
      });
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Slot3, { ...{ [ITEM_DATA_ATTR]: "" }, ref: composedRefs, children });
    }
  );
  CollectionItemSlot.displayName = ITEM_SLOT_NAME;
  function useCollection5(scope) {
    const context = useCollectionContext(name + "CollectionConsumer", scope);
    const getItems = import_react6.default.useCallback(() => {
      const collectionNode = context.collectionRef.current;
      if (!collectionNode)
        return [];
      const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
      const items = Array.from(context.itemMap.values());
      const orderedItems = items.sort(
        (a3, b3) => orderedNodes.indexOf(a3.ref.current) - orderedNodes.indexOf(b3.ref.current)
      );
      return orderedItems;
    }, [context.collectionRef, context.itemMap]);
    return getItems;
  }
  return [
    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },
    useCollection5,
    createCollectionScope5
  ];
}

// node_modules/@radix-ui/react-direction/dist/index.mjs
var React15 = __toESM(require_react(), 1);
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var DirectionContext = React15.createContext(void 0);
function useDirection(localDir) {
  const globalDir = React15.useContext(DirectionContext);
  return localDir || globalDir || "ltr";
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var React18 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React16 = __toESM(require_react(), 1);
var ReactDOM2 = __toESM(require_react_dom(), 1);
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var NODES2 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive2 = NODES2.reduce((primitive, node) => {
  const Node3 = React16.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot3 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});
function dispatchDiscreteCustomEvent(target, event) {
  if (target)
    ReactDOM2.flushSync(() => target.dispatchEvent(event));
}

// node_modules/@radix-ui/react-use-escape-keydown/dist/index.mjs
var React17 = __toESM(require_react(), 1);
function useEscapeKeydown(onEscapeKeyDownProp, ownerDocument = globalThis?.document) {
  const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp);
  React17.useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === "Escape") {
        onEscapeKeyDown(event);
      }
    };
    ownerDocument.addEventListener("keydown", handleKeyDown, { capture: true });
    return () => ownerDocument.removeEventListener("keydown", handleKeyDown, { capture: true });
  }, [onEscapeKeyDown, ownerDocument]);
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
"use client";
var DISMISSABLE_LAYER_NAME = "DismissableLayer";
var CONTEXT_UPDATE = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE = "dismissableLayer.focusOutside";
var originalBodyPointerEvents;
var DismissableLayerContext = React18.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer = React18.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = React18.useContext(DismissableLayerContext);
    const [node, setNode] = React18.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = React18.useState({});
    const composedRefs = useComposedRefs2(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch)
        return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    React18.useEffect(() => {
      if (!node)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    React18.useEffect(() => {
      return () => {
        if (!node)
          return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate();
      };
    }, [node, context]);
    React18.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
      Primitive2.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers2(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers2(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers2(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer.displayName = DISMISSABLE_LAYER_NAME;
var BRANCH_NAME = "DismissableLayerBranch";
var DismissableLayerBranch = React18.forwardRef((props, forwardedRef) => {
  const context = React18.useContext(DismissableLayerContext);
  const ref = React18.useRef(null);
  const composedRefs = useComposedRefs2(forwardedRef, ref);
  React18.useEffect(() => {
    const node = ref.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Primitive2.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch.displayName = BRANCH_NAME;
function usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
  const isPointerInsideReactTreeRef = React18.useRef(false);
  const handleClickRef = React18.useRef(() => {
  });
  React18.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent(
            POINTER_DOWN_OUTSIDE,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef(onFocusOutside);
  const isFocusInsideReactTreeRef = React18.useRef(false);
  React18.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate() {
  const event = new CustomEvent(CONTEXT_UPDATE);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent(name, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });
  if (handler)
    target.addEventListener(name, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent(target, event);
  } else {
    target.dispatchEvent(event);
  }
}

// node_modules/@radix-ui/react-focus-guards/dist/index.mjs
var React19 = __toESM(require_react(), 1);
"use client";
var count3 = 0;
function useFocusGuards() {
  React19.useEffect(() => {
    const edgeGuards = document.querySelectorAll("[data-radix-focus-guard]");
    document.body.insertAdjacentElement("afterbegin", edgeGuards[0] ?? createFocusGuard());
    document.body.insertAdjacentElement("beforeend", edgeGuards[1] ?? createFocusGuard());
    count3++;
    return () => {
      if (count3 === 1) {
        document.querySelectorAll("[data-radix-focus-guard]").forEach((node) => node.remove());
      }
      count3--;
    };
  }, []);
}
function createFocusGuard() {
  const element = document.createElement("span");
  element.setAttribute("data-radix-focus-guard", "");
  element.tabIndex = 0;
  element.style.outline = "none";
  element.style.opacity = "0";
  element.style.position = "fixed";
  element.style.pointerEvents = "none";
  return element;
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-focus-scope/dist/index.mjs
var React20 = __toESM(require_react(), 1);
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
"use client";
var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount";
var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount";
var EVENT_OPTIONS = { bubbles: false, cancelable: true };
var FOCUS_SCOPE_NAME = "FocusScope";
var FocusScope = React20.forwardRef((props, forwardedRef) => {
  const {
    loop = false,
    trapped = false,
    onMountAutoFocus: onMountAutoFocusProp,
    onUnmountAutoFocus: onUnmountAutoFocusProp,
    ...scopeProps
  } = props;
  const [container, setContainer] = React20.useState(null);
  const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
  const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
  const lastFocusedElementRef = React20.useRef(null);
  const composedRefs = useComposedRefs2(forwardedRef, (node) => setContainer(node));
  const focusScope = React20.useRef({
    paused: false,
    pause() {
      this.paused = true;
    },
    resume() {
      this.paused = false;
    }
  }).current;
  React20.useEffect(() => {
    if (trapped) {
      let handleFocusIn2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const target = event.target;
        if (container.contains(target)) {
          lastFocusedElementRef.current = target;
        } else {
          focus(lastFocusedElementRef.current, { select: true });
        }
      }, handleFocusOut2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget === null)
          return;
        if (!container.contains(relatedTarget)) {
          focus(lastFocusedElementRef.current, { select: true });
        }
      }, handleMutations2 = function(mutations) {
        const focusedElement = document.activeElement;
        if (focusedElement !== document.body)
          return;
        for (const mutation of mutations) {
          if (mutation.removedNodes.length > 0)
            focus(container);
        }
      };
      var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
      document.addEventListener("focusin", handleFocusIn2);
      document.addEventListener("focusout", handleFocusOut2);
      const mutationObserver = new MutationObserver(handleMutations2);
      if (container)
        mutationObserver.observe(container, { childList: true, subtree: true });
      return () => {
        document.removeEventListener("focusin", handleFocusIn2);
        document.removeEventListener("focusout", handleFocusOut2);
        mutationObserver.disconnect();
      };
    }
  }, [trapped, container, focusScope.paused]);
  React20.useEffect(() => {
    if (container) {
      focusScopesStack.add(focusScope);
      const previouslyFocusedElement = document.activeElement;
      const hasFocusedCandidate = container.contains(previouslyFocusedElement);
      if (!hasFocusedCandidate) {
        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS);
        container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
        container.dispatchEvent(mountEvent);
        if (!mountEvent.defaultPrevented) {
          focusFirst(removeLinks(getTabbableCandidates(container)), { select: true });
          if (document.activeElement === previouslyFocusedElement) {
            focus(container);
          }
        }
      }
      return () => {
        container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
        setTimeout(() => {
          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS);
          container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
          container.dispatchEvent(unmountEvent);
          if (!unmountEvent.defaultPrevented) {
            focus(previouslyFocusedElement ?? document.body, { select: true });
          }
          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
          focusScopesStack.remove(focusScope);
        }, 0);
      };
    }
  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
  const handleKeyDown = React20.useCallback(
    (event) => {
      if (!loop && !trapped)
        return;
      if (focusScope.paused)
        return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container2 = event.currentTarget;
        const [first, last] = getTabbableEdges(container2);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container2)
            event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop)
              focus(first, { select: true });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop)
              focus(last, { select: true });
          }
        }
      }
    },
    [loop, trapped, focusScope.paused]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Primitive2.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
});
FocusScope.displayName = FOCUS_SCOPE_NAME;
function focusFirst(candidates, { select = false } = {}) {
  const previouslyFocusedElement = document.activeElement;
  for (const candidate of candidates) {
    focus(candidate, { select });
    if (document.activeElement !== previouslyFocusedElement)
      return;
  }
}
function getTabbableEdges(container) {
  const candidates = getTabbableCandidates(container);
  const first = findVisible(candidates, container);
  const last = findVisible(candidates.reverse(), container);
  return [first, last];
}
function getTabbableCandidates(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput)
        return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode())
    nodes.push(walker.currentNode);
  return nodes;
}
function findVisible(elements, container) {
  for (const element of elements) {
    if (!isHidden(element, { upTo: container }))
      return element;
  }
}
function isHidden(node, { upTo }) {
  if (getComputedStyle(node).visibility === "hidden")
    return true;
  while (node) {
    if (upTo !== void 0 && node === upTo)
      return false;
    if (getComputedStyle(node).display === "none")
      return true;
    node = node.parentElement;
  }
  return false;
}
function isSelectableInput(element) {
  return element instanceof HTMLInputElement && "select" in element;
}
function focus(element, { select = false } = {}) {
  if (element && element.focus) {
    const previouslyFocusedElement = document.activeElement;
    element.focus({ preventScroll: true });
    if (element !== previouslyFocusedElement && isSelectableInput(element) && select)
      element.select();
  }
}
var focusScopesStack = createFocusScopesStack();
function createFocusScopesStack() {
  let stack = [];
  return {
    add(focusScope) {
      const activeFocusScope = stack[0];
      if (focusScope !== activeFocusScope) {
        activeFocusScope?.pause();
      }
      stack = arrayRemove(stack, focusScope);
      stack.unshift(focusScope);
    },
    remove(focusScope) {
      stack = arrayRemove(stack, focusScope);
      stack[0]?.resume();
    }
  };
}
function arrayRemove(array, item) {
  const updatedArray = [...array];
  const index2 = updatedArray.indexOf(item);
  if (index2 !== -1) {
    updatedArray.splice(index2, 1);
  }
  return updatedArray;
}
function removeLinks(items) {
  return items.filter((item) => item.tagName !== "A");
}

// node_modules/@radix-ui/react-id/dist/index.mjs
var React22 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-use-layout-effect/dist/index.mjs
var React21 = __toESM(require_react(), 1);
var useLayoutEffect2 = Boolean(globalThis?.document) ? React21.useLayoutEffect : () => {
};

// node_modules/@radix-ui/react-id/dist/index.mjs
var useReactId = React22["useId".toString()] || (() => void 0);
var count4 = 0;
function useId(deterministicId) {
  const [id, setId] = React22.useState(useReactId());
  useLayoutEffect2(() => {
    if (!deterministicId)
      setId((reactId) => reactId ?? String(count4++));
  }, [deterministicId]);
  return deterministicId || (id ? `radix-${id}` : "");
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-popper/dist/index.mjs
var React26 = __toESM(require_react(), 1);

// node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
var sides = ["top", "right", "bottom", "left"];
var min = Math.min;
var max = Math.max;
var round = Math.round;
var floor = Math.floor;
var createCoords = (v5) => ({
  x: v5,
  y: v5
});
var oppositeSideMap = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
var oppositeAlignmentMap = {
  start: "end",
  end: "start"
};
function clamp(start, value, end) {
  return max(start, min(value, end));
}
function evaluate(value, param) {
  return typeof value === "function" ? value(param) : value;
}
function getSide(placement) {
  return placement.split("-")[0];
}
function getAlignment(placement) {
  return placement.split("-")[1];
}
function getOppositeAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
  return axis === "y" ? "height" : "width";
}
function getSideAxis(placement) {
  return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x";
}
function getAlignmentAxis(placement) {
  return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
  if (rtl === void 0) {
    rtl = false;
  }
  const alignment = getAlignment(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const length = getAxisLength(alignmentAxis);
  let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
  if (rects.reference[length] > rects.floating[length]) {
    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  }
  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
  const oppositePlacement = getOppositePlacement(placement);
  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
  return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
}
function getSideList(side, isStart, rtl) {
  const lr = ["left", "right"];
  const rl = ["right", "left"];
  const tb = ["top", "bottom"];
  const bt = ["bottom", "top"];
  switch (side) {
    case "top":
    case "bottom":
      if (rtl)
        return isStart ? rl : lr;
      return isStart ? lr : rl;
    case "left":
    case "right":
      return isStart ? tb : bt;
    default:
      return [];
  }
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
  const alignment = getAlignment(placement);
  let list = getSideList(getSide(placement), direction === "start", rtl);
  if (alignment) {
    list = list.map((side) => side + "-" + alignment);
    if (flipAlignment) {
      list = list.concat(list.map(getOppositeAlignmentPlacement));
    }
  }
  return list;
}
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
}
function expandPaddingObject(padding) {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...padding
  };
}
function getPaddingObject(padding) {
  return typeof padding !== "number" ? expandPaddingObject(padding) : {
    top: padding,
    right: padding,
    bottom: padding,
    left: padding
  };
}
function rectToClientRect(rect) {
  const {
    x: x2,
    y: y2,
    width,
    height
  } = rect;
  return {
    width,
    height,
    top: y2,
    left: x2,
    right: x2 + width,
    bottom: y2 + height,
    x: x2,
    y: y2
  };
}

// node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
  let {
    reference,
    floating
  } = _ref;
  const sideAxis = getSideAxis(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const alignLength = getAxisLength(alignmentAxis);
  const side = getSide(placement);
  const isVertical = sideAxis === "y";
  const commonX = reference.x + reference.width / 2 - floating.width / 2;
  const commonY = reference.y + reference.height / 2 - floating.height / 2;
  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  let coords;
  switch (side) {
    case "top":
      coords = {
        x: commonX,
        y: reference.y - floating.height
      };
      break;
    case "bottom":
      coords = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case "right":
      coords = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case "left":
      coords = {
        x: reference.x - floating.width,
        y: commonY
      };
      break;
    default:
      coords = {
        x: reference.x,
        y: reference.y
      };
  }
  switch (getAlignment(placement)) {
    case "start":
      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
      break;
    case "end":
      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
      break;
  }
  return coords;
}
var computePosition = async (reference, floating, config) => {
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2
  } = config;
  const validMiddleware = middleware.filter(Boolean);
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
  let rects = await platform2.getElementRects({
    reference,
    floating,
    strategy
  });
  let {
    x: x2,
    y: y2
  } = computeCoordsFromPlacement(rects, placement, rtl);
  let statefulPlacement = placement;
  let middlewareData = {};
  let resetCount = 0;
  for (let i3 = 0; i3 < validMiddleware.length; i3++) {
    const {
      name,
      fn
    } = validMiddleware[i3];
    const {
      x: nextX,
      y: nextY,
      data,
      reset
    } = await fn({
      x: x2,
      y: y2,
      initialPlacement: placement,
      placement: statefulPlacement,
      strategy,
      middlewareData,
      rects,
      platform: platform2,
      elements: {
        reference,
        floating
      }
    });
    x2 = nextX != null ? nextX : x2;
    y2 = nextY != null ? nextY : y2;
    middlewareData = {
      ...middlewareData,
      [name]: {
        ...middlewareData[name],
        ...data
      }
    };
    if (reset && resetCount <= 50) {
      resetCount++;
      if (typeof reset === "object") {
        if (reset.placement) {
          statefulPlacement = reset.placement;
        }
        if (reset.rects) {
          rects = reset.rects === true ? await platform2.getElementRects({
            reference,
            floating,
            strategy
          }) : reset.rects;
        }
        ({
          x: x2,
          y: y2
        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
      }
      i3 = -1;
    }
  }
  return {
    x: x2,
    y: y2,
    placement: statefulPlacement,
    strategy,
    middlewareData
  };
};
async function detectOverflow(state, options) {
  var _await$platform$isEle;
  if (options === void 0) {
    options = {};
  }
  const {
    x: x2,
    y: y2,
    platform: platform2,
    rects,
    elements,
    strategy
  } = state;
  const {
    boundary = "clippingAncestors",
    rootBoundary = "viewport",
    elementContext = "floating",
    altBoundary = false,
    padding = 0
  } = evaluate(options, state);
  const paddingObject = getPaddingObject(padding);
  const altContext = elementContext === "floating" ? "reference" : "floating";
  const element = elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
    element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
    boundary,
    rootBoundary,
    strategy
  }));
  const rect = elementContext === "floating" ? {
    x: x2,
    y: y2,
    width: rects.floating.width,
    height: rects.floating.height
  } : rects.reference;
  const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
  const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
    x: 1,
    y: 1
  } : {
    x: 1,
    y: 1
  };
  const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
    elements,
    rect,
    offsetParent,
    strategy
  }) : rect);
  return {
    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  };
}
var arrow = (options) => ({
  name: "arrow",
  options,
  async fn(state) {
    const {
      x: x2,
      y: y2,
      placement,
      rects,
      platform: platform2,
      elements,
      middlewareData
    } = state;
    const {
      element,
      padding = 0
    } = evaluate(options, state) || {};
    if (element == null) {
      return {};
    }
    const paddingObject = getPaddingObject(padding);
    const coords = {
      x: x2,
      y: y2
    };
    const axis = getAlignmentAxis(placement);
    const length = getAxisLength(axis);
    const arrowDimensions = await platform2.getDimensions(element);
    const isYAxis = axis === "y";
    const minProp = isYAxis ? "top" : "left";
    const maxProp = isYAxis ? "bottom" : "right";
    const clientProp = isYAxis ? "clientHeight" : "clientWidth";
    const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
    const startDiff = coords[axis] - rects.reference[axis];
    const arrowOffsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(element));
    let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
    if (!clientSize || !await (platform2.isElement == null ? void 0 : platform2.isElement(arrowOffsetParent))) {
      clientSize = elements.floating[clientProp] || rects.floating[length];
    }
    const centerToReference = endDiff / 2 - startDiff / 2;
    const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
    const minPadding = min(paddingObject[minProp], largestPossiblePadding);
    const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);
    const min$1 = minPadding;
    const max2 = clientSize - arrowDimensions[length] - maxPadding;
    const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
    const offset5 = clamp(min$1, center, max2);
    const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset5 && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
    const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max2 : 0;
    return {
      [axis]: coords[axis] + alignmentOffset,
      data: {
        [axis]: offset5,
        centerOffset: center - offset5 - alignmentOffset,
        ...shouldAddOffset && {
          alignmentOffset
        }
      },
      reset: shouldAddOffset
    };
  }
});
var flip = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "flip",
    options,
    async fn(state) {
      var _middlewareData$arrow, _middlewareData$flip;
      const {
        placement,
        middlewareData,
        rects,
        initialPlacement,
        platform: platform2,
        elements
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true,
        fallbackPlacements: specifiedFallbackPlacements,
        fallbackStrategy = "bestFit",
        fallbackAxisSideDirection = "none",
        flipAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options, state);
      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      const side = getSide(placement);
      const initialSideAxis = getSideAxis(initialPlacement);
      const isBasePlacement = getSide(initialPlacement) === initialPlacement;
      const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
      const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
      if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
      }
      const placements2 = [initialPlacement, ...fallbackPlacements];
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const overflows = [];
      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
      if (checkMainAxis) {
        overflows.push(overflow[side]);
      }
      if (checkCrossAxis) {
        const sides2 = getAlignmentSides(placement, rects, rtl);
        overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
      }
      overflowsData = [...overflowsData, {
        placement,
        overflows
      }];
      if (!overflows.every((side2) => side2 <= 0)) {
        var _middlewareData$flip2, _overflowsData$filter;
        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
        const nextPlacement = placements2[nextIndex];
        if (nextPlacement) {
          return {
            data: {
              index: nextIndex,
              overflows: overflowsData
            },
            reset: {
              placement: nextPlacement
            }
          };
        }
        let resetPlacement = (_overflowsData$filter = overflowsData.filter((d3) => d3.overflows[0] <= 0).sort((a3, b3) => a3.overflows[1] - b3.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
        if (!resetPlacement) {
          switch (fallbackStrategy) {
            case "bestFit": {
              var _overflowsData$filter2;
              const placement2 = (_overflowsData$filter2 = overflowsData.filter((d3) => {
                if (hasFallbackAxisSideDirection) {
                  const currentSideAxis = getSideAxis(d3.placement);
                  return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
                  // reading directions favoring greater width.
                  currentSideAxis === "y";
                }
                return true;
              }).map((d3) => [d3.placement, d3.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a3, b3) => a3[1] - b3[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
              if (placement2) {
                resetPlacement = placement2;
              }
              break;
            }
            case "initialPlacement":
              resetPlacement = initialPlacement;
              break;
          }
        }
        if (placement !== resetPlacement) {
          return {
            reset: {
              placement: resetPlacement
            }
          };
        }
      }
      return {};
    }
  };
};
function getSideOffsets(overflow, rect) {
  return {
    top: overflow.top - rect.height,
    right: overflow.right - rect.width,
    bottom: overflow.bottom - rect.height,
    left: overflow.left - rect.width
  };
}
function isAnySideFullyClipped(overflow) {
  return sides.some((side) => overflow[side] >= 0);
}
var hide = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "hide",
    options,
    async fn(state) {
      const {
        rects
      } = state;
      const {
        strategy = "referenceHidden",
        ...detectOverflowOptions
      } = evaluate(options, state);
      switch (strategy) {
        case "referenceHidden": {
          const overflow = await detectOverflow(state, {
            ...detectOverflowOptions,
            elementContext: "reference"
          });
          const offsets = getSideOffsets(overflow, rects.reference);
          return {
            data: {
              referenceHiddenOffsets: offsets,
              referenceHidden: isAnySideFullyClipped(offsets)
            }
          };
        }
        case "escaped": {
          const overflow = await detectOverflow(state, {
            ...detectOverflowOptions,
            altBoundary: true
          });
          const offsets = getSideOffsets(overflow, rects.floating);
          return {
            data: {
              escapedOffsets: offsets,
              escaped: isAnySideFullyClipped(offsets)
            }
          };
        }
        default: {
          return {};
        }
      }
    }
  };
};
async function convertValueToCoords(state, options) {
  const {
    placement,
    platform: platform2,
    elements
  } = state;
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
  const side = getSide(placement);
  const alignment = getAlignment(placement);
  const isVertical = getSideAxis(placement) === "y";
  const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1;
  const crossAxisMulti = rtl && isVertical ? -1 : 1;
  const rawValue2 = evaluate(options, state);
  let {
    mainAxis,
    crossAxis,
    alignmentAxis
  } = typeof rawValue2 === "number" ? {
    mainAxis: rawValue2,
    crossAxis: 0,
    alignmentAxis: null
  } : {
    mainAxis: rawValue2.mainAxis || 0,
    crossAxis: rawValue2.crossAxis || 0,
    alignmentAxis: rawValue2.alignmentAxis
  };
  if (alignment && typeof alignmentAxis === "number") {
    crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
  }
  return isVertical ? {
    x: crossAxis * crossAxisMulti,
    y: mainAxis * mainAxisMulti
  } : {
    x: mainAxis * mainAxisMulti,
    y: crossAxis * crossAxisMulti
  };
}
var offset2 = function(options) {
  if (options === void 0) {
    options = 0;
  }
  return {
    name: "offset",
    options,
    async fn(state) {
      var _middlewareData$offse, _middlewareData$arrow;
      const {
        x: x2,
        y: y2,
        placement,
        middlewareData
      } = state;
      const diffCoords = await convertValueToCoords(state, options);
      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      return {
        x: x2 + diffCoords.x,
        y: y2 + diffCoords.y,
        data: {
          ...diffCoords,
          placement
        }
      };
    }
  };
};
var shift = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "shift",
    options,
    async fn(state) {
      const {
        x: x2,
        y: y2,
        placement
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = false,
        limiter = {
          fn: (_ref) => {
            let {
              x: x3,
              y: y3
            } = _ref;
            return {
              x: x3,
              y: y3
            };
          }
        },
        ...detectOverflowOptions
      } = evaluate(options, state);
      const coords = {
        x: x2,
        y: y2
      };
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const crossAxis = getSideAxis(getSide(placement));
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      if (checkMainAxis) {
        const minSide = mainAxis === "y" ? "top" : "left";
        const maxSide = mainAxis === "y" ? "bottom" : "right";
        const min2 = mainAxisCoord + overflow[minSide];
        const max2 = mainAxisCoord - overflow[maxSide];
        mainAxisCoord = clamp(min2, mainAxisCoord, max2);
      }
      if (checkCrossAxis) {
        const minSide = crossAxis === "y" ? "top" : "left";
        const maxSide = crossAxis === "y" ? "bottom" : "right";
        const min2 = crossAxisCoord + overflow[minSide];
        const max2 = crossAxisCoord - overflow[maxSide];
        crossAxisCoord = clamp(min2, crossAxisCoord, max2);
      }
      const limitedCoords = limiter.fn({
        ...state,
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      });
      return {
        ...limitedCoords,
        data: {
          x: limitedCoords.x - x2,
          y: limitedCoords.y - y2,
          enabled: {
            [mainAxis]: checkMainAxis,
            [crossAxis]: checkCrossAxis
          }
        }
      };
    }
  };
};
var limitShift = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    options,
    fn(state) {
      const {
        x: x2,
        y: y2,
        placement,
        rects,
        middlewareData
      } = state;
      const {
        offset: offset5 = 0,
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true
      } = evaluate(options, state);
      const coords = {
        x: x2,
        y: y2
      };
      const crossAxis = getSideAxis(placement);
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      const rawOffset = evaluate(offset5, state);
      const computedOffset = typeof rawOffset === "number" ? {
        mainAxis: rawOffset,
        crossAxis: 0
      } : {
        mainAxis: 0,
        crossAxis: 0,
        ...rawOffset
      };
      if (checkMainAxis) {
        const len = mainAxis === "y" ? "height" : "width";
        const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
        const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
        if (mainAxisCoord < limitMin) {
          mainAxisCoord = limitMin;
        } else if (mainAxisCoord > limitMax) {
          mainAxisCoord = limitMax;
        }
      }
      if (checkCrossAxis) {
        var _middlewareData$offse, _middlewareData$offse2;
        const len = mainAxis === "y" ? "width" : "height";
        const isOriginSide = ["top", "left"].includes(getSide(placement));
        const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
        const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
        if (crossAxisCoord < limitMin) {
          crossAxisCoord = limitMin;
        } else if (crossAxisCoord > limitMax) {
          crossAxisCoord = limitMax;
        }
      }
      return {
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      };
    }
  };
};
var size = function(options) {
  if (options === void 0) {
    options = {};
  }
  return {
    name: "size",
    options,
    async fn(state) {
      var _state$middlewareData, _state$middlewareData2;
      const {
        placement,
        rects,
        platform: platform2,
        elements
      } = state;
      const {
        apply = () => {
        },
        ...detectOverflowOptions
      } = evaluate(options, state);
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const side = getSide(placement);
      const alignment = getAlignment(placement);
      const isYAxis = getSideAxis(placement) === "y";
      const {
        width,
        height
      } = rects.floating;
      let heightSide;
      let widthSide;
      if (side === "top" || side === "bottom") {
        heightSide = side;
        widthSide = alignment === (await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right";
      } else {
        widthSide = side;
        heightSide = alignment === "end" ? "top" : "bottom";
      }
      const maximumClippingHeight = height - overflow.top - overflow.bottom;
      const maximumClippingWidth = width - overflow.left - overflow.right;
      const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);
      const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);
      const noShift = !state.middlewareData.shift;
      let availableHeight = overflowAvailableHeight;
      let availableWidth = overflowAvailableWidth;
      if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
        availableWidth = maximumClippingWidth;
      }
      if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
        availableHeight = maximumClippingHeight;
      }
      if (noShift && !alignment) {
        const xMin = max(overflow.left, 0);
        const xMax = max(overflow.right, 0);
        const yMin = max(overflow.top, 0);
        const yMax = max(overflow.bottom, 0);
        if (isYAxis) {
          availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
        } else {
          availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
        }
      }
      await apply({
        ...state,
        availableWidth,
        availableHeight
      });
      const nextDimensions = await platform2.getDimensions(elements.floating);
      if (width !== nextDimensions.width || height !== nextDimensions.height) {
        return {
          reset: {
            rects: true
          }
        };
      }
      return {};
    }
  };
};

// node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function hasWindow() {
  return typeof window !== "undefined";
}
function getNodeName(node) {
  if (isNode3(node)) {
    return (node.nodeName || "").toLowerCase();
  }
  return "#document";
}
function getWindow(node) {
  var _node$ownerDocument;
  return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
  var _ref;
  return (_ref = (isNode3(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode3(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
  if (!hasWindow() || typeof ShadowRoot === "undefined") {
    return false;
  }
  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
function isOverflowElement(element) {
  const {
    overflow,
    overflowX,
    overflowY,
    display
  } = getComputedStyle2(element);
  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !["inline", "contents"].includes(display);
}
function isTableElement(element) {
  return ["table", "td", "th"].includes(getNodeName(element));
}
function isTopLayer(element) {
  return [":popover-open", ":modal"].some((selector) => {
    try {
      return element.matches(selector);
    } catch (e3) {
      return false;
    }
  });
}
function isContainingBlock(elementOrCss) {
  const webkit = isWebKit();
  const css = isElement(elementOrCss) ? getComputedStyle2(elementOrCss) : elementOrCss;
  return css.transform !== "none" || css.perspective !== "none" || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || ["transform", "perspective", "filter"].some((value) => (css.willChange || "").includes(value)) || ["paint", "layout", "strict", "content"].some((value) => (css.contain || "").includes(value));
}
function getContainingBlock(element) {
  let currentNode = getParentNode(element);
  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
    if (isContainingBlock(currentNode)) {
      return currentNode;
    } else if (isTopLayer(currentNode)) {
      return null;
    }
    currentNode = getParentNode(currentNode);
  }
  return null;
}
function isWebKit() {
  if (typeof CSS === "undefined" || !CSS.supports)
    return false;
  return CSS.supports("-webkit-backdrop-filter", "none");
}
function isLastTraversableNode(node) {
  return ["html", "body", "#document"].includes(getNodeName(node));
}
function getComputedStyle2(element) {
  return getWindow(element).getComputedStyle(element);
}
function getNodeScroll(element) {
  if (isElement(element)) {
    return {
      scrollLeft: element.scrollLeft,
      scrollTop: element.scrollTop
    };
  }
  return {
    scrollLeft: element.scrollX,
    scrollTop: element.scrollY
  };
}
function getParentNode(node) {
  if (getNodeName(node) === "html") {
    return node;
  }
  const result = (
    // Step into the shadow DOM of the parent of a slotted node.
    node.assignedSlot || // DOM Element detected.
    node.parentNode || // ShadowRoot detected.
    isShadowRoot(node) && node.host || // Fallback.
    getDocumentElement(node)
  );
  return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
  const parentNode = getParentNode(node);
  if (isLastTraversableNode(parentNode)) {
    return node.ownerDocument ? node.ownerDocument.body : node.body;
  }
  if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
    return parentNode;
  }
  return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
  var _node$ownerDocument2;
  if (list === void 0) {
    list = [];
  }
  if (traverseIframes === void 0) {
    traverseIframes = true;
  }
  const scrollableAncestor = getNearestOverflowAncestor(node);
  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
  const win = getWindow(scrollableAncestor);
  if (isBody) {
    const frameElement = getFrameElement(win);
    return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
  }
  return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
function getFrameElement(win) {
  return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}

// node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element) {
  const css = getComputedStyle2(element);
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element);
  const offsetWidth = hasOffset ? element.offsetWidth : width;
  const offsetHeight = hasOffset ? element.offsetHeight : height;
  const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }
  return {
    width,
    height,
    $: shouldFallback
  };
}
function unwrapElement(element) {
  return !isElement(element) ? element.contextElement : element;
}
function getScale(element) {
  const domElement = unwrapElement(element);
  if (!isHTMLElement(domElement)) {
    return createCoords(1);
  }
  const rect = domElement.getBoundingClientRect();
  const {
    width,
    height,
    $
  } = getCssDimensions(domElement);
  let x2 = ($ ? round(rect.width) : rect.width) / width;
  let y2 = ($ ? round(rect.height) : rect.height) / height;
  if (!x2 || !Number.isFinite(x2)) {
    x2 = 1;
  }
  if (!y2 || !Number.isFinite(y2)) {
    y2 = 1;
  }
  return {
    x: x2,
    y: y2
  };
}
var noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element) {
  const win = getWindow(element);
  if (!isWebKit() || !win.visualViewport) {
    return noOffsets;
  }
  return {
    x: win.visualViewport.offsetLeft,
    y: win.visualViewport.offsetTop
  };
}
function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
    return false;
  }
  return isFixed;
}
function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  const clientRect = element.getBoundingClientRect();
  const domElement = unwrapElement(element);
  let scale = createCoords(1);
  if (includeScale) {
    if (offsetParent) {
      if (isElement(offsetParent)) {
        scale = getScale(offsetParent);
      }
    } else {
      scale = getScale(element);
    }
  }
  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  let x2 = (clientRect.left + visualOffsets.x) / scale.x;
  let y2 = (clientRect.top + visualOffsets.y) / scale.y;
  let width = clientRect.width / scale.x;
  let height = clientRect.height / scale.y;
  if (domElement) {
    const win = getWindow(domElement);
    const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
    let currentWin = win;
    let currentIFrame = getFrameElement(currentWin);
    while (currentIFrame && offsetParent && offsetWin !== currentWin) {
      const iframeScale = getScale(currentIFrame);
      const iframeRect = currentIFrame.getBoundingClientRect();
      const css = getComputedStyle2(currentIFrame);
      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
      x2 *= iframeScale.x;
      y2 *= iframeScale.y;
      width *= iframeScale.x;
      height *= iframeScale.y;
      x2 += left;
      y2 += top;
      currentWin = getWindow(currentIFrame);
      currentIFrame = getFrameElement(currentWin);
    }
  }
  return rectToClientRect({
    width,
    height,
    x: x2,
    y: y2
  });
}
function getWindowScrollBarX(element, rect) {
  const leftScroll = getNodeScroll(element).scrollLeft;
  if (!rect) {
    return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
  }
  return rect.left + leftScroll;
}
function getHTMLOffset(documentElement, scroll, ignoreScrollbarX) {
  if (ignoreScrollbarX === void 0) {
    ignoreScrollbarX = false;
  }
  const htmlRect = documentElement.getBoundingClientRect();
  const x2 = htmlRect.left + scroll.scrollLeft - (ignoreScrollbarX ? 0 : (
    // RTL <body> scrollbar.
    getWindowScrollBarX(documentElement, htmlRect)
  ));
  const y2 = htmlRect.top + scroll.scrollTop;
  return {
    x: x2,
    y: y2
  };
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  let {
    elements,
    rect,
    offsetParent,
    strategy
  } = _ref;
  const isFixed = strategy === "fixed";
  const documentElement = getDocumentElement(offsetParent);
  const topLayer = elements ? isTopLayer(elements.floating) : false;
  if (offsetParent === documentElement || topLayer && isFixed) {
    return rect;
  }
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  let scale = createCoords(1);
  const offsets = createCoords(0);
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      const offsetRect = getBoundingClientRect(offsetParent);
      scale = getScale(offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    }
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll, true) : createCoords(0);
  return {
    width: rect.width * scale.x,
    height: rect.height * scale.y,
    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
  };
}
function getClientRects(element) {
  return Array.from(element.getClientRects());
}
function getDocumentRect(element) {
  const html = getDocumentElement(element);
  const scroll = getNodeScroll(element);
  const body = element.ownerDocument.body;
  const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
  const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
  let x2 = -scroll.scrollLeft + getWindowScrollBarX(element);
  const y2 = -scroll.scrollTop;
  if (getComputedStyle2(body).direction === "rtl") {
    x2 += max(html.clientWidth, body.clientWidth) - width;
  }
  return {
    width,
    height,
    x: x2,
    y: y2
  };
}
function getViewportRect(element, strategy) {
  const win = getWindow(element);
  const html = getDocumentElement(element);
  const visualViewport = win.visualViewport;
  let width = html.clientWidth;
  let height = html.clientHeight;
  let x2 = 0;
  let y2 = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    const visualViewportBased = isWebKit();
    if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
      x2 = visualViewport.offsetLeft;
      y2 = visualViewport.offsetTop;
    }
  }
  return {
    width,
    height,
    x: x2,
    y: y2
  };
}
function getInnerBoundingClientRect(element, strategy) {
  const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
  const top = clientRect.top + element.clientTop;
  const left = clientRect.left + element.clientLeft;
  const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
  const width = element.clientWidth * scale.x;
  const height = element.clientHeight * scale.y;
  const x2 = left * scale.x;
  const y2 = top * scale.y;
  return {
    width,
    height,
    x: x2,
    y: y2
  };
}
function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
  let rect;
  if (clippingAncestor === "viewport") {
    rect = getViewportRect(element, strategy);
  } else if (clippingAncestor === "document") {
    rect = getDocumentRect(getDocumentElement(element));
  } else if (isElement(clippingAncestor)) {
    rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  } else {
    const visualOffsets = getVisualOffsets(element);
    rect = {
      x: clippingAncestor.x - visualOffsets.x,
      y: clippingAncestor.y - visualOffsets.y,
      width: clippingAncestor.width,
      height: clippingAncestor.height
    };
  }
  return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element, stopNode) {
  const parentNode = getParentNode(element);
  if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
    return false;
  }
  return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
function getClippingElementAncestors(element, cache2) {
  const cachedResult = cache2.get(element);
  if (cachedResult) {
    return cachedResult;
  }
  let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
  let currentContainingBlockComputedStyle = null;
  const elementIsFixed = getComputedStyle2(element).position === "fixed";
  let currentNode = elementIsFixed ? getParentNode(element) : element;
  while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
    const computedStyle = getComputedStyle2(currentNode);
    const currentNodeIsContaining = isContainingBlock(currentNode);
    if (!currentNodeIsContaining && computedStyle.position === "fixed") {
      currentContainingBlockComputedStyle = null;
    }
    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && ["absolute", "fixed"].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
    if (shouldDropCurrentNode) {
      result = result.filter((ancestor) => ancestor !== currentNode);
    } else {
      currentContainingBlockComputedStyle = computedStyle;
    }
    currentNode = getParentNode(currentNode);
  }
  cache2.set(element, result);
  return result;
}
function getClippingRect(_ref) {
  let {
    element,
    boundary,
    rootBoundary,
    strategy
  } = _ref;
  const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
  const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  const firstClippingAncestor = clippingAncestors[0];
  const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
    const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
  return {
    width: clippingRect.right - clippingRect.left,
    height: clippingRect.bottom - clippingRect.top,
    x: clippingRect.left,
    y: clippingRect.top
  };
}
function getDimensions(element) {
  const {
    width,
    height
  } = getCssDimensions(element);
  return {
    width,
    height
  };
}
function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  const isFixed = strategy === "fixed";
  const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  const offsets = createCoords(0);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  const x2 = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
  const y2 = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
  return {
    x: x2,
    y: y2,
    width: rect.width,
    height: rect.height
  };
}
function isStaticPositioned(element) {
  return getComputedStyle2(element).position === "static";
}
function getTrueOffsetParent(element, polyfill) {
  if (!isHTMLElement(element) || getComputedStyle2(element).position === "fixed") {
    return null;
  }
  if (polyfill) {
    return polyfill(element);
  }
  let rawOffsetParent = element.offsetParent;
  if (getDocumentElement(element) === rawOffsetParent) {
    rawOffsetParent = rawOffsetParent.ownerDocument.body;
  }
  return rawOffsetParent;
}
function getOffsetParent(element, polyfill) {
  const win = getWindow(element);
  if (isTopLayer(element)) {
    return win;
  }
  if (!isHTMLElement(element)) {
    let svgOffsetParent = getParentNode(element);
    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
      if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
        return svgOffsetParent;
      }
      svgOffsetParent = getParentNode(svgOffsetParent);
    }
    return win;
  }
  let offsetParent = getTrueOffsetParent(element, polyfill);
  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
    offsetParent = getTrueOffsetParent(offsetParent, polyfill);
  }
  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
    return win;
  }
  return offsetParent || getContainingBlock(element) || win;
}
var getElementRects = async function(data) {
  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  const getDimensionsFn = this.getDimensions;
  const floatingDimensions = await getDimensionsFn(data.floating);
  return {
    reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
    floating: {
      x: 0,
      y: 0,
      width: floatingDimensions.width,
      height: floatingDimensions.height
    }
  };
};
function isRTL(element) {
  return getComputedStyle2(element).direction === "rtl";
}
var platform = {
  convertOffsetParentRelativeRectToViewportRelativeRect,
  getDocumentElement,
  getClippingRect,
  getOffsetParent,
  getElementRects,
  getClientRects,
  getDimensions,
  getScale,
  isElement,
  isRTL
};
function observeMove(element, onMove) {
  let io = null;
  let timeoutId;
  const root2 = getDocumentElement(element);
  function cleanup() {
    var _io;
    clearTimeout(timeoutId);
    (_io = io) == null || _io.disconnect();
    io = null;
  }
  function refresh(skip, threshold) {
    if (skip === void 0) {
      skip = false;
    }
    if (threshold === void 0) {
      threshold = 1;
    }
    cleanup();
    const {
      left,
      top,
      width,
      height
    } = element.getBoundingClientRect();
    if (!skip) {
      onMove();
    }
    if (!width || !height) {
      return;
    }
    const insetTop = floor(top);
    const insetRight = floor(root2.clientWidth - (left + width));
    const insetBottom = floor(root2.clientHeight - (top + height));
    const insetLeft = floor(left);
    const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
    const options = {
      rootMargin,
      threshold: max(0, min(1, threshold)) || 1
    };
    let isFirstUpdate = true;
    function handleObserve(entries) {
      const ratio = entries[0].intersectionRatio;
      if (ratio !== threshold) {
        if (!isFirstUpdate) {
          return refresh();
        }
        if (!ratio) {
          timeoutId = setTimeout(() => {
            refresh(false, 1e-7);
          }, 1e3);
        } else {
          refresh(false, ratio);
        }
      }
      isFirstUpdate = false;
    }
    try {
      io = new IntersectionObserver(handleObserve, {
        ...options,
        // Handle <iframe>s
        root: root2.ownerDocument
      });
    } catch (e3) {
      io = new IntersectionObserver(handleObserve, options);
    }
    io.observe(element);
  }
  refresh(true);
  return cleanup;
}
function autoUpdate(reference, floating, update2, options) {
  if (options === void 0) {
    options = {};
  }
  const {
    ancestorScroll = true,
    ancestorResize = true,
    elementResize = typeof ResizeObserver === "function",
    layoutShift = typeof IntersectionObserver === "function",
    animationFrame = false
  } = options;
  const referenceEl = unwrapElement(reference);
  const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...getOverflowAncestors(floating)] : [];
  ancestors.forEach((ancestor) => {
    ancestorScroll && ancestor.addEventListener("scroll", update2, {
      passive: true
    });
    ancestorResize && ancestor.addEventListener("resize", update2);
  });
  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update2) : null;
  let reobserveFrame = -1;
  let resizeObserver = null;
  if (elementResize) {
    resizeObserver = new ResizeObserver((_ref) => {
      let [firstEntry] = _ref;
      if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
        resizeObserver.unobserve(floating);
        cancelAnimationFrame(reobserveFrame);
        reobserveFrame = requestAnimationFrame(() => {
          var _resizeObserver;
          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
        });
      }
      update2();
    });
    if (referenceEl && !animationFrame) {
      resizeObserver.observe(referenceEl);
    }
    resizeObserver.observe(floating);
  }
  let frameId;
  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  if (animationFrame) {
    frameLoop();
  }
  function frameLoop() {
    const nextRefRect = getBoundingClientRect(reference);
    if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
      update2();
    }
    prevRefRect = nextRefRect;
    frameId = requestAnimationFrame(frameLoop);
  }
  update2();
  return () => {
    var _resizeObserver2;
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.removeEventListener("scroll", update2);
      ancestorResize && ancestor.removeEventListener("resize", update2);
    });
    cleanupIo == null || cleanupIo();
    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
    resizeObserver = null;
    if (animationFrame) {
      cancelAnimationFrame(frameId);
    }
  };
}
var offset3 = offset2;
var shift2 = shift;
var flip2 = flip;
var size2 = size;
var hide2 = hide;
var arrow2 = arrow;
var limitShift2 = limitShift;
var computePosition2 = (reference, floating, options) => {
  const cache2 = /* @__PURE__ */ new Map();
  const mergedOptions = {
    platform,
    ...options
  };
  const platformWithCache = {
    ...mergedOptions.platform,
    _c: cache2
  };
  return computePosition(reference, floating, {
    ...mergedOptions,
    platform: platformWithCache
  });
};

// node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs
var React23 = __toESM(require_react(), 1);
var import_react7 = __toESM(require_react(), 1);
var ReactDOM3 = __toESM(require_react_dom(), 1);
var index = typeof document !== "undefined" ? import_react7.useLayoutEffect : import_react7.useEffect;
function deepEqual(a3, b3) {
  if (a3 === b3) {
    return true;
  }
  if (typeof a3 !== typeof b3) {
    return false;
  }
  if (typeof a3 === "function" && a3.toString() === b3.toString()) {
    return true;
  }
  let length;
  let i3;
  let keys;
  if (a3 && b3 && typeof a3 === "object") {
    if (Array.isArray(a3)) {
      length = a3.length;
      if (length !== b3.length)
        return false;
      for (i3 = length; i3-- !== 0; ) {
        if (!deepEqual(a3[i3], b3[i3])) {
          return false;
        }
      }
      return true;
    }
    keys = Object.keys(a3);
    length = keys.length;
    if (length !== Object.keys(b3).length) {
      return false;
    }
    for (i3 = length; i3-- !== 0; ) {
      if (!{}.hasOwnProperty.call(b3, keys[i3])) {
        return false;
      }
    }
    for (i3 = length; i3-- !== 0; ) {
      const key = keys[i3];
      if (key === "_owner" && a3.$$typeof) {
        continue;
      }
      if (!deepEqual(a3[key], b3[key])) {
        return false;
      }
    }
    return true;
  }
  return a3 !== a3 && b3 !== b3;
}
function getDPR(element) {
  if (typeof window === "undefined") {
    return 1;
  }
  const win = element.ownerDocument.defaultView || window;
  return win.devicePixelRatio || 1;
}
function roundByDPR(element, value) {
  const dpr = getDPR(element);
  return Math.round(value * dpr) / dpr;
}
function useLatestRef(value) {
  const ref = React23.useRef(value);
  index(() => {
    ref.current = value;
  });
  return ref;
}
function useFloating(options) {
  if (options === void 0) {
    options = {};
  }
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2,
    elements: {
      reference: externalReference,
      floating: externalFloating
    } = {},
    transform = true,
    whileElementsMounted,
    open
  } = options;
  const [data, setData] = React23.useState({
    x: 0,
    y: 0,
    strategy,
    placement,
    middlewareData: {},
    isPositioned: false
  });
  const [latestMiddleware, setLatestMiddleware] = React23.useState(middleware);
  if (!deepEqual(latestMiddleware, middleware)) {
    setLatestMiddleware(middleware);
  }
  const [_reference, _setReference] = React23.useState(null);
  const [_floating, _setFloating] = React23.useState(null);
  const setReference = React23.useCallback((node) => {
    if (node !== referenceRef.current) {
      referenceRef.current = node;
      _setReference(node);
    }
  }, []);
  const setFloating = React23.useCallback((node) => {
    if (node !== floatingRef.current) {
      floatingRef.current = node;
      _setFloating(node);
    }
  }, []);
  const referenceEl = externalReference || _reference;
  const floatingEl = externalFloating || _floating;
  const referenceRef = React23.useRef(null);
  const floatingRef = React23.useRef(null);
  const dataRef = React23.useRef(data);
  const hasWhileElementsMounted = whileElementsMounted != null;
  const whileElementsMountedRef = useLatestRef(whileElementsMounted);
  const platformRef = useLatestRef(platform2);
  const openRef = useLatestRef(open);
  const update2 = React23.useCallback(() => {
    if (!referenceRef.current || !floatingRef.current) {
      return;
    }
    const config = {
      placement,
      strategy,
      middleware: latestMiddleware
    };
    if (platformRef.current) {
      config.platform = platformRef.current;
    }
    computePosition2(referenceRef.current, floatingRef.current, config).then((data2) => {
      const fullData = {
        ...data2,
        // The floating element's position may be recomputed while it's closed
        // but still mounted (such as when transitioning out). To ensure
        // `isPositioned` will be `false` initially on the next open, avoid
        // setting it to `true` when `open === false` (must be specified).
        isPositioned: openRef.current !== false
      };
      if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
        dataRef.current = fullData;
        ReactDOM3.flushSync(() => {
          setData(fullData);
        });
      }
    });
  }, [latestMiddleware, placement, strategy, platformRef, openRef]);
  index(() => {
    if (open === false && dataRef.current.isPositioned) {
      dataRef.current.isPositioned = false;
      setData((data2) => ({
        ...data2,
        isPositioned: false
      }));
    }
  }, [open]);
  const isMountedRef = React23.useRef(false);
  index(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  index(() => {
    if (referenceEl)
      referenceRef.current = referenceEl;
    if (floatingEl)
      floatingRef.current = floatingEl;
    if (referenceEl && floatingEl) {
      if (whileElementsMountedRef.current) {
        return whileElementsMountedRef.current(referenceEl, floatingEl, update2);
      }
      update2();
    }
  }, [referenceEl, floatingEl, update2, whileElementsMountedRef, hasWhileElementsMounted]);
  const refs = React23.useMemo(() => ({
    reference: referenceRef,
    floating: floatingRef,
    setReference,
    setFloating
  }), [setReference, setFloating]);
  const elements = React23.useMemo(() => ({
    reference: referenceEl,
    floating: floatingEl
  }), [referenceEl, floatingEl]);
  const floatingStyles = React23.useMemo(() => {
    const initialStyles = {
      position: strategy,
      left: 0,
      top: 0
    };
    if (!elements.floating) {
      return initialStyles;
    }
    const x2 = roundByDPR(elements.floating, data.x);
    const y2 = roundByDPR(elements.floating, data.y);
    if (transform) {
      return {
        ...initialStyles,
        transform: "translate(" + x2 + "px, " + y2 + "px)",
        ...getDPR(elements.floating) >= 1.5 && {
          willChange: "transform"
        }
      };
    }
    return {
      position: strategy,
      left: x2,
      top: y2
    };
  }, [strategy, transform, elements.floating, data.x, data.y]);
  return React23.useMemo(() => ({
    ...data,
    update: update2,
    refs,
    elements,
    floatingStyles
  }), [data, update2, refs, elements, floatingStyles]);
}
var arrow$1 = (options) => {
  function isRef(value) {
    return {}.hasOwnProperty.call(value, "current");
  }
  return {
    name: "arrow",
    options,
    fn(state) {
      const {
        element,
        padding
      } = typeof options === "function" ? options(state) : options;
      if (element && isRef(element)) {
        if (element.current != null) {
          return arrow2({
            element: element.current,
            padding
          }).fn(state);
        }
        return {};
      }
      if (element) {
        return arrow2({
          element,
          padding
        }).fn(state);
      }
      return {};
    }
  };
};
var offset4 = (options, deps) => ({
  ...offset3(options),
  options: [options, deps]
});
var shift3 = (options, deps) => ({
  ...shift2(options),
  options: [options, deps]
});
var limitShift3 = (options, deps) => ({
  ...limitShift2(options),
  options: [options, deps]
});
var flip3 = (options, deps) => ({
  ...flip2(options),
  options: [options, deps]
});
var size3 = (options, deps) => ({
  ...size2(options),
  options: [options, deps]
});
var hide3 = (options, deps) => ({
  ...hide2(options),
  options: [options, deps]
});
var arrow3 = (options, deps) => ({
  ...arrow$1(options),
  options: [options, deps]
});

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-arrow/dist/index.mjs
var React24 = __toESM(require_react(), 1);
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
var NAME = "Arrow";
var Arrow = React24.forwardRef((props, forwardedRef) => {
  const { children, width = 10, height = 5, ...arrowProps } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
    Primitive2.svg,
    {
      ...arrowProps,
      ref: forwardedRef,
      width,
      height,
      viewBox: "0 0 30 10",
      preserveAspectRatio: "none",
      children: props.asChild ? children : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("polygon", { points: "0,0 30,0 15,10" })
    }
  );
});
Arrow.displayName = NAME;
var Root2 = Arrow;

// node_modules/@radix-ui/react-use-size/dist/index.mjs
var React25 = __toESM(require_react(), 1);
function useSize(element) {
  const [size4, setSize] = React25.useState(void 0);
  useLayoutEffect2(() => {
    if (element) {
      setSize({ width: element.offsetWidth, height: element.offsetHeight });
      const resizeObserver = new ResizeObserver((entries) => {
        if (!Array.isArray(entries)) {
          return;
        }
        if (!entries.length) {
          return;
        }
        const entry = entries[0];
        let width;
        let height;
        if ("borderBoxSize" in entry) {
          const borderSizeEntry = entry["borderBoxSize"];
          const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;
          width = borderSize["inlineSize"];
          height = borderSize["blockSize"];
        } else {
          width = element.offsetWidth;
          height = element.offsetHeight;
        }
        setSize({ width, height });
      });
      resizeObserver.observe(element, { box: "border-box" });
      return () => resizeObserver.unobserve(element);
    } else {
      setSize(void 0);
    }
  }, [element]);
  return size4;
}

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-popper/dist/index.mjs
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
"use client";
var POPPER_NAME = "Popper";
var [createPopperContext, createPopperScope] = createContextScope(POPPER_NAME);
var [PopperProvider, usePopperContext] = createPopperContext(POPPER_NAME);
var Popper = (props) => {
  const { __scopePopper, children } = props;
  const [anchor, setAnchor] = React26.useState(null);
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(PopperProvider, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });
};
Popper.displayName = POPPER_NAME;
var ANCHOR_NAME = "PopperAnchor";
var PopperAnchor = React26.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopper, virtualRef, ...anchorProps } = props;
    const context = usePopperContext(ANCHOR_NAME, __scopePopper);
    const ref = React26.useRef(null);
    const composedRefs = useComposedRefs2(forwardedRef, ref);
    React26.useEffect(() => {
      context.onAnchorChange(virtualRef?.current || ref.current);
    });
    return virtualRef ? null : /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Primitive2.div, { ...anchorProps, ref: composedRefs });
  }
);
PopperAnchor.displayName = ANCHOR_NAME;
var CONTENT_NAME = "PopperContent";
var [PopperContentProvider, useContentContext] = createPopperContext(CONTENT_NAME);
var PopperContent = React26.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopper,
      side = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      arrowPadding = 0,
      avoidCollisions = true,
      collisionBoundary = [],
      collisionPadding: collisionPaddingProp = 0,
      sticky = "partial",
      hideWhenDetached = false,
      updatePositionStrategy = "optimized",
      onPlaced,
      ...contentProps
    } = props;
    const context = usePopperContext(CONTENT_NAME, __scopePopper);
    const [content, setContent] = React26.useState(null);
    const composedRefs = useComposedRefs2(forwardedRef, (node) => setContent(node));
    const [arrow4, setArrow] = React26.useState(null);
    const arrowSize = useSize(arrow4);
    const arrowWidth = arrowSize?.width ?? 0;
    const arrowHeight = arrowSize?.height ?? 0;
    const desiredPlacement = side + (align !== "center" ? "-" + align : "");
    const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };
    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];
    const hasExplicitBoundaries = boundary.length > 0;
    const detectOverflowOptions = {
      padding: collisionPadding,
      boundary: boundary.filter(isNotNull),
      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
      altBoundary: hasExplicitBoundaries
    };
    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({
      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
      strategy: "fixed",
      placement: desiredPlacement,
      whileElementsMounted: (...args) => {
        const cleanup = autoUpdate(...args, {
          animationFrame: updatePositionStrategy === "always"
        });
        return cleanup;
      },
      elements: {
        reference: context.anchor
      },
      middleware: [
        offset4({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),
        avoidCollisions && shift3({
          mainAxis: true,
          crossAxis: false,
          limiter: sticky === "partial" ? limitShift3() : void 0,
          ...detectOverflowOptions
        }),
        avoidCollisions && flip3({ ...detectOverflowOptions }),
        size3({
          ...detectOverflowOptions,
          apply: ({ elements, rects, availableWidth, availableHeight }) => {
            const { width: anchorWidth, height: anchorHeight } = rects.reference;
            const contentStyle = elements.floating.style;
            contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`);
            contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`);
            contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`);
            contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`);
          }
        }),
        arrow4 && arrow3({ element: arrow4, padding: arrowPadding }),
        transformOrigin({ arrowWidth, arrowHeight }),
        hideWhenDetached && hide3({ strategy: "referenceHidden", ...detectOverflowOptions })
      ]
    });
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);
    const handlePlaced = useCallbackRef(onPlaced);
    useLayoutEffect2(() => {
      if (isPositioned) {
        handlePlaced?.();
      }
    }, [isPositioned, handlePlaced]);
    const arrowX = middlewareData.arrow?.x;
    const arrowY = middlewareData.arrow?.y;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const [contentZIndex, setContentZIndex] = React26.useState();
    useLayoutEffect2(() => {
      if (content)
        setContentZIndex(window.getComputedStyle(content).zIndex);
    }, [content]);
    return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "div",
      {
        ref: refs.setFloating,
        "data-radix-popper-content-wrapper": "",
        style: {
          ...floatingStyles,
          transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)",
          // keep off the page when measuring
          minWidth: "max-content",
          zIndex: contentZIndex,
          ["--radix-popper-transform-origin"]: [
            middlewareData.transformOrigin?.x,
            middlewareData.transformOrigin?.y
          ].join(" "),
          // hide the content if using the hide middleware and should be hidden
          // set visibility to hidden and disable pointer events so the UI behaves
          // as if the PopperContent isn't there at all
          ...middlewareData.hide?.referenceHidden && {
            visibility: "hidden",
            pointerEvents: "none"
          }
        },
        dir: props.dir,
        children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
          PopperContentProvider,
          {
            scope: __scopePopper,
            placedSide,
            onArrowChange: setArrow,
            arrowX,
            arrowY,
            shouldHideArrow: cannotCenterArrow,
            children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
              Primitive2.div,
              {
                "data-side": placedSide,
                "data-align": placedAlign,
                ...contentProps,
                ref: composedRefs,
                style: {
                  ...contentProps.style,
                  // if the PopperContent hasn't been placed yet (not all measurements done)
                  // we prevent animations so that users's animation don't kick in too early referring wrong sides
                  animation: !isPositioned ? "none" : void 0
                }
              }
            )
          }
        )
      }
    );
  }
);
PopperContent.displayName = CONTENT_NAME;
var ARROW_NAME = "PopperArrow";
var OPPOSITE_SIDE = {
  top: "bottom",
  right: "left",
  bottom: "top",
  left: "right"
};
var PopperArrow = React26.forwardRef(function PopperArrow2(props, forwardedRef) {
  const { __scopePopper, ...arrowProps } = props;
  const contentContext = useContentContext(ARROW_NAME, __scopePopper);
  const baseSide = OPPOSITE_SIDE[contentContext.placedSide];
  return (
    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
    // doesn't report size as we'd expect on SVG elements.
    // it reports their bounding box which is effectively the largest path inside the SVG.
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "span",
      {
        ref: contentContext.onArrowChange,
        style: {
          position: "absolute",
          left: contentContext.arrowX,
          top: contentContext.arrowY,
          [baseSide]: 0,
          transformOrigin: {
            top: "",
            right: "0 0",
            bottom: "center 0",
            left: "100% 0"
          }[contentContext.placedSide],
          transform: {
            top: "translateY(100%)",
            right: "translateY(50%) rotate(90deg) translateX(-50%)",
            bottom: `rotate(180deg)`,
            left: "translateY(50%) rotate(-90deg) translateX(50%)"
          }[contentContext.placedSide],
          visibility: contentContext.shouldHideArrow ? "hidden" : void 0
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
          Root2,
          {
            ...arrowProps,
            ref: forwardedRef,
            style: {
              ...arrowProps.style,
              // ensures the element can be measured correctly (mostly for if SVG)
              display: "block"
            }
          }
        )
      }
    )
  );
});
PopperArrow.displayName = ARROW_NAME;
function isNotNull(value) {
  return value !== null;
}
var transformOrigin = (options) => ({
  name: "transformOrigin",
  options,
  fn(data) {
    const { placement, rects, middlewareData } = data;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const isArrowHidden = cannotCenterArrow;
    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement(placement);
    const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign];
    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;
    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;
    let x2 = "";
    let y2 = "";
    if (placedSide === "bottom") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${-arrowHeight}px`;
    } else if (placedSide === "top") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${rects.floating.height + arrowHeight}px`;
    } else if (placedSide === "right") {
      x2 = `${-arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    } else if (placedSide === "left") {
      x2 = `${rects.floating.width + arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    }
    return { data: { x: x2, y: y2 } };
  }
});
function getSideAndAlignFromPlacement(placement) {
  const [side, align = "center"] = placement.split("-");
  return [side, align];
}
var Root22 = Popper;
var Anchor = PopperAnchor;
var Content = PopperContent;
var Arrow2 = PopperArrow;

// node_modules/@radix-ui/react-menu/node_modules/@radix-ui/react-portal/dist/index.mjs
var React27 = __toESM(require_react(), 1);
var import_react_dom2 = __toESM(require_react_dom(), 1);
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
"use client";
var PORTAL_NAME = "Portal";
var Portal = React27.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = React27.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? import_react_dom2.default.createPortal(/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Primitive2.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal.displayName = PORTAL_NAME;

// node_modules/@radix-ui/react-presence/dist/index.mjs
var React29 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-presence/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React28 = __toESM(require_react(), 1);
function setRef4(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs4(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef4(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef4(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs3(...refs) {
  return React28.useCallback(composeRefs4(...refs), refs);
}

// node_modules/@radix-ui/react-presence/dist/index.mjs
var React30 = __toESM(require_react(), 1);
"use client";
function useStateMachine(initialState2, machine) {
  return React30.useReducer((state, event) => {
    const nextState = machine[state][event];
    return nextState ?? state;
  }, initialState2);
}
var Presence = (props) => {
  const { present, children } = props;
  const presence = usePresence(present);
  const child = typeof children === "function" ? children({ present: presence.isPresent }) : React29.Children.only(children);
  const ref = useComposedRefs3(presence.ref, getElementRef4(child));
  const forceMount = typeof children === "function";
  return forceMount || presence.isPresent ? React29.cloneElement(child, { ref }) : null;
};
Presence.displayName = "Presence";
function usePresence(present) {
  const [node, setNode] = React29.useState();
  const stylesRef = React29.useRef({});
  const prevPresentRef = React29.useRef(present);
  const prevAnimationNameRef = React29.useRef("none");
  const initialState2 = present ? "mounted" : "unmounted";
  const [state, send] = useStateMachine(initialState2, {
    mounted: {
      UNMOUNT: "unmounted",
      ANIMATION_OUT: "unmountSuspended"
    },
    unmountSuspended: {
      MOUNT: "mounted",
      ANIMATION_END: "unmounted"
    },
    unmounted: {
      MOUNT: "mounted"
    }
  });
  React29.useEffect(() => {
    const currentAnimationName = getAnimationName(stylesRef.current);
    prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none";
  }, [state]);
  useLayoutEffect2(() => {
    const styles2 = stylesRef.current;
    const wasPresent = prevPresentRef.current;
    const hasPresentChanged = wasPresent !== present;
    if (hasPresentChanged) {
      const prevAnimationName = prevAnimationNameRef.current;
      const currentAnimationName = getAnimationName(styles2);
      if (present) {
        send("MOUNT");
      } else if (currentAnimationName === "none" || styles2?.display === "none") {
        send("UNMOUNT");
      } else {
        const isAnimating = prevAnimationName !== currentAnimationName;
        if (wasPresent && isAnimating) {
          send("ANIMATION_OUT");
        } else {
          send("UNMOUNT");
        }
      }
      prevPresentRef.current = present;
    }
  }, [present, send]);
  useLayoutEffect2(() => {
    if (node) {
      let timeoutId;
      const ownerWindow = node.ownerDocument.defaultView ?? window;
      const handleAnimationEnd = (event) => {
        const currentAnimationName = getAnimationName(stylesRef.current);
        const isCurrentAnimation = currentAnimationName.includes(event.animationName);
        if (event.target === node && isCurrentAnimation) {
          send("ANIMATION_END");
          if (!prevPresentRef.current) {
            const currentFillMode = node.style.animationFillMode;
            node.style.animationFillMode = "forwards";
            timeoutId = ownerWindow.setTimeout(() => {
              if (node.style.animationFillMode === "forwards") {
                node.style.animationFillMode = currentFillMode;
              }
            });
          }
        }
      };
      const handleAnimationStart = (event) => {
        if (event.target === node) {
          prevAnimationNameRef.current = getAnimationName(stylesRef.current);
        }
      };
      node.addEventListener("animationstart", handleAnimationStart);
      node.addEventListener("animationcancel", handleAnimationEnd);
      node.addEventListener("animationend", handleAnimationEnd);
      return () => {
        ownerWindow.clearTimeout(timeoutId);
        node.removeEventListener("animationstart", handleAnimationStart);
        node.removeEventListener("animationcancel", handleAnimationEnd);
        node.removeEventListener("animationend", handleAnimationEnd);
      };
    } else {
      send("ANIMATION_END");
    }
  }, [node, send]);
  return {
    isPresent: ["mounted", "unmountSuspended"].includes(state),
    ref: React29.useCallback((node2) => {
      if (node2)
        stylesRef.current = getComputedStyle(node2);
      setNode(node2);
    }, [])
  };
}
function getAnimationName(styles2) {
  return styles2?.animationName || "none";
}
function getElementRef4(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-roving-focus/dist/index.mjs
var React35 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers3(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-collection/dist/index.mjs
var import_react8 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React31 = __toESM(require_react(), 1);
function setRef5(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs5(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef5(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef5(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs4(...refs) {
  return React31.useCallback(composeRefs5(...refs), refs);
}

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-slot/dist/index.mjs
var React32 = __toESM(require_react(), 1);
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
var Slot4 = React32.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React32.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable4);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React32.Children.count(newElement) > 1)
          return React32.Children.only(null);
        return React32.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SlotClone4, { ...slotProps, ref: forwardedRef, children: React32.isValidElement(newElement) ? React32.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SlotClone4, { ...slotProps, ref: forwardedRef, children });
});
Slot4.displayName = "Slot";
var SlotClone4 = React32.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React32.isValidElement(children)) {
    const childrenRef = getElementRef5(children);
    return React32.cloneElement(children, {
      ...mergeProps4(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs5(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React32.Children.count(children) > 1 ? React32.Children.only(null) : null;
});
SlotClone4.displayName = "SlotClone";
var Slottable4 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_jsx_runtime14.Fragment, { children });
};
function isSlottable4(child) {
  return React32.isValidElement(child) && child.type === Slottable4;
}
function mergeProps4(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef5(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-collection/dist/index.mjs
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
"use client";
function createCollection2(name) {
  const PROVIDER_NAME2 = name + "CollectionProvider";
  const [createCollectionContext, createCollectionScope5] = createContextScope(PROVIDER_NAME2);
  const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(
    PROVIDER_NAME2,
    { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }
  );
  const CollectionProvider = (props) => {
    const { scope, children } = props;
    const ref = import_react8.default.useRef(null);
    const itemMap = import_react8.default.useRef(/* @__PURE__ */ new Map()).current;
    return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(CollectionProviderImpl, { scope, itemMap, collectionRef: ref, children });
  };
  CollectionProvider.displayName = PROVIDER_NAME2;
  const COLLECTION_SLOT_NAME = name + "CollectionSlot";
  const CollectionSlot = import_react8.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children } = props;
      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
      const composedRefs = useComposedRefs4(forwardedRef, context.collectionRef);
      return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Slot4, { ref: composedRefs, children });
    }
  );
  CollectionSlot.displayName = COLLECTION_SLOT_NAME;
  const ITEM_SLOT_NAME = name + "CollectionItemSlot";
  const ITEM_DATA_ATTR = "data-radix-collection-item";
  const CollectionItemSlot = import_react8.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children, ...itemData } = props;
      const ref = import_react8.default.useRef(null);
      const composedRefs = useComposedRefs4(forwardedRef, ref);
      const context = useCollectionContext(ITEM_SLOT_NAME, scope);
      import_react8.default.useEffect(() => {
        context.itemMap.set(ref, { ref, ...itemData });
        return () => void context.itemMap.delete(ref);
      });
      return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Slot4, { ...{ [ITEM_DATA_ATTR]: "" }, ref: composedRefs, children });
    }
  );
  CollectionItemSlot.displayName = ITEM_SLOT_NAME;
  function useCollection5(scope) {
    const context = useCollectionContext(name + "CollectionConsumer", scope);
    const getItems = import_react8.default.useCallback(() => {
      const collectionNode = context.collectionRef.current;
      if (!collectionNode)
        return [];
      const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
      const items = Array.from(context.itemMap.values());
      const orderedItems = items.sort(
        (a3, b3) => orderedNodes.indexOf(a3.ref.current) - orderedNodes.indexOf(b3.ref.current)
      );
      return orderedItems;
    }, [context.collectionRef, context.itemMap]);
    return getItems;
  }
  return [
    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },
    useCollection5,
    createCollectionScope5
  ];
}

// node_modules/@radix-ui/react-roving-focus/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React34 = __toESM(require_react(), 1);
var ReactDOM5 = __toESM(require_react_dom(), 1);
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var NODES3 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive3 = NODES3.reduce((primitive, node) => {
  const Node3 = React34.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot4 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});

// node_modules/@radix-ui/react-roving-focus/dist/index.mjs
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
"use client";
var ENTRY_FOCUS = "rovingFocusGroup.onEntryFocus";
var EVENT_OPTIONS2 = { bubbles: false, cancelable: true };
var GROUP_NAME = "RovingFocusGroup";
var [Collection, useCollection, createCollectionScope] = createCollection2(GROUP_NAME);
var [createRovingFocusGroupContext, createRovingFocusGroupScope] = createContextScope(
  GROUP_NAME,
  [createCollectionScope]
);
var [RovingFocusProvider, useRovingFocusContext] = createRovingFocusGroupContext(GROUP_NAME);
var RovingFocusGroup = React35.forwardRef(
  (props, forwardedRef) => {
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Collection.Provider, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Collection.Slot, { scope: props.__scopeRovingFocusGroup, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(RovingFocusGroupImpl, { ...props, ref: forwardedRef }) }) });
  }
);
RovingFocusGroup.displayName = GROUP_NAME;
var RovingFocusGroupImpl = React35.forwardRef((props, forwardedRef) => {
  const {
    __scopeRovingFocusGroup,
    orientation,
    loop = false,
    dir,
    currentTabStopId: currentTabStopIdProp,
    defaultCurrentTabStopId,
    onCurrentTabStopIdChange,
    onEntryFocus,
    preventScrollOnEntryFocus = false,
    ...groupProps
  } = props;
  const ref = React35.useRef(null);
  const composedRefs = useComposedRefs4(forwardedRef, ref);
  const direction = useDirection(dir);
  const [currentTabStopId = null, setCurrentTabStopId] = useControllableState({
    prop: currentTabStopIdProp,
    defaultProp: defaultCurrentTabStopId,
    onChange: onCurrentTabStopIdChange
  });
  const [isTabbingBackOut, setIsTabbingBackOut] = React35.useState(false);
  const handleEntryFocus = useCallbackRef(onEntryFocus);
  const getItems = useCollection(__scopeRovingFocusGroup);
  const isClickFocusRef = React35.useRef(false);
  const [focusableItemsCount, setFocusableItemsCount] = React35.useState(0);
  React35.useEffect(() => {
    const node = ref.current;
    if (node) {
      node.addEventListener(ENTRY_FOCUS, handleEntryFocus);
      return () => node.removeEventListener(ENTRY_FOCUS, handleEntryFocus);
    }
  }, [handleEntryFocus]);
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
    RovingFocusProvider,
    {
      scope: __scopeRovingFocusGroup,
      orientation,
      dir: direction,
      loop,
      currentTabStopId,
      onItemFocus: React35.useCallback(
        (tabStopId) => setCurrentTabStopId(tabStopId),
        [setCurrentTabStopId]
      ),
      onItemShiftTab: React35.useCallback(() => setIsTabbingBackOut(true), []),
      onFocusableItemAdd: React35.useCallback(
        () => setFocusableItemsCount((prevCount) => prevCount + 1),
        []
      ),
      onFocusableItemRemove: React35.useCallback(
        () => setFocusableItemsCount((prevCount) => prevCount - 1),
        []
      ),
      children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
        Primitive3.div,
        {
          tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0,
          "data-orientation": orientation,
          ...groupProps,
          ref: composedRefs,
          style: { outline: "none", ...props.style },
          onMouseDown: composeEventHandlers3(props.onMouseDown, () => {
            isClickFocusRef.current = true;
          }),
          onFocus: composeEventHandlers3(props.onFocus, (event) => {
            const isKeyboardFocus = !isClickFocusRef.current;
            if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {
              const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS2);
              event.currentTarget.dispatchEvent(entryFocusEvent);
              if (!entryFocusEvent.defaultPrevented) {
                const items = getItems().filter((item) => item.focusable);
                const activeItem = items.find((item) => item.active);
                const currentItem = items.find((item) => item.id === currentTabStopId);
                const candidateItems = [activeItem, currentItem, ...items].filter(
                  Boolean
                );
                const candidateNodes = candidateItems.map((item) => item.ref.current);
                focusFirst2(candidateNodes, preventScrollOnEntryFocus);
              }
            }
            isClickFocusRef.current = false;
          }),
          onBlur: composeEventHandlers3(props.onBlur, () => setIsTabbingBackOut(false))
        }
      )
    }
  );
});
var ITEM_NAME = "RovingFocusGroupItem";
var RovingFocusGroupItem = React35.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeRovingFocusGroup,
      focusable = true,
      active = false,
      tabStopId,
      ...itemProps
    } = props;
    const autoId = useId();
    const id = tabStopId || autoId;
    const context = useRovingFocusContext(ITEM_NAME, __scopeRovingFocusGroup);
    const isCurrentTabStop = context.currentTabStopId === id;
    const getItems = useCollection(__scopeRovingFocusGroup);
    const { onFocusableItemAdd, onFocusableItemRemove } = context;
    React35.useEffect(() => {
      if (focusable) {
        onFocusableItemAdd();
        return () => onFocusableItemRemove();
      }
    }, [focusable, onFocusableItemAdd, onFocusableItemRemove]);
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      Collection.ItemSlot,
      {
        scope: __scopeRovingFocusGroup,
        id,
        focusable,
        active,
        children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
          Primitive3.span,
          {
            tabIndex: isCurrentTabStop ? 0 : -1,
            "data-orientation": context.orientation,
            ...itemProps,
            ref: forwardedRef,
            onMouseDown: composeEventHandlers3(props.onMouseDown, (event) => {
              if (!focusable)
                event.preventDefault();
              else
                context.onItemFocus(id);
            }),
            onFocus: composeEventHandlers3(props.onFocus, () => context.onItemFocus(id)),
            onKeyDown: composeEventHandlers3(props.onKeyDown, (event) => {
              if (event.key === "Tab" && event.shiftKey) {
                context.onItemShiftTab();
                return;
              }
              if (event.target !== event.currentTarget)
                return;
              const focusIntent = getFocusIntent(event, context.orientation, context.dir);
              if (focusIntent !== void 0) {
                if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
                  return;
                event.preventDefault();
                const items = getItems().filter((item) => item.focusable);
                let candidateNodes = items.map((item) => item.ref.current);
                if (focusIntent === "last")
                  candidateNodes.reverse();
                else if (focusIntent === "prev" || focusIntent === "next") {
                  if (focusIntent === "prev")
                    candidateNodes.reverse();
                  const currentIndex = candidateNodes.indexOf(event.currentTarget);
                  candidateNodes = context.loop ? wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1);
                }
                setTimeout(() => focusFirst2(candidateNodes));
              }
            })
          }
        )
      }
    );
  }
);
RovingFocusGroupItem.displayName = ITEM_NAME;
var MAP_KEY_TO_FOCUS_INTENT = {
  ArrowLeft: "prev",
  ArrowUp: "prev",
  ArrowRight: "next",
  ArrowDown: "next",
  PageUp: "first",
  Home: "first",
  PageDown: "last",
  End: "last"
};
function getDirectionAwareKey(key, dir) {
  if (dir !== "rtl")
    return key;
  return key === "ArrowLeft" ? "ArrowRight" : key === "ArrowRight" ? "ArrowLeft" : key;
}
function getFocusIntent(event, orientation, dir) {
  const key = getDirectionAwareKey(event.key, dir);
  if (orientation === "vertical" && ["ArrowLeft", "ArrowRight"].includes(key))
    return void 0;
  if (orientation === "horizontal" && ["ArrowUp", "ArrowDown"].includes(key))
    return void 0;
  return MAP_KEY_TO_FOCUS_INTENT[key];
}
function focusFirst2(candidates, preventScroll = false) {
  const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
  for (const candidate of candidates) {
    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)
      return;
    candidate.focus({ preventScroll });
    if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT)
      return;
  }
}
function wrapArray(array, startIndex) {
  return array.map((_2, index2) => array[(startIndex + index2) % array.length]);
}
var Root3 = RovingFocusGroup;
var Item = RovingFocusGroupItem;

// node_modules/aria-hidden/dist/es2015/index.js
var getDefaultParent = function(originalTarget) {
  if (typeof document === "undefined") {
    return null;
  }
  var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;
  return sampleTarget.ownerDocument.body;
};
var counterMap = /* @__PURE__ */ new WeakMap();
var uncontrolledNodes = /* @__PURE__ */ new WeakMap();
var markerMap = {};
var lockCount = 0;
var unwrapHost = function(node) {
  return node && (node.host || unwrapHost(node.parentNode));
};
var correctTargets = function(parent, targets) {
  return targets.map(function(target) {
    if (parent.contains(target)) {
      return target;
    }
    var correctedTarget = unwrapHost(target);
    if (correctedTarget && parent.contains(correctedTarget)) {
      return correctedTarget;
    }
    console.error("aria-hidden", target, "in not contained inside", parent, ". Doing nothing");
    return null;
  }).filter(function(x2) {
    return Boolean(x2);
  });
};
var applyAttributeToOthers = function(originalTarget, parentNode, markerName, controlAttribute) {
  var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
  if (!markerMap[markerName]) {
    markerMap[markerName] = /* @__PURE__ */ new WeakMap();
  }
  var markerCounter = markerMap[markerName];
  var hiddenNodes = [];
  var elementsToKeep = /* @__PURE__ */ new Set();
  var elementsToStop = new Set(targets);
  var keep = function(el) {
    if (!el || elementsToKeep.has(el)) {
      return;
    }
    elementsToKeep.add(el);
    keep(el.parentNode);
  };
  targets.forEach(keep);
  var deep = function(parent) {
    if (!parent || elementsToStop.has(parent)) {
      return;
    }
    Array.prototype.forEach.call(parent.children, function(node) {
      if (elementsToKeep.has(node)) {
        deep(node);
      } else {
        try {
          var attr = node.getAttribute(controlAttribute);
          var alreadyHidden = attr !== null && attr !== "false";
          var counterValue = (counterMap.get(node) || 0) + 1;
          var markerValue = (markerCounter.get(node) || 0) + 1;
          counterMap.set(node, counterValue);
          markerCounter.set(node, markerValue);
          hiddenNodes.push(node);
          if (counterValue === 1 && alreadyHidden) {
            uncontrolledNodes.set(node, true);
          }
          if (markerValue === 1) {
            node.setAttribute(markerName, "true");
          }
          if (!alreadyHidden) {
            node.setAttribute(controlAttribute, "true");
          }
        } catch (e3) {
          console.error("aria-hidden: cannot operate on ", node, e3);
        }
      }
    });
  };
  deep(parentNode);
  elementsToKeep.clear();
  lockCount++;
  return function() {
    hiddenNodes.forEach(function(node) {
      var counterValue = counterMap.get(node) - 1;
      var markerValue = markerCounter.get(node) - 1;
      counterMap.set(node, counterValue);
      markerCounter.set(node, markerValue);
      if (!counterValue) {
        if (!uncontrolledNodes.has(node)) {
          node.removeAttribute(controlAttribute);
        }
        uncontrolledNodes.delete(node);
      }
      if (!markerValue) {
        node.removeAttribute(markerName);
      }
    });
    lockCount--;
    if (!lockCount) {
      counterMap = /* @__PURE__ */ new WeakMap();
      counterMap = /* @__PURE__ */ new WeakMap();
      uncontrolledNodes = /* @__PURE__ */ new WeakMap();
      markerMap = {};
    }
  };
};
var hideOthers = function(originalTarget, parentNode, markerName) {
  if (markerName === void 0) {
    markerName = "data-aria-hidden";
  }
  var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
  var activeParentNode = parentNode || getDefaultParent(originalTarget);
  if (!activeParentNode) {
    return function() {
      return null;
    };
  }
  targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll("[aria-live]")));
  return applyAttributeToOthers(targets, activeParentNode, markerName, "aria-hidden");
};

// node_modules/tslib/tslib.es6.js
var __assign5 = function() {
  __assign5 = Object.assign || function __assign6(t3) {
    for (var s4, i3 = 1, n4 = arguments.length; i3 < n4; i3++) {
      s4 = arguments[i3];
      for (var p3 in s4)
        if (Object.prototype.hasOwnProperty.call(s4, p3))
          t3[p3] = s4[p3];
    }
    return t3;
  };
  return __assign5.apply(this, arguments);
};
function __rest5(s4, e3) {
  var t3 = {};
  for (var p3 in s4)
    if (Object.prototype.hasOwnProperty.call(s4, p3) && e3.indexOf(p3) < 0)
      t3[p3] = s4[p3];
  if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s4); i3 < p3.length; i3++) {
      if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i3]))
        t3[p3[i3]] = s4[p3[i3]];
    }
  return t3;
}
function __spreadArray4(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i3 = 0, l4 = from.length, ar; i3 < l4; i3++) {
      if (ar || !(i3 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i3);
        ar[i3] = from[i3];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/Combination.js
var React42 = __toESM(require_react());

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/UI.js
var React38 = __toESM(require_react());

// node_modules/react-remove-scroll-bar/dist/es2015/constants.js
var zeroRightClassName = "right-scroll-bar-position";
var fullWidthClassName = "width-before-scroll-bar";
var noScrollbarsClassName = "with-scroll-bars-hidden";
var removedBarSizeVariable = "--removed-body-scroll-bar-size";

// node_modules/use-callback-ref/dist/es2015/assignRef.js
function assignRef(ref, value) {
  if (typeof ref === "function") {
    ref(value);
  } else if (ref) {
    ref.current = value;
  }
  return ref;
}

// node_modules/use-callback-ref/dist/es2015/useRef.js
var import_react9 = __toESM(require_react());
function useCallbackRef2(initialValue, callback) {
  var ref = (0, import_react9.useState)(function() {
    return {
      // value
      value: initialValue,
      // last callback
      callback,
      // "memoized" public interface
      facade: {
        get current() {
          return ref.value;
        },
        set current(value) {
          var last = ref.value;
          if (last !== value) {
            ref.value = value;
            ref.callback(value, last);
          }
        }
      }
    };
  })[0];
  ref.callback = callback;
  return ref.facade;
}

// node_modules/use-callback-ref/dist/es2015/useMergeRef.js
var React36 = __toESM(require_react());
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? React36.useLayoutEffect : React36.useEffect;
var currentValues = /* @__PURE__ */ new WeakMap();
function useMergeRefs(refs, defaultValue) {
  var callbackRef = useCallbackRef2(defaultValue || null, function(newValue) {
    return refs.forEach(function(ref) {
      return assignRef(ref, newValue);
    });
  });
  useIsomorphicLayoutEffect(function() {
    var oldValue = currentValues.get(callbackRef);
    if (oldValue) {
      var prevRefs_1 = new Set(oldValue);
      var nextRefs_1 = new Set(refs);
      var current_1 = callbackRef.current;
      prevRefs_1.forEach(function(ref) {
        if (!nextRefs_1.has(ref)) {
          assignRef(ref, null);
        }
      });
      nextRefs_1.forEach(function(ref) {
        if (!prevRefs_1.has(ref)) {
          assignRef(ref, current_1);
        }
      });
    }
    currentValues.set(callbackRef, refs);
  }, [refs]);
  return callbackRef;
}

// node_modules/use-sidecar/dist/es2015/medium.js
function ItoI(a3) {
  return a3;
}
function innerCreateMedium(defaults2, middleware) {
  if (middleware === void 0) {
    middleware = ItoI;
  }
  var buffer = [];
  var assigned = false;
  var medium = {
    read: function() {
      if (assigned) {
        throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");
      }
      if (buffer.length) {
        return buffer[buffer.length - 1];
      }
      return defaults2;
    },
    useMedium: function(data) {
      var item = middleware(data, assigned);
      buffer.push(item);
      return function() {
        buffer = buffer.filter(function(x2) {
          return x2 !== item;
        });
      };
    },
    assignSyncMedium: function(cb) {
      assigned = true;
      while (buffer.length) {
        var cbs = buffer;
        buffer = [];
        cbs.forEach(cb);
      }
      buffer = {
        push: function(x2) {
          return cb(x2);
        },
        filter: function() {
          return buffer;
        }
      };
    },
    assignMedium: function(cb) {
      assigned = true;
      var pendingQueue = [];
      if (buffer.length) {
        var cbs = buffer;
        buffer = [];
        cbs.forEach(cb);
        pendingQueue = buffer;
      }
      var executeQueue = function() {
        var cbs2 = pendingQueue;
        pendingQueue = [];
        cbs2.forEach(cb);
      };
      var cycle = function() {
        return Promise.resolve().then(executeQueue);
      };
      cycle();
      buffer = {
        push: function(x2) {
          pendingQueue.push(x2);
          cycle();
        },
        filter: function(filter2) {
          pendingQueue = pendingQueue.filter(filter2);
          return buffer;
        }
      };
    }
  };
  return medium;
}
function createSidecarMedium(options) {
  if (options === void 0) {
    options = {};
  }
  var medium = innerCreateMedium(null);
  medium.options = __assign5({ async: true, ssr: false }, options);
  return medium;
}

// node_modules/use-sidecar/dist/es2015/exports.js
var React37 = __toESM(require_react());
var SideCar = function(_a5) {
  var sideCar = _a5.sideCar, rest = __rest5(_a5, ["sideCar"]);
  if (!sideCar) {
    throw new Error("Sidecar: please provide `sideCar` property to import the right car");
  }
  var Target = sideCar.read();
  if (!Target) {
    throw new Error("Sidecar medium not found");
  }
  return React37.createElement(Target, __assign5({}, rest));
};
SideCar.isSideCarExport = true;
function exportSidecar(medium, exported) {
  medium.useMedium(exported);
  return SideCar;
}

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/medium.js
var effectCar = createSidecarMedium();

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/UI.js
var nothing = function() {
  return;
};
var RemoveScroll = React38.forwardRef(function(props, parentRef) {
  var ref = React38.useRef(null);
  var _a5 = React38.useState({
    onScrollCapture: nothing,
    onWheelCapture: nothing,
    onTouchMoveCapture: nothing
  }), callbacks = _a5[0], setCallbacks = _a5[1];
  var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest5(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]);
  var SideCar2 = sideCar;
  var containerRef = useMergeRefs([ref, parentRef]);
  var containerProps = __assign5(__assign5({}, rest), callbacks);
  return React38.createElement(
    React38.Fragment,
    null,
    enabled && React38.createElement(SideCar2, { sideCar: effectCar, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode }),
    forwardProps ? React38.cloneElement(React38.Children.only(children), __assign5(__assign5({}, containerProps), { ref: containerRef })) : React38.createElement(Container, __assign5({}, containerProps, { className, ref: containerRef }), children)
  );
});
RemoveScroll.defaultProps = {
  enabled: true,
  removeScrollBar: true,
  inert: false
};
RemoveScroll.classNames = {
  fullWidth: fullWidthClassName,
  zeroRight: zeroRightClassName
};

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var React41 = __toESM(require_react());

// node_modules/react-remove-scroll-bar/dist/es2015/component.js
var React40 = __toESM(require_react());

// node_modules/react-style-singleton/dist/es2015/hook.js
var React39 = __toESM(require_react());

// node_modules/get-nonce/dist/es2015/index.js
var currentNonce;
var getNonce = function() {
  if (currentNonce) {
    return currentNonce;
  }
  if (typeof __webpack_nonce__ !== "undefined") {
    return __webpack_nonce__;
  }
  return void 0;
};

// node_modules/react-style-singleton/dist/es2015/singleton.js
function makeStyleTag() {
  if (!document)
    return null;
  var tag = document.createElement("style");
  tag.type = "text/css";
  var nonce = getNonce();
  if (nonce) {
    tag.setAttribute("nonce", nonce);
  }
  return tag;
}
function injectStyles(tag, css) {
  if (tag.styleSheet) {
    tag.styleSheet.cssText = css;
  } else {
    tag.appendChild(document.createTextNode(css));
  }
}
function insertStyleTag(tag) {
  var head = document.head || document.getElementsByTagName("head")[0];
  head.appendChild(tag);
}
var stylesheetSingleton = function() {
  var counter = 0;
  var stylesheet = null;
  return {
    add: function(style) {
      if (counter == 0) {
        if (stylesheet = makeStyleTag()) {
          injectStyles(stylesheet, style);
          insertStyleTag(stylesheet);
        }
      }
      counter++;
    },
    remove: function() {
      counter--;
      if (!counter && stylesheet) {
        stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
        stylesheet = null;
      }
    }
  };
};

// node_modules/react-style-singleton/dist/es2015/hook.js
var styleHookSingleton = function() {
  var sheet = stylesheetSingleton();
  return function(styles2, isDynamic) {
    React39.useEffect(function() {
      sheet.add(styles2);
      return function() {
        sheet.remove();
      };
    }, [styles2 && isDynamic]);
  };
};

// node_modules/react-style-singleton/dist/es2015/component.js
var styleSingleton = function() {
  var useStyle = styleHookSingleton();
  var Sheet = function(_a5) {
    var styles2 = _a5.styles, dynamic = _a5.dynamic;
    useStyle(styles2, dynamic);
    return null;
  };
  return Sheet;
};

// node_modules/react-remove-scroll-bar/dist/es2015/utils.js
var zeroGap = {
  left: 0,
  top: 0,
  right: 0,
  gap: 0
};
var parse5 = function(x2) {
  return parseInt(x2 || "", 10) || 0;
};
var getOffset = function(gapMode) {
  var cs = window.getComputedStyle(document.body);
  var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"];
  var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"];
  var right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"];
  return [parse5(left), parse5(top), parse5(right)];
};
var getGapWidth = function(gapMode) {
  if (gapMode === void 0) {
    gapMode = "margin";
  }
  if (typeof window === "undefined") {
    return zeroGap;
  }
  var offsets = getOffset(gapMode);
  var documentWidth = document.documentElement.clientWidth;
  var windowWidth = window.innerWidth;
  return {
    left: offsets[0],
    top: offsets[1],
    right: offsets[2],
    gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0])
  };
};

// node_modules/react-remove-scroll-bar/dist/es2015/component.js
var Style = styleSingleton();
var lockAttribute = "data-scroll-locked";
var getStyles = function(_a5, allowRelative, gapMode, important) {
  var left = _a5.left, top = _a5.top, right = _a5.right, gap = _a5.gap;
  if (gapMode === void 0) {
    gapMode = "margin";
  }
  return "\n  .".concat(noScrollbarsClassName, " {\n   overflow: hidden ").concat(important, ";\n   padding-right: ").concat(gap, "px ").concat(important, ";\n  }\n  body[").concat(lockAttribute, "] {\n    overflow: hidden ").concat(important, ";\n    overscroll-behavior: contain;\n    ").concat([
    allowRelative && "position: relative ".concat(important, ";"),
    gapMode === "margin" && "\n    padding-left: ".concat(left, "px;\n    padding-top: ").concat(top, "px;\n    padding-right: ").concat(right, "px;\n    margin-left:0;\n    margin-top:0;\n    margin-right: ").concat(gap, "px ").concat(important, ";\n    "),
    gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";")
  ].filter(Boolean).join(""), "\n  }\n  \n  .").concat(zeroRightClassName, " {\n    right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " {\n    margin-right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n    right: 0 ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n    margin-right: 0 ").concat(important, ";\n  }\n  \n  body[").concat(lockAttribute, "] {\n    ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n  }\n");
};
var getCurrentUseCounter = function() {
  var counter = parseInt(document.body.getAttribute(lockAttribute) || "0", 10);
  return isFinite(counter) ? counter : 0;
};
var useLockAttribute = function() {
  React40.useEffect(function() {
    document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString());
    return function() {
      var newCounter = getCurrentUseCounter() - 1;
      if (newCounter <= 0) {
        document.body.removeAttribute(lockAttribute);
      } else {
        document.body.setAttribute(lockAttribute, newCounter.toString());
      }
    };
  }, []);
};
var RemoveScrollBar = function(_a5) {
  var noRelative = _a5.noRelative, noImportant = _a5.noImportant, _b = _a5.gapMode, gapMode = _b === void 0 ? "margin" : _b;
  useLockAttribute();
  var gap = React40.useMemo(function() {
    return getGapWidth(gapMode);
  }, [gapMode]);
  return React40.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? "!important" : "") });
};

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js
var passiveSupported = false;
if (typeof window !== "undefined") {
  try {
    options = Object.defineProperty({}, "passive", {
      get: function() {
        passiveSupported = true;
        return true;
      }
    });
    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (err) {
    passiveSupported = false;
  }
}
var options;
var nonPassive = passiveSupported ? { passive: false } : false;

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/handleScroll.js
var alwaysContainsScroll = function(node) {
  return node.tagName === "TEXTAREA";
};
var elementCanBeScrolled = function(node, overflow) {
  if (!(node instanceof Element)) {
    return false;
  }
  var styles2 = window.getComputedStyle(node);
  return (
    // not-not-scrollable
    styles2[overflow] !== "hidden" && // contains scroll inside self
    !(styles2.overflowY === styles2.overflowX && !alwaysContainsScroll(node) && styles2[overflow] === "visible")
  );
};
var elementCouldBeVScrolled = function(node) {
  return elementCanBeScrolled(node, "overflowY");
};
var elementCouldBeHScrolled = function(node) {
  return elementCanBeScrolled(node, "overflowX");
};
var locationCouldBeScrolled = function(axis, node) {
  var ownerDocument = node.ownerDocument;
  var current = node;
  do {
    if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) {
      current = current.host;
    }
    var isScrollable = elementCouldBeScrolled(axis, current);
    if (isScrollable) {
      var _a5 = getScrollVariables(axis, current), scrollHeight = _a5[1], clientHeight = _a5[2];
      if (scrollHeight > clientHeight) {
        return true;
      }
    }
    current = current.parentNode;
  } while (current && current !== ownerDocument.body);
  return false;
};
var getVScrollVariables = function(_a5) {
  var scrollTop = _a5.scrollTop, scrollHeight = _a5.scrollHeight, clientHeight = _a5.clientHeight;
  return [
    scrollTop,
    scrollHeight,
    clientHeight
  ];
};
var getHScrollVariables = function(_a5) {
  var scrollLeft = _a5.scrollLeft, scrollWidth = _a5.scrollWidth, clientWidth = _a5.clientWidth;
  return [
    scrollLeft,
    scrollWidth,
    clientWidth
  ];
};
var elementCouldBeScrolled = function(axis, node) {
  return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);
};
var getScrollVariables = function(axis, node) {
  return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node);
};
var getDirectionFactor = function(axis, direction) {
  return axis === "h" && direction === "rtl" ? -1 : 1;
};
var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) {
  var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);
  var delta = directionFactor * sourceDelta;
  var target = event.target;
  var targetInLock = endTarget.contains(target);
  var shouldCancelScroll = false;
  var isDeltaPositive = delta > 0;
  var availableScroll = 0;
  var availableScrollTop = 0;
  do {
    var _a5 = getScrollVariables(axis, target), position = _a5[0], scroll_1 = _a5[1], capacity = _a5[2];
    var elementScroll = scroll_1 - capacity - directionFactor * position;
    if (position || elementScroll) {
      if (elementCouldBeScrolled(axis, target)) {
        availableScroll += elementScroll;
        availableScrollTop += position;
      }
    }
    if (target instanceof ShadowRoot) {
      target = target.host;
    } else {
      target = target.parentNode;
    }
  } while (
    // portaled content
    !targetInLock && target !== document.body || // self content
    targetInLock && (endTarget.contains(target) || endTarget === target)
  );
  if (isDeltaPositive && (noOverscroll && Math.abs(availableScroll) < 1 || !noOverscroll && delta > availableScroll)) {
    shouldCancelScroll = true;
  } else if (!isDeltaPositive && (noOverscroll && Math.abs(availableScrollTop) < 1 || !noOverscroll && -delta > availableScrollTop)) {
    shouldCancelScroll = true;
  }
  return shouldCancelScroll;
};

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var getTouchXY = function(event) {
  return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
};
var getDeltaXY = function(event) {
  return [event.deltaX, event.deltaY];
};
var extractRef = function(ref) {
  return ref && "current" in ref ? ref.current : ref;
};
var deltaCompare = function(x2, y2) {
  return x2[0] === y2[0] && x2[1] === y2[1];
};
var generateStyle = function(id) {
  return "\n  .block-interactivity-".concat(id, " {pointer-events: none;}\n  .allow-interactivity-").concat(id, " {pointer-events: all;}\n");
};
var idCounter = 0;
var lockStack = [];
function RemoveScrollSideCar(props) {
  var shouldPreventQueue = React41.useRef([]);
  var touchStartRef = React41.useRef([0, 0]);
  var activeAxis = React41.useRef();
  var id = React41.useState(idCounter++)[0];
  var Style2 = React41.useState(styleSingleton)[0];
  var lastProps = React41.useRef(props);
  React41.useEffect(function() {
    lastProps.current = props;
  }, [props]);
  React41.useEffect(function() {
    if (props.inert) {
      document.body.classList.add("block-interactivity-".concat(id));
      var allow_1 = __spreadArray4([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);
      allow_1.forEach(function(el) {
        return el.classList.add("allow-interactivity-".concat(id));
      });
      return function() {
        document.body.classList.remove("block-interactivity-".concat(id));
        allow_1.forEach(function(el) {
          return el.classList.remove("allow-interactivity-".concat(id));
        });
      };
    }
    return;
  }, [props.inert, props.lockRef.current, props.shards]);
  var shouldCancelEvent = React41.useCallback(function(event, parent) {
    if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) {
      return !lastProps.current.allowPinchZoom;
    }
    var touch = getTouchXY(event);
    var touchStart = touchStartRef.current;
    var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0];
    var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1];
    var currentAxis;
    var target = event.target;
    var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v";
    if ("touches" in event && moveDirection === "h" && target.type === "range") {
      return false;
    }
    var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
    if (!canBeScrolledInMainDirection) {
      return true;
    }
    if (canBeScrolledInMainDirection) {
      currentAxis = moveDirection;
    } else {
      currentAxis = moveDirection === "v" ? "h" : "v";
      canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
    }
    if (!canBeScrolledInMainDirection) {
      return false;
    }
    if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) {
      activeAxis.current = currentAxis;
    }
    if (!currentAxis) {
      return true;
    }
    var cancelingAxis = activeAxis.current || currentAxis;
    return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true);
  }, []);
  var shouldPrevent = React41.useCallback(function(_event) {
    var event = _event;
    if (!lockStack.length || lockStack[lockStack.length - 1] !== Style2) {
      return;
    }
    var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event);
    var sourceEvent = shouldPreventQueue.current.filter(function(e3) {
      return e3.name === event.type && (e3.target === event.target || event.target === e3.shadowParent) && deltaCompare(e3.delta, delta);
    })[0];
    if (sourceEvent && sourceEvent.should) {
      if (event.cancelable) {
        event.preventDefault();
      }
      return;
    }
    if (!sourceEvent) {
      var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) {
        return node.contains(event.target);
      });
      var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
      if (shouldStop) {
        if (event.cancelable) {
          event.preventDefault();
        }
      }
    }
  }, []);
  var shouldCancel = React41.useCallback(function(name, delta, target, should) {
    var event = { name, delta, target, should, shadowParent: getOutermostShadowParent(target) };
    shouldPreventQueue.current.push(event);
    setTimeout(function() {
      shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e3) {
        return e3 !== event;
      });
    }, 1);
  }, []);
  var scrollTouchStart = React41.useCallback(function(event) {
    touchStartRef.current = getTouchXY(event);
    activeAxis.current = void 0;
  }, []);
  var scrollWheel = React41.useCallback(function(event) {
    shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  var scrollTouchMove = React41.useCallback(function(event) {
    shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  React41.useEffect(function() {
    lockStack.push(Style2);
    props.setCallbacks({
      onScrollCapture: scrollWheel,
      onWheelCapture: scrollWheel,
      onTouchMoveCapture: scrollTouchMove
    });
    document.addEventListener("wheel", shouldPrevent, nonPassive);
    document.addEventListener("touchmove", shouldPrevent, nonPassive);
    document.addEventListener("touchstart", scrollTouchStart, nonPassive);
    return function() {
      lockStack = lockStack.filter(function(inst) {
        return inst !== Style2;
      });
      document.removeEventListener("wheel", shouldPrevent, nonPassive);
      document.removeEventListener("touchmove", shouldPrevent, nonPassive);
      document.removeEventListener("touchstart", scrollTouchStart, nonPassive);
    };
  }, []);
  var removeScrollBar = props.removeScrollBar, inert = props.inert;
  return React41.createElement(
    React41.Fragment,
    null,
    inert ? React41.createElement(Style2, { styles: generateStyle(id) }) : null,
    removeScrollBar ? React41.createElement(RemoveScrollBar, { gapMode: props.gapMode }) : null
  );
}
function getOutermostShadowParent(node) {
  var shadowParent = null;
  while (node !== null) {
    if (node instanceof ShadowRoot) {
      shadowParent = node.host;
      node = node.host;
    }
    node = node.parentNode;
  }
  return shadowParent;
}

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/sidecar.js
var sidecar_default = exportSidecar(effectCar, RemoveScrollSideCar);

// node_modules/@radix-ui/react-menu/node_modules/react-remove-scroll/dist/es2015/Combination.js
var ReactRemoveScroll = React42.forwardRef(function(props, ref) {
  return React42.createElement(RemoveScroll, __assign5({}, props, { ref, sideCar: sidecar_default }));
});
ReactRemoveScroll.classNames = RemoveScroll.classNames;
var Combination_default = ReactRemoveScroll;

// node_modules/@radix-ui/react-menu/dist/index.mjs
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
"use client";
var SELECTION_KEYS = ["Enter", " "];
var FIRST_KEYS = ["ArrowDown", "PageUp", "Home"];
var LAST_KEYS = ["ArrowUp", "PageDown", "End"];
var FIRST_LAST_KEYS = [...FIRST_KEYS, ...LAST_KEYS];
var SUB_OPEN_KEYS = {
  ltr: [...SELECTION_KEYS, "ArrowRight"],
  rtl: [...SELECTION_KEYS, "ArrowLeft"]
};
var SUB_CLOSE_KEYS = {
  ltr: ["ArrowLeft"],
  rtl: ["ArrowRight"]
};
var MENU_NAME = "Menu";
var [Collection2, useCollection2, createCollectionScope2] = createCollection(MENU_NAME);
var [createMenuContext, createMenuScope] = createContextScope(MENU_NAME, [
  createCollectionScope2,
  createPopperScope,
  createRovingFocusGroupScope
]);
var usePopperScope = createPopperScope();
var useRovingFocusGroupScope = createRovingFocusGroupScope();
var [MenuProvider, useMenuContext] = createMenuContext(MENU_NAME);
var [MenuRootProvider, useMenuRootContext] = createMenuContext(MENU_NAME);
var Menu = (props) => {
  const { __scopeMenu, open = false, children, dir, onOpenChange, modal = true } = props;
  const popperScope = usePopperScope(__scopeMenu);
  const [content, setContent] = React43.useState(null);
  const isUsingKeyboardRef = React43.useRef(false);
  const handleOpenChange = useCallbackRef(onOpenChange);
  const direction = useDirection(dir);
  React43.useEffect(() => {
    const handleKeyDown = () => {
      isUsingKeyboardRef.current = true;
      document.addEventListener("pointerdown", handlePointer, { capture: true, once: true });
      document.addEventListener("pointermove", handlePointer, { capture: true, once: true });
    };
    const handlePointer = () => isUsingKeyboardRef.current = false;
    document.addEventListener("keydown", handleKeyDown, { capture: true });
    return () => {
      document.removeEventListener("keydown", handleKeyDown, { capture: true });
      document.removeEventListener("pointerdown", handlePointer, { capture: true });
      document.removeEventListener("pointermove", handlePointer, { capture: true });
    };
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Root22, { ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
    MenuProvider,
    {
      scope: __scopeMenu,
      open,
      onOpenChange: handleOpenChange,
      content,
      onContentChange: setContent,
      children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
        MenuRootProvider,
        {
          scope: __scopeMenu,
          onClose: React43.useCallback(() => handleOpenChange(false), [handleOpenChange]),
          isUsingKeyboardRef,
          dir: direction,
          modal,
          children
        }
      )
    }
  ) });
};
Menu.displayName = MENU_NAME;
var ANCHOR_NAME2 = "MenuAnchor";
var MenuAnchor = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, ...anchorProps } = props;
    const popperScope = usePopperScope(__scopeMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Anchor, { ...popperScope, ...anchorProps, ref: forwardedRef });
  }
);
MenuAnchor.displayName = ANCHOR_NAME2;
var PORTAL_NAME2 = "MenuPortal";
var [PortalProvider, usePortalContext] = createMenuContext(PORTAL_NAME2, {
  forceMount: void 0
});
var MenuPortal = (props) => {
  const { __scopeMenu, forceMount, children, container } = props;
  const context = useMenuContext(PORTAL_NAME2, __scopeMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(PortalProvider, { scope: __scopeMenu, forceMount, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Portal, { asChild: true, container, children }) }) });
};
MenuPortal.displayName = PORTAL_NAME2;
var CONTENT_NAME2 = "MenuContent";
var [MenuContentProvider, useMenuContentContext] = createMenuContext(CONTENT_NAME2);
var MenuContent = React43.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext(CONTENT_NAME2, props.__scopeMenu);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = useMenuContext(CONTENT_NAME2, props.__scopeMenu);
    const rootContext = useMenuRootContext(CONTENT_NAME2, props.__scopeMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Collection2.Provider, { scope: props.__scopeMenu, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Collection2.Slot, { scope: props.__scopeMenu, children: rootContext.modal ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(MenuRootContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(MenuRootContentNonModal, { ...contentProps, ref: forwardedRef }) }) }) });
  }
);
var MenuRootContentModal = React43.forwardRef(
  (props, forwardedRef) => {
    const context = useMenuContext(CONTENT_NAME2, props.__scopeMenu);
    const ref = React43.useRef(null);
    const composedRefs = useComposedRefs2(forwardedRef, ref);
    React43.useEffect(() => {
      const content = ref.current;
      if (content)
        return hideOthers(content);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: context.open,
        disableOutsideScroll: true,
        onFocusOutside: composeEventHandlers2(
          props.onFocusOutside,
          (event) => event.preventDefault(),
          { checkForDefaultPrevented: false }
        ),
        onDismiss: () => context.onOpenChange(false)
      }
    );
  }
);
var MenuRootContentNonModal = React43.forwardRef((props, forwardedRef) => {
  const context = useMenuContext(CONTENT_NAME2, props.__scopeMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
    MenuContentImpl,
    {
      ...props,
      ref: forwardedRef,
      trapFocus: false,
      disableOutsidePointerEvents: false,
      disableOutsideScroll: false,
      onDismiss: () => context.onOpenChange(false)
    }
  );
});
var MenuContentImpl = React43.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeMenu,
      loop = false,
      trapFocus,
      onOpenAutoFocus,
      onCloseAutoFocus,
      disableOutsidePointerEvents,
      onEntryFocus,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      disableOutsideScroll,
      ...contentProps
    } = props;
    const context = useMenuContext(CONTENT_NAME2, __scopeMenu);
    const rootContext = useMenuRootContext(CONTENT_NAME2, __scopeMenu);
    const popperScope = usePopperScope(__scopeMenu);
    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeMenu);
    const getItems = useCollection2(__scopeMenu);
    const [currentItemId, setCurrentItemId] = React43.useState(null);
    const contentRef = React43.useRef(null);
    const composedRefs = useComposedRefs2(forwardedRef, contentRef, context.onContentChange);
    const timerRef = React43.useRef(0);
    const searchRef = React43.useRef("");
    const pointerGraceTimerRef = React43.useRef(0);
    const pointerGraceIntentRef = React43.useRef(null);
    const pointerDirRef = React43.useRef("right");
    const lastPointerXRef = React43.useRef(0);
    const ScrollLockWrapper = disableOutsideScroll ? Combination_default : React43.Fragment;
    const scrollLockWrapperProps = disableOutsideScroll ? { as: Slot3, allowPinchZoom: true } : void 0;
    const handleTypeaheadSearch = (key) => {
      const search3 = searchRef.current + key;
      const items = getItems().filter((item) => !item.disabled);
      const currentItem = document.activeElement;
      const currentMatch = items.find((item) => item.ref.current === currentItem)?.textValue;
      const values = items.map((item) => item.textValue);
      const nextMatch = getNextMatch(values, search3, currentMatch);
      const newItem = items.find((item) => item.textValue === nextMatch)?.ref.current;
      (function updateSearch(value) {
        searchRef.current = value;
        window.clearTimeout(timerRef.current);
        if (value !== "")
          timerRef.current = window.setTimeout(() => updateSearch(""), 1e3);
      })(search3);
      if (newItem) {
        setTimeout(() => newItem.focus());
      }
    };
    React43.useEffect(() => {
      return () => window.clearTimeout(timerRef.current);
    }, []);
    useFocusGuards();
    const isPointerMovingToSubmenu = React43.useCallback((event) => {
      const isMovingTowards = pointerDirRef.current === pointerGraceIntentRef.current?.side;
      return isMovingTowards && isPointerInGraceArea(event, pointerGraceIntentRef.current?.area);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuContentProvider,
      {
        scope: __scopeMenu,
        searchRef,
        onItemEnter: React43.useCallback(
          (event) => {
            if (isPointerMovingToSubmenu(event))
              event.preventDefault();
          },
          [isPointerMovingToSubmenu]
        ),
        onItemLeave: React43.useCallback(
          (event) => {
            if (isPointerMovingToSubmenu(event))
              return;
            contentRef.current?.focus();
            setCurrentItemId(null);
          },
          [isPointerMovingToSubmenu]
        ),
        onTriggerLeave: React43.useCallback(
          (event) => {
            if (isPointerMovingToSubmenu(event))
              event.preventDefault();
          },
          [isPointerMovingToSubmenu]
        ),
        pointerGraceTimerRef,
        onPointerGraceIntentChange: React43.useCallback((intent) => {
          pointerGraceIntentRef.current = intent;
        }, []),
        children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ScrollLockWrapper, { ...scrollLockWrapperProps, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
          FocusScope,
          {
            asChild: true,
            trapped: trapFocus,
            onMountAutoFocus: composeEventHandlers2(onOpenAutoFocus, (event) => {
              event.preventDefault();
              contentRef.current?.focus({ preventScroll: true });
            }),
            onUnmountAutoFocus: onCloseAutoFocus,
            children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
              DismissableLayer,
              {
                asChild: true,
                disableOutsidePointerEvents,
                onEscapeKeyDown,
                onPointerDownOutside,
                onFocusOutside,
                onInteractOutside,
                onDismiss,
                children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
                  Root3,
                  {
                    asChild: true,
                    ...rovingFocusGroupScope,
                    dir: rootContext.dir,
                    orientation: "vertical",
                    loop,
                    currentTabStopId: currentItemId,
                    onCurrentTabStopIdChange: setCurrentItemId,
                    onEntryFocus: composeEventHandlers2(onEntryFocus, (event) => {
                      if (!rootContext.isUsingKeyboardRef.current)
                        event.preventDefault();
                    }),
                    preventScrollOnEntryFocus: true,
                    children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
                      Content,
                      {
                        role: "menu",
                        "aria-orientation": "vertical",
                        "data-state": getOpenState(context.open),
                        "data-radix-menu-content": "",
                        dir: rootContext.dir,
                        ...popperScope,
                        ...contentProps,
                        ref: composedRefs,
                        style: { outline: "none", ...contentProps.style },
                        onKeyDown: composeEventHandlers2(contentProps.onKeyDown, (event) => {
                          const target = event.target;
                          const isKeyDownInside = target.closest("[data-radix-menu-content]") === event.currentTarget;
                          const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
                          const isCharacterKey = event.key.length === 1;
                          if (isKeyDownInside) {
                            if (event.key === "Tab")
                              event.preventDefault();
                            if (!isModifierKey && isCharacterKey)
                              handleTypeaheadSearch(event.key);
                          }
                          const content = contentRef.current;
                          if (event.target !== content)
                            return;
                          if (!FIRST_LAST_KEYS.includes(event.key))
                            return;
                          event.preventDefault();
                          const items = getItems().filter((item) => !item.disabled);
                          const candidateNodes = items.map((item) => item.ref.current);
                          if (LAST_KEYS.includes(event.key))
                            candidateNodes.reverse();
                          focusFirst3(candidateNodes);
                        }),
                        onBlur: composeEventHandlers2(props.onBlur, (event) => {
                          if (!event.currentTarget.contains(event.target)) {
                            window.clearTimeout(timerRef.current);
                            searchRef.current = "";
                          }
                        }),
                        onPointerMove: composeEventHandlers2(
                          props.onPointerMove,
                          whenMouse((event) => {
                            const target = event.target;
                            const pointerXHasChanged = lastPointerXRef.current !== event.clientX;
                            if (event.currentTarget.contains(target) && pointerXHasChanged) {
                              const newDir = event.clientX > lastPointerXRef.current ? "right" : "left";
                              pointerDirRef.current = newDir;
                              lastPointerXRef.current = event.clientX;
                            }
                          })
                        )
                      }
                    )
                  }
                )
              }
            )
          }
        ) })
      }
    );
  }
);
MenuContent.displayName = CONTENT_NAME2;
var GROUP_NAME2 = "MenuGroup";
var MenuGroup = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, ...groupProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Primitive2.div, { role: "group", ...groupProps, ref: forwardedRef });
  }
);
MenuGroup.displayName = GROUP_NAME2;
var LABEL_NAME = "MenuLabel";
var MenuLabel = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, ...labelProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Primitive2.div, { ...labelProps, ref: forwardedRef });
  }
);
MenuLabel.displayName = LABEL_NAME;
var ITEM_NAME2 = "MenuItem";
var ITEM_SELECT = "menu.itemSelect";
var MenuItem = React43.forwardRef(
  (props, forwardedRef) => {
    const { disabled = false, onSelect, ...itemProps } = props;
    const ref = React43.useRef(null);
    const rootContext = useMenuRootContext(ITEM_NAME2, props.__scopeMenu);
    const contentContext = useMenuContentContext(ITEM_NAME2, props.__scopeMenu);
    const composedRefs = useComposedRefs2(forwardedRef, ref);
    const isPointerDownRef = React43.useRef(false);
    const handleSelect = () => {
      const menuItem = ref.current;
      if (!disabled && menuItem) {
        const itemSelectEvent = new CustomEvent(ITEM_SELECT, { bubbles: true, cancelable: true });
        menuItem.addEventListener(ITEM_SELECT, (event) => onSelect?.(event), { once: true });
        dispatchDiscreteCustomEvent(menuItem, itemSelectEvent);
        if (itemSelectEvent.defaultPrevented) {
          isPointerDownRef.current = false;
        } else {
          rootContext.onClose();
        }
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuItemImpl,
      {
        ...itemProps,
        ref: composedRefs,
        disabled,
        onClick: composeEventHandlers2(props.onClick, handleSelect),
        onPointerDown: (event) => {
          props.onPointerDown?.(event);
          isPointerDownRef.current = true;
        },
        onPointerUp: composeEventHandlers2(props.onPointerUp, (event) => {
          if (!isPointerDownRef.current)
            event.currentTarget?.click();
        }),
        onKeyDown: composeEventHandlers2(props.onKeyDown, (event) => {
          const isTypingAhead = contentContext.searchRef.current !== "";
          if (disabled || isTypingAhead && event.key === " ")
            return;
          if (SELECTION_KEYS.includes(event.key)) {
            event.currentTarget.click();
            event.preventDefault();
          }
        })
      }
    );
  }
);
MenuItem.displayName = ITEM_NAME2;
var MenuItemImpl = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, disabled = false, textValue, ...itemProps } = props;
    const contentContext = useMenuContentContext(ITEM_NAME2, __scopeMenu);
    const rovingFocusGroupScope = useRovingFocusGroupScope(__scopeMenu);
    const ref = React43.useRef(null);
    const composedRefs = useComposedRefs2(forwardedRef, ref);
    const [isFocused, setIsFocused] = React43.useState(false);
    const [textContent, setTextContent] = React43.useState("");
    React43.useEffect(() => {
      const menuItem = ref.current;
      if (menuItem) {
        setTextContent((menuItem.textContent ?? "").trim());
      }
    }, [itemProps.children]);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      Collection2.ItemSlot,
      {
        scope: __scopeMenu,
        disabled,
        textValue: textValue ?? textContent,
        children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Item, { asChild: true, ...rovingFocusGroupScope, focusable: !disabled, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
          Primitive2.div,
          {
            role: "menuitem",
            "data-highlighted": isFocused ? "" : void 0,
            "aria-disabled": disabled || void 0,
            "data-disabled": disabled ? "" : void 0,
            ...itemProps,
            ref: composedRefs,
            onPointerMove: composeEventHandlers2(
              props.onPointerMove,
              whenMouse((event) => {
                if (disabled) {
                  contentContext.onItemLeave(event);
                } else {
                  contentContext.onItemEnter(event);
                  if (!event.defaultPrevented) {
                    const item = event.currentTarget;
                    item.focus({ preventScroll: true });
                  }
                }
              })
            ),
            onPointerLeave: composeEventHandlers2(
              props.onPointerLeave,
              whenMouse((event) => contentContext.onItemLeave(event))
            ),
            onFocus: composeEventHandlers2(props.onFocus, () => setIsFocused(true)),
            onBlur: composeEventHandlers2(props.onBlur, () => setIsFocused(false))
          }
        ) })
      }
    );
  }
);
var CHECKBOX_ITEM_NAME = "MenuCheckboxItem";
var MenuCheckboxItem = React43.forwardRef(
  (props, forwardedRef) => {
    const { checked = false, onCheckedChange, ...checkboxItemProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ItemIndicatorProvider, { scope: props.__scopeMenu, checked, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuItem,
      {
        role: "menuitemcheckbox",
        "aria-checked": isIndeterminate(checked) ? "mixed" : checked,
        ...checkboxItemProps,
        ref: forwardedRef,
        "data-state": getCheckedState(checked),
        onSelect: composeEventHandlers2(
          checkboxItemProps.onSelect,
          () => onCheckedChange?.(isIndeterminate(checked) ? true : !checked),
          { checkForDefaultPrevented: false }
        )
      }
    ) });
  }
);
MenuCheckboxItem.displayName = CHECKBOX_ITEM_NAME;
var RADIO_GROUP_NAME = "MenuRadioGroup";
var [RadioGroupProvider, useRadioGroupContext] = createMenuContext(
  RADIO_GROUP_NAME,
  { value: void 0, onValueChange: () => {
  } }
);
var MenuRadioGroup = React43.forwardRef(
  (props, forwardedRef) => {
    const { value, onValueChange, ...groupProps } = props;
    const handleValueChange = useCallbackRef(onValueChange);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(RadioGroupProvider, { scope: props.__scopeMenu, value, onValueChange: handleValueChange, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(MenuGroup, { ...groupProps, ref: forwardedRef }) });
  }
);
MenuRadioGroup.displayName = RADIO_GROUP_NAME;
var RADIO_ITEM_NAME = "MenuRadioItem";
var MenuRadioItem = React43.forwardRef(
  (props, forwardedRef) => {
    const { value, ...radioItemProps } = props;
    const context = useRadioGroupContext(RADIO_ITEM_NAME, props.__scopeMenu);
    const checked = value === context.value;
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ItemIndicatorProvider, { scope: props.__scopeMenu, checked, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuItem,
      {
        role: "menuitemradio",
        "aria-checked": checked,
        ...radioItemProps,
        ref: forwardedRef,
        "data-state": getCheckedState(checked),
        onSelect: composeEventHandlers2(
          radioItemProps.onSelect,
          () => context.onValueChange?.(value),
          { checkForDefaultPrevented: false }
        )
      }
    ) });
  }
);
MenuRadioItem.displayName = RADIO_ITEM_NAME;
var ITEM_INDICATOR_NAME = "MenuItemIndicator";
var [ItemIndicatorProvider, useItemIndicatorContext] = createMenuContext(
  ITEM_INDICATOR_NAME,
  { checked: false }
);
var MenuItemIndicator = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, forceMount, ...itemIndicatorProps } = props;
    const indicatorContext = useItemIndicatorContext(ITEM_INDICATOR_NAME, __scopeMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      Presence,
      {
        present: forceMount || isIndeterminate(indicatorContext.checked) || indicatorContext.checked === true,
        children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
          Primitive2.span,
          {
            ...itemIndicatorProps,
            ref: forwardedRef,
            "data-state": getCheckedState(indicatorContext.checked)
          }
        )
      }
    );
  }
);
MenuItemIndicator.displayName = ITEM_INDICATOR_NAME;
var SEPARATOR_NAME = "MenuSeparator";
var MenuSeparator = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, ...separatorProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      Primitive2.div,
      {
        role: "separator",
        "aria-orientation": "horizontal",
        ...separatorProps,
        ref: forwardedRef
      }
    );
  }
);
MenuSeparator.displayName = SEPARATOR_NAME;
var ARROW_NAME2 = "MenuArrow";
var MenuArrow = React43.forwardRef(
  (props, forwardedRef) => {
    const { __scopeMenu, ...arrowProps } = props;
    const popperScope = usePopperScope(__scopeMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Arrow2, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
MenuArrow.displayName = ARROW_NAME2;
var SUB_NAME = "MenuSub";
var [MenuSubProvider, useMenuSubContext] = createMenuContext(SUB_NAME);
var MenuSub = (props) => {
  const { __scopeMenu, children, open = false, onOpenChange } = props;
  const parentMenuContext = useMenuContext(SUB_NAME, __scopeMenu);
  const popperScope = usePopperScope(__scopeMenu);
  const [trigger, setTrigger] = React43.useState(null);
  const [content, setContent] = React43.useState(null);
  const handleOpenChange = useCallbackRef(onOpenChange);
  React43.useEffect(() => {
    if (parentMenuContext.open === false)
      handleOpenChange(false);
    return () => handleOpenChange(false);
  }, [parentMenuContext.open, handleOpenChange]);
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Root22, { ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
    MenuProvider,
    {
      scope: __scopeMenu,
      open,
      onOpenChange: handleOpenChange,
      content,
      onContentChange: setContent,
      children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
        MenuSubProvider,
        {
          scope: __scopeMenu,
          contentId: useId(),
          triggerId: useId(),
          trigger,
          onTriggerChange: setTrigger,
          children
        }
      )
    }
  ) });
};
MenuSub.displayName = SUB_NAME;
var SUB_TRIGGER_NAME = "MenuSubTrigger";
var MenuSubTrigger = React43.forwardRef(
  (props, forwardedRef) => {
    const context = useMenuContext(SUB_TRIGGER_NAME, props.__scopeMenu);
    const rootContext = useMenuRootContext(SUB_TRIGGER_NAME, props.__scopeMenu);
    const subContext = useMenuSubContext(SUB_TRIGGER_NAME, props.__scopeMenu);
    const contentContext = useMenuContentContext(SUB_TRIGGER_NAME, props.__scopeMenu);
    const openTimerRef = React43.useRef(null);
    const { pointerGraceTimerRef, onPointerGraceIntentChange } = contentContext;
    const scope = { __scopeMenu: props.__scopeMenu };
    const clearOpenTimer = React43.useCallback(() => {
      if (openTimerRef.current)
        window.clearTimeout(openTimerRef.current);
      openTimerRef.current = null;
    }, []);
    React43.useEffect(() => clearOpenTimer, [clearOpenTimer]);
    React43.useEffect(() => {
      const pointerGraceTimer = pointerGraceTimerRef.current;
      return () => {
        window.clearTimeout(pointerGraceTimer);
        onPointerGraceIntentChange(null);
      };
    }, [pointerGraceTimerRef, onPointerGraceIntentChange]);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(MenuAnchor, { asChild: true, ...scope, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuItemImpl,
      {
        id: subContext.triggerId,
        "aria-haspopup": "menu",
        "aria-expanded": context.open,
        "aria-controls": subContext.contentId,
        "data-state": getOpenState(context.open),
        ...props,
        ref: composeRefs3(forwardedRef, subContext.onTriggerChange),
        onClick: (event) => {
          props.onClick?.(event);
          if (props.disabled || event.defaultPrevented)
            return;
          event.currentTarget.focus();
          if (!context.open)
            context.onOpenChange(true);
        },
        onPointerMove: composeEventHandlers2(
          props.onPointerMove,
          whenMouse((event) => {
            contentContext.onItemEnter(event);
            if (event.defaultPrevented)
              return;
            if (!props.disabled && !context.open && !openTimerRef.current) {
              contentContext.onPointerGraceIntentChange(null);
              openTimerRef.current = window.setTimeout(() => {
                context.onOpenChange(true);
                clearOpenTimer();
              }, 100);
            }
          })
        ),
        onPointerLeave: composeEventHandlers2(
          props.onPointerLeave,
          whenMouse((event) => {
            clearOpenTimer();
            const contentRect = context.content?.getBoundingClientRect();
            if (contentRect) {
              const side = context.content?.dataset.side;
              const rightSide = side === "right";
              const bleed = rightSide ? -5 : 5;
              const contentNearEdge = contentRect[rightSide ? "left" : "right"];
              const contentFarEdge = contentRect[rightSide ? "right" : "left"];
              contentContext.onPointerGraceIntentChange({
                area: [
                  // Apply a bleed on clientX to ensure that our exit point is
                  // consistently within polygon bounds
                  { x: event.clientX + bleed, y: event.clientY },
                  { x: contentNearEdge, y: contentRect.top },
                  { x: contentFarEdge, y: contentRect.top },
                  { x: contentFarEdge, y: contentRect.bottom },
                  { x: contentNearEdge, y: contentRect.bottom }
                ],
                side
              });
              window.clearTimeout(pointerGraceTimerRef.current);
              pointerGraceTimerRef.current = window.setTimeout(
                () => contentContext.onPointerGraceIntentChange(null),
                300
              );
            } else {
              contentContext.onTriggerLeave(event);
              if (event.defaultPrevented)
                return;
              contentContext.onPointerGraceIntentChange(null);
            }
          })
        ),
        onKeyDown: composeEventHandlers2(props.onKeyDown, (event) => {
          const isTypingAhead = contentContext.searchRef.current !== "";
          if (props.disabled || isTypingAhead && event.key === " ")
            return;
          if (SUB_OPEN_KEYS[rootContext.dir].includes(event.key)) {
            context.onOpenChange(true);
            context.content?.focus();
            event.preventDefault();
          }
        })
      }
    ) });
  }
);
MenuSubTrigger.displayName = SUB_TRIGGER_NAME;
var SUB_CONTENT_NAME = "MenuSubContent";
var MenuSubContent = React43.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext(CONTENT_NAME2, props.__scopeMenu);
    const { forceMount = portalContext.forceMount, ...subContentProps } = props;
    const context = useMenuContext(CONTENT_NAME2, props.__scopeMenu);
    const rootContext = useMenuRootContext(CONTENT_NAME2, props.__scopeMenu);
    const subContext = useMenuSubContext(SUB_CONTENT_NAME, props.__scopeMenu);
    const ref = React43.useRef(null);
    const composedRefs = useComposedRefs2(forwardedRef, ref);
    return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Collection2.Provider, { scope: props.__scopeMenu, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Collection2.Slot, { scope: props.__scopeMenu, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      MenuContentImpl,
      {
        id: subContext.contentId,
        "aria-labelledby": subContext.triggerId,
        ...subContentProps,
        ref: composedRefs,
        align: "start",
        side: rootContext.dir === "rtl" ? "left" : "right",
        disableOutsidePointerEvents: false,
        disableOutsideScroll: false,
        trapFocus: false,
        onOpenAutoFocus: (event) => {
          if (rootContext.isUsingKeyboardRef.current)
            ref.current?.focus();
          event.preventDefault();
        },
        onCloseAutoFocus: (event) => event.preventDefault(),
        onFocusOutside: composeEventHandlers2(props.onFocusOutside, (event) => {
          if (event.target !== subContext.trigger)
            context.onOpenChange(false);
        }),
        onEscapeKeyDown: composeEventHandlers2(props.onEscapeKeyDown, (event) => {
          rootContext.onClose();
          event.preventDefault();
        }),
        onKeyDown: composeEventHandlers2(props.onKeyDown, (event) => {
          const isKeyDownInside = event.currentTarget.contains(event.target);
          const isCloseKey = SUB_CLOSE_KEYS[rootContext.dir].includes(event.key);
          if (isKeyDownInside && isCloseKey) {
            context.onOpenChange(false);
            subContext.trigger?.focus();
            event.preventDefault();
          }
        })
      }
    ) }) }) });
  }
);
MenuSubContent.displayName = SUB_CONTENT_NAME;
function getOpenState(open) {
  return open ? "open" : "closed";
}
function isIndeterminate(checked) {
  return checked === "indeterminate";
}
function getCheckedState(checked) {
  return isIndeterminate(checked) ? "indeterminate" : checked ? "checked" : "unchecked";
}
function focusFirst3(candidates) {
  const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
  for (const candidate of candidates) {
    if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)
      return;
    candidate.focus();
    if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT)
      return;
  }
}
function wrapArray2(array, startIndex) {
  return array.map((_2, index2) => array[(startIndex + index2) % array.length]);
}
function getNextMatch(values, search3, currentMatch) {
  const isRepeated = search3.length > 1 && Array.from(search3).every((char) => char === search3[0]);
  const normalizedSearch = isRepeated ? search3[0] : search3;
  const currentMatchIndex = currentMatch ? values.indexOf(currentMatch) : -1;
  let wrappedValues = wrapArray2(values, Math.max(currentMatchIndex, 0));
  const excludeCurrentMatch = normalizedSearch.length === 1;
  if (excludeCurrentMatch)
    wrappedValues = wrappedValues.filter((v5) => v5 !== currentMatch);
  const nextMatch = wrappedValues.find(
    (value) => value.toLowerCase().startsWith(normalizedSearch.toLowerCase())
  );
  return nextMatch !== currentMatch ? nextMatch : void 0;
}
function isPointInPolygon2(point, polygon) {
  const { x: x2, y: y2 } = point;
  let inside = false;
  for (let i3 = 0, j3 = polygon.length - 1; i3 < polygon.length; j3 = i3++) {
    const xi = polygon[i3].x;
    const yi = polygon[i3].y;
    const xj = polygon[j3].x;
    const yj = polygon[j3].y;
    const intersect2 = yi > y2 !== yj > y2 && x2 < (xj - xi) * (y2 - yi) / (yj - yi) + xi;
    if (intersect2)
      inside = !inside;
  }
  return inside;
}
function isPointerInGraceArea(event, area) {
  if (!area)
    return false;
  const cursorPos = { x: event.clientX, y: event.clientY };
  return isPointInPolygon2(cursorPos, area);
}
function whenMouse(handler) {
  return (event) => event.pointerType === "mouse" ? handler(event) : void 0;
}
var Root32 = Menu;
var Anchor2 = MenuAnchor;
var Portal2 = MenuPortal;
var Content2 = MenuContent;
var Group = MenuGroup;
var Label = MenuLabel;
var Item2 = MenuItem;
var CheckboxItem = MenuCheckboxItem;
var RadioGroup = MenuRadioGroup;
var RadioItem = MenuRadioItem;
var ItemIndicator = MenuItemIndicator;
var Separator = MenuSeparator;
var Arrow22 = MenuArrow;
var SubTrigger = MenuSubTrigger;
var SubContent = MenuSubContent;

// node_modules/@radix-ui/react-dropdown-menu/dist/index.mjs
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
"use client";
var DROPDOWN_MENU_NAME = "DropdownMenu";
var [createDropdownMenuContext, createDropdownMenuScope] = createContextScope(
  DROPDOWN_MENU_NAME,
  [createMenuScope]
);
var useMenuScope = createMenuScope();
var [DropdownMenuProvider, useDropdownMenuContext] = createDropdownMenuContext(DROPDOWN_MENU_NAME);
var DropdownMenu = (props) => {
  const {
    __scopeDropdownMenu,
    children,
    dir,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = true
  } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  const triggerRef = React44.useRef(null);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
    DropdownMenuProvider,
    {
      scope: __scopeDropdownMenu,
      triggerId: useId(),
      triggerRef,
      contentId: useId(),
      open,
      onOpenChange: setOpen,
      onOpenToggle: React44.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      modal,
      children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Root32, { ...menuScope, open, onOpenChange: setOpen, dir, modal, children })
    }
  );
};
DropdownMenu.displayName = DROPDOWN_MENU_NAME;
var TRIGGER_NAME = "DropdownMenuTrigger";
var DropdownMenuTrigger = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, disabled = false, ...triggerProps } = props;
    const context = useDropdownMenuContext(TRIGGER_NAME, __scopeDropdownMenu);
    const menuScope = useMenuScope(__scopeDropdownMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Anchor2, { asChild: true, ...menuScope, children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
      Primitive.button,
      {
        type: "button",
        id: context.triggerId,
        "aria-haspopup": "menu",
        "aria-expanded": context.open,
        "aria-controls": context.open ? context.contentId : void 0,
        "data-state": context.open ? "open" : "closed",
        "data-disabled": disabled ? "" : void 0,
        disabled,
        ...triggerProps,
        ref: composeRefs2(forwardedRef, context.triggerRef),
        onPointerDown: composeEventHandlers(props.onPointerDown, (event) => {
          if (!disabled && event.button === 0 && event.ctrlKey === false) {
            context.onOpenToggle();
            if (!context.open)
              event.preventDefault();
          }
        }),
        onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
          if (disabled)
            return;
          if (["Enter", " "].includes(event.key))
            context.onOpenToggle();
          if (event.key === "ArrowDown")
            context.onOpenChange(true);
          if (["Enter", " ", "ArrowDown"].includes(event.key))
            event.preventDefault();
        })
      }
    ) });
  }
);
DropdownMenuTrigger.displayName = TRIGGER_NAME;
var PORTAL_NAME3 = "DropdownMenuPortal";
var DropdownMenuPortal = (props) => {
  const { __scopeDropdownMenu, ...portalProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Portal2, { ...menuScope, ...portalProps });
};
DropdownMenuPortal.displayName = PORTAL_NAME3;
var CONTENT_NAME3 = "DropdownMenuContent";
var DropdownMenuContent = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, ...contentProps } = props;
    const context = useDropdownMenuContext(CONTENT_NAME3, __scopeDropdownMenu);
    const menuScope = useMenuScope(__scopeDropdownMenu);
    const hasInteractedOutsideRef = React44.useRef(false);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
      Content2,
      {
        id: context.contentId,
        "aria-labelledby": context.triggerId,
        ...menuScope,
        ...contentProps,
        ref: forwardedRef,
        onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => {
          if (!hasInteractedOutsideRef.current)
            context.triggerRef.current?.focus();
          hasInteractedOutsideRef.current = false;
          event.preventDefault();
        }),
        onInteractOutside: composeEventHandlers(props.onInteractOutside, (event) => {
          const originalEvent = event.detail.originalEvent;
          const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
          const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
          if (!context.modal || isRightClick)
            hasInteractedOutsideRef.current = true;
        }),
        style: {
          ...props.style,
          // re-namespace exposed content custom properties
          ...{
            "--radix-dropdown-menu-content-transform-origin": "var(--radix-popper-transform-origin)",
            "--radix-dropdown-menu-content-available-width": "var(--radix-popper-available-width)",
            "--radix-dropdown-menu-content-available-height": "var(--radix-popper-available-height)",
            "--radix-dropdown-menu-trigger-width": "var(--radix-popper-anchor-width)",
            "--radix-dropdown-menu-trigger-height": "var(--radix-popper-anchor-height)"
          }
        }
      }
    );
  }
);
DropdownMenuContent.displayName = CONTENT_NAME3;
var GROUP_NAME3 = "DropdownMenuGroup";
var DropdownMenuGroup = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, ...groupProps } = props;
    const menuScope = useMenuScope(__scopeDropdownMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Group, { ...menuScope, ...groupProps, ref: forwardedRef });
  }
);
DropdownMenuGroup.displayName = GROUP_NAME3;
var LABEL_NAME2 = "DropdownMenuLabel";
var DropdownMenuLabel = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, ...labelProps } = props;
    const menuScope = useMenuScope(__scopeDropdownMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Label, { ...menuScope, ...labelProps, ref: forwardedRef });
  }
);
DropdownMenuLabel.displayName = LABEL_NAME2;
var ITEM_NAME3 = "DropdownMenuItem";
var DropdownMenuItem = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, ...itemProps } = props;
    const menuScope = useMenuScope(__scopeDropdownMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Item2, { ...menuScope, ...itemProps, ref: forwardedRef });
  }
);
DropdownMenuItem.displayName = ITEM_NAME3;
var CHECKBOX_ITEM_NAME2 = "DropdownMenuCheckboxItem";
var DropdownMenuCheckboxItem = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...checkboxItemProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(CheckboxItem, { ...menuScope, ...checkboxItemProps, ref: forwardedRef });
});
DropdownMenuCheckboxItem.displayName = CHECKBOX_ITEM_NAME2;
var RADIO_GROUP_NAME2 = "DropdownMenuRadioGroup";
var DropdownMenuRadioGroup = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...radioGroupProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RadioGroup, { ...menuScope, ...radioGroupProps, ref: forwardedRef });
});
DropdownMenuRadioGroup.displayName = RADIO_GROUP_NAME2;
var RADIO_ITEM_NAME2 = "DropdownMenuRadioItem";
var DropdownMenuRadioItem = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...radioItemProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RadioItem, { ...menuScope, ...radioItemProps, ref: forwardedRef });
});
DropdownMenuRadioItem.displayName = RADIO_ITEM_NAME2;
var INDICATOR_NAME = "DropdownMenuItemIndicator";
var DropdownMenuItemIndicator = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...itemIndicatorProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ItemIndicator, { ...menuScope, ...itemIndicatorProps, ref: forwardedRef });
});
DropdownMenuItemIndicator.displayName = INDICATOR_NAME;
var SEPARATOR_NAME2 = "DropdownMenuSeparator";
var DropdownMenuSeparator = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...separatorProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Separator, { ...menuScope, ...separatorProps, ref: forwardedRef });
});
DropdownMenuSeparator.displayName = SEPARATOR_NAME2;
var ARROW_NAME3 = "DropdownMenuArrow";
var DropdownMenuArrow = React44.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDropdownMenu, ...arrowProps } = props;
    const menuScope = useMenuScope(__scopeDropdownMenu);
    return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Arrow22, { ...menuScope, ...arrowProps, ref: forwardedRef });
  }
);
DropdownMenuArrow.displayName = ARROW_NAME3;
var SUB_TRIGGER_NAME2 = "DropdownMenuSubTrigger";
var DropdownMenuSubTrigger = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...subTriggerProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(SubTrigger, { ...menuScope, ...subTriggerProps, ref: forwardedRef });
});
DropdownMenuSubTrigger.displayName = SUB_TRIGGER_NAME2;
var SUB_CONTENT_NAME2 = "DropdownMenuSubContent";
var DropdownMenuSubContent = React44.forwardRef((props, forwardedRef) => {
  const { __scopeDropdownMenu, ...subContentProps } = props;
  const menuScope = useMenuScope(__scopeDropdownMenu);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
    SubContent,
    {
      ...menuScope,
      ...subContentProps,
      ref: forwardedRef,
      style: {
        ...props.style,
        // re-namespace exposed content custom properties
        ...{
          "--radix-dropdown-menu-content-transform-origin": "var(--radix-popper-transform-origin)",
          "--radix-dropdown-menu-content-available-width": "var(--radix-popper-available-width)",
          "--radix-dropdown-menu-content-available-height": "var(--radix-popper-available-height)",
          "--radix-dropdown-menu-trigger-width": "var(--radix-popper-anchor-width)",
          "--radix-dropdown-menu-trigger-height": "var(--radix-popper-anchor-height)"
        }
      }
    }
  );
});
DropdownMenuSubContent.displayName = SUB_CONTENT_NAME2;
var Root23 = DropdownMenu;
var Trigger = DropdownMenuTrigger;
var Portal22 = DropdownMenuPortal;
var Content22 = DropdownMenuContent;
var Label2 = DropdownMenuLabel;
var Item22 = DropdownMenuItem;
var CheckboxItem2 = DropdownMenuCheckboxItem;
var RadioItem2 = DropdownMenuRadioItem;
var ItemIndicator2 = DropdownMenuItemIndicator;
var Separator2 = DropdownMenuSeparator;
var SubTrigger2 = DropdownMenuSubTrigger;
var SubContent2 = DropdownMenuSubContent;

// src/components/ui/dropdown-menu.tsx
var React45 = __toESM(require_react());
var DropdownMenu2 = Root23;
var DropdownMenuTrigger2 = Trigger;
var DropdownMenuSubTrigger2 = React45.forwardRef(({ className, inset, children, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  SubTrigger2,
  {
    ref,
    className: cn(
      "flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-dropdown-hover data-[state=open]:bg-dropdown-hover [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
      inset && "pl-8",
      className
    ),
    ...props
  },
  children,
  /* @__PURE__ */ React45.createElement(ChevronRight, { className: "ml-auto" })
));
DropdownMenuSubTrigger2.displayName = SubTrigger2.displayName;
var DropdownMenuSubContent2 = React45.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  SubContent2,
  {
    ref,
    className: cn(
      "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-primary p-1 text-normal shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    ),
    ...props
  }
));
DropdownMenuSubContent2.displayName = SubContent2.displayName;
var DropdownMenuContent2 = React45.forwardRef(({ className, sideOffset = 4, ...props }, ref) => /* @__PURE__ */ React45.createElement(Portal22, { container: activeDocument.body }, /* @__PURE__ */ React45.createElement(
  Content22,
  {
    ref,
    sideOffset,
    className: cn(
      "z-50 min-w-[8rem] overflow-hidden rounded-md border border-border border-solid bg-primary p-1 text-normal shadow-md",
      "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    ),
    ...props
  }
)));
DropdownMenuContent2.displayName = Content22.displayName;
var DropdownMenuItem2 = React45.forwardRef(({ className, inset, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  Item22,
  {
    ref,
    className: cn(
      "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-dropdown-hover focus:text-normal data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
      inset && "pl-8",
      className
    ),
    ...props
  }
));
DropdownMenuItem2.displayName = Item22.displayName;
var DropdownMenuCheckboxItem2 = React45.forwardRef(({ className, children, checked, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  CheckboxItem2,
  {
    ref,
    className: cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-dropdown-hover focus:text-normal data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    ),
    checked,
    ...props
  },
  /* @__PURE__ */ React45.createElement("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center" }, /* @__PURE__ */ React45.createElement(ItemIndicator2, null, /* @__PURE__ */ React45.createElement(Check, { className: "h-4 w-4" }))),
  children
));
DropdownMenuCheckboxItem2.displayName = CheckboxItem2.displayName;
var DropdownMenuRadioItem2 = React45.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  RadioItem2,
  {
    ref,
    className: cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-dropdown-hover focus:text-normal data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    ),
    ...props
  },
  /* @__PURE__ */ React45.createElement("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center" }, /* @__PURE__ */ React45.createElement(ItemIndicator2, null, /* @__PURE__ */ React45.createElement(Circle, { className: "h-2 w-2 fill-current" }))),
  children
));
DropdownMenuRadioItem2.displayName = RadioItem2.displayName;
var DropdownMenuLabel2 = React45.forwardRef(({ className, inset, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  Label2,
  {
    ref,
    className: cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className),
    ...props
  }
));
DropdownMenuLabel2.displayName = Label2.displayName;
var DropdownMenuSeparator2 = React45.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React45.createElement(
  Separator2,
  {
    ref,
    className: cn("-mx-1 my-1 h-px bg-muted", className),
    ...props
  }
));
DropdownMenuSeparator2.displayName = Separator2.displayName;
var DropdownMenuShortcut = ({ className, ...props }) => {
  return /* @__PURE__ */ React45.createElement("span", { className: cn("ml-auto text-xs tracking-widest opacity-60", className), ...props });
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";

// src/components/ui/setting-switch.tsx
var React46 = __toESM(require_react());
var SettingSwitch = React46.forwardRef(
  ({ checked = false, onCheckedChange, disabled = false, className, ...props }, ref) => {
    const handleClick = () => {
      if (!disabled) {
        onCheckedChange?.(!checked);
      }
    };
    const handleKeyDown = (event) => {
      if (disabled)
        return;
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        onCheckedChange?.(!checked);
      }
    };
    return /* @__PURE__ */ React46.createElement(
      "div",
      {
        role: "switch",
        "aria-checked": checked,
        "aria-disabled": disabled,
        "data-state": checked ? "checked" : "unchecked",
        "data-disabled": disabled ? "" : void 0,
        ref,
        tabIndex: disabled ? -1 : 0,
        className: cn(
          "relative inline-flex h-5.5 w-10 shrink-0 cursor-pointer items-center rounded-full transition-colors",
          "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
          checked ? "bg-interactive-accent" : "bg-[--background-modifier-border-hover]",
          disabled && "cursor-not-allowed opacity-50",
          className
        ),
        onClick: handleClick,
        onKeyDown: handleKeyDown,
        ...props
      },
      /* @__PURE__ */ React46.createElement(
        "div",
        {
          className: cn(
            "pointer-events-none block h-4 w-4 rounded-full bg-toggle-thumb shadow-lg ring-0 transition-transform",
            checked ? "translate-x-5.5" : "translate-x-0.5"
          )
        }
      )
    );
  }
);
SettingSwitch.displayName = "SettingSwitch";

// src/components/ui/tooltip.tsx
var React59 = __toESM(require_react());

// node_modules/@radix-ui/react-tooltip/dist/index.mjs
var React58 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers4(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React47 = __toESM(require_react(), 1);
function setRef6(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs6(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef6(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef6(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs5(...refs) {
  return React47.useCallback(composeRefs6(...refs), refs);
}

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var React50 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React49 = __toESM(require_react(), 1);
var ReactDOM6 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-slot/dist/index.mjs
var React48 = __toESM(require_react(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var Slot5 = React48.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React48.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable5);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React48.Children.count(newElement) > 1)
          return React48.Children.only(null);
        return React48.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(SlotClone5, { ...slotProps, ref: forwardedRef, children: React48.isValidElement(newElement) ? React48.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(SlotClone5, { ...slotProps, ref: forwardedRef, children });
});
Slot5.displayName = "Slot";
var SlotClone5 = React48.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React48.isValidElement(children)) {
    const childrenRef = getElementRef6(children);
    return React48.cloneElement(children, {
      ...mergeProps5(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs6(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React48.Children.count(children) > 1 ? React48.Children.only(null) : null;
});
SlotClone5.displayName = "SlotClone";
var Slottable5 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(import_jsx_runtime20.Fragment, { children });
};
function isSlottable5(child) {
  return React48.isValidElement(child) && child.type === Slottable5;
}
function mergeProps5(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef6(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var NODES4 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive4 = NODES4.reduce((primitive, node) => {
  const Node3 = React49.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot5 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});
function dispatchDiscreteCustomEvent2(target, event) {
  if (target)
    ReactDOM6.flushSync(() => target.dispatchEvent(event));
}

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
"use client";
var DISMISSABLE_LAYER_NAME2 = "DismissableLayer";
var CONTEXT_UPDATE2 = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE2 = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE2 = "dismissableLayer.focusOutside";
var originalBodyPointerEvents2;
var DismissableLayerContext2 = React50.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer2 = React50.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = React50.useContext(DismissableLayerContext2);
    const [node, setNode] = React50.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = React50.useState({});
    const composedRefs = useComposedRefs5(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside2((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside2((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch)
        return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    React50.useEffect(() => {
      if (!node)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents2 = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate2();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents2;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    React50.useEffect(() => {
      return () => {
        if (!node)
          return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate2();
      };
    }, [node, context]);
    React50.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE2, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE2, handleUpdate);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
      Primitive4.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers4(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers4(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers4(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer2.displayName = DISMISSABLE_LAYER_NAME2;
var BRANCH_NAME2 = "DismissableLayerBranch";
var DismissableLayerBranch2 = React50.forwardRef((props, forwardedRef) => {
  const context = React50.useContext(DismissableLayerContext2);
  const ref = React50.useRef(null);
  const composedRefs = useComposedRefs5(forwardedRef, ref);
  React50.useEffect(() => {
    const node = ref.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Primitive4.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch2.displayName = BRANCH_NAME2;
function usePointerDownOutside2(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
  const isPointerInsideReactTreeRef = React50.useRef(false);
  const handleClickRef = React50.useRef(() => {
  });
  React50.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent2(
            POINTER_DOWN_OUTSIDE2,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside2(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef(onFocusOutside);
  const isFocusInsideReactTreeRef = React50.useRef(false);
  React50.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent2(FOCUS_OUTSIDE2, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate2() {
  const event = new CustomEvent(CONTEXT_UPDATE2);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent2(name, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });
  if (handler)
    target.addEventListener(name, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent2(target, event);
  } else {
    target.dispatchEvent(event);
  }
}

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-popper/dist/index.mjs
var React52 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-arrow/dist/index.mjs
var React51 = __toESM(require_react(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var NAME2 = "Arrow";
var Arrow3 = React51.forwardRef((props, forwardedRef) => {
  const { children, width = 10, height = 5, ...arrowProps } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
    Primitive4.svg,
    {
      ...arrowProps,
      ref: forwardedRef,
      width,
      height,
      viewBox: "0 0 30 10",
      preserveAspectRatio: "none",
      children: props.asChild ? children : /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("polygon", { points: "0,0 30,0 15,10" })
    }
  );
});
Arrow3.displayName = NAME2;
var Root4 = Arrow3;

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-popper/dist/index.mjs
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
"use client";
var POPPER_NAME2 = "Popper";
var [createPopperContext2, createPopperScope2] = createContextScope(POPPER_NAME2);
var [PopperProvider2, usePopperContext2] = createPopperContext2(POPPER_NAME2);
var Popper2 = (props) => {
  const { __scopePopper, children } = props;
  const [anchor, setAnchor] = React52.useState(null);
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(PopperProvider2, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });
};
Popper2.displayName = POPPER_NAME2;
var ANCHOR_NAME3 = "PopperAnchor";
var PopperAnchor2 = React52.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopper, virtualRef, ...anchorProps } = props;
    const context = usePopperContext2(ANCHOR_NAME3, __scopePopper);
    const ref = React52.useRef(null);
    const composedRefs = useComposedRefs5(forwardedRef, ref);
    React52.useEffect(() => {
      context.onAnchorChange(virtualRef?.current || ref.current);
    });
    return virtualRef ? null : /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Primitive4.div, { ...anchorProps, ref: composedRefs });
  }
);
PopperAnchor2.displayName = ANCHOR_NAME3;
var CONTENT_NAME4 = "PopperContent";
var [PopperContentProvider2, useContentContext2] = createPopperContext2(CONTENT_NAME4);
var PopperContent2 = React52.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopper,
      side = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      arrowPadding = 0,
      avoidCollisions = true,
      collisionBoundary = [],
      collisionPadding: collisionPaddingProp = 0,
      sticky = "partial",
      hideWhenDetached = false,
      updatePositionStrategy = "optimized",
      onPlaced,
      ...contentProps
    } = props;
    const context = usePopperContext2(CONTENT_NAME4, __scopePopper);
    const [content, setContent] = React52.useState(null);
    const composedRefs = useComposedRefs5(forwardedRef, (node) => setContent(node));
    const [arrow4, setArrow] = React52.useState(null);
    const arrowSize = useSize(arrow4);
    const arrowWidth = arrowSize?.width ?? 0;
    const arrowHeight = arrowSize?.height ?? 0;
    const desiredPlacement = side + (align !== "center" ? "-" + align : "");
    const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };
    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];
    const hasExplicitBoundaries = boundary.length > 0;
    const detectOverflowOptions = {
      padding: collisionPadding,
      boundary: boundary.filter(isNotNull2),
      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
      altBoundary: hasExplicitBoundaries
    };
    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({
      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
      strategy: "fixed",
      placement: desiredPlacement,
      whileElementsMounted: (...args) => {
        const cleanup = autoUpdate(...args, {
          animationFrame: updatePositionStrategy === "always"
        });
        return cleanup;
      },
      elements: {
        reference: context.anchor
      },
      middleware: [
        offset4({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),
        avoidCollisions && shift3({
          mainAxis: true,
          crossAxis: false,
          limiter: sticky === "partial" ? limitShift3() : void 0,
          ...detectOverflowOptions
        }),
        avoidCollisions && flip3({ ...detectOverflowOptions }),
        size3({
          ...detectOverflowOptions,
          apply: ({ elements, rects, availableWidth, availableHeight }) => {
            const { width: anchorWidth, height: anchorHeight } = rects.reference;
            const contentStyle = elements.floating.style;
            contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`);
            contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`);
            contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`);
            contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`);
          }
        }),
        arrow4 && arrow3({ element: arrow4, padding: arrowPadding }),
        transformOrigin2({ arrowWidth, arrowHeight }),
        hideWhenDetached && hide3({ strategy: "referenceHidden", ...detectOverflowOptions })
      ]
    });
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement2(placement);
    const handlePlaced = useCallbackRef(onPlaced);
    useLayoutEffect2(() => {
      if (isPositioned) {
        handlePlaced?.();
      }
    }, [isPositioned, handlePlaced]);
    const arrowX = middlewareData.arrow?.x;
    const arrowY = middlewareData.arrow?.y;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const [contentZIndex, setContentZIndex] = React52.useState();
    useLayoutEffect2(() => {
      if (content)
        setContentZIndex(window.getComputedStyle(content).zIndex);
    }, [content]);
    return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
      "div",
      {
        ref: refs.setFloating,
        "data-radix-popper-content-wrapper": "",
        style: {
          ...floatingStyles,
          transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)",
          // keep off the page when measuring
          minWidth: "max-content",
          zIndex: contentZIndex,
          ["--radix-popper-transform-origin"]: [
            middlewareData.transformOrigin?.x,
            middlewareData.transformOrigin?.y
          ].join(" "),
          // hide the content if using the hide middleware and should be hidden
          // set visibility to hidden and disable pointer events so the UI behaves
          // as if the PopperContent isn't there at all
          ...middlewareData.hide?.referenceHidden && {
            visibility: "hidden",
            pointerEvents: "none"
          }
        },
        dir: props.dir,
        children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
          PopperContentProvider2,
          {
            scope: __scopePopper,
            placedSide,
            onArrowChange: setArrow,
            arrowX,
            arrowY,
            shouldHideArrow: cannotCenterArrow,
            children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              Primitive4.div,
              {
                "data-side": placedSide,
                "data-align": placedAlign,
                ...contentProps,
                ref: composedRefs,
                style: {
                  ...contentProps.style,
                  // if the PopperContent hasn't been placed yet (not all measurements done)
                  // we prevent animations so that users's animation don't kick in too early referring wrong sides
                  animation: !isPositioned ? "none" : void 0
                }
              }
            )
          }
        )
      }
    );
  }
);
PopperContent2.displayName = CONTENT_NAME4;
var ARROW_NAME4 = "PopperArrow";
var OPPOSITE_SIDE2 = {
  top: "bottom",
  right: "left",
  bottom: "top",
  left: "right"
};
var PopperArrow3 = React52.forwardRef(function PopperArrow22(props, forwardedRef) {
  const { __scopePopper, ...arrowProps } = props;
  const contentContext = useContentContext2(ARROW_NAME4, __scopePopper);
  const baseSide = OPPOSITE_SIDE2[contentContext.placedSide];
  return (
    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
    // doesn't report size as we'd expect on SVG elements.
    // it reports their bounding box which is effectively the largest path inside the SVG.
    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
      "span",
      {
        ref: contentContext.onArrowChange,
        style: {
          position: "absolute",
          left: contentContext.arrowX,
          top: contentContext.arrowY,
          [baseSide]: 0,
          transformOrigin: {
            top: "",
            right: "0 0",
            bottom: "center 0",
            left: "100% 0"
          }[contentContext.placedSide],
          transform: {
            top: "translateY(100%)",
            right: "translateY(50%) rotate(90deg) translateX(-50%)",
            bottom: `rotate(180deg)`,
            left: "translateY(50%) rotate(-90deg) translateX(50%)"
          }[contentContext.placedSide],
          visibility: contentContext.shouldHideArrow ? "hidden" : void 0
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
          Root4,
          {
            ...arrowProps,
            ref: forwardedRef,
            style: {
              ...arrowProps.style,
              // ensures the element can be measured correctly (mostly for if SVG)
              display: "block"
            }
          }
        )
      }
    )
  );
});
PopperArrow3.displayName = ARROW_NAME4;
function isNotNull2(value) {
  return value !== null;
}
var transformOrigin2 = (options) => ({
  name: "transformOrigin",
  options,
  fn(data) {
    const { placement, rects, middlewareData } = data;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const isArrowHidden = cannotCenterArrow;
    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement2(placement);
    const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign];
    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;
    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;
    let x2 = "";
    let y2 = "";
    if (placedSide === "bottom") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${-arrowHeight}px`;
    } else if (placedSide === "top") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${rects.floating.height + arrowHeight}px`;
    } else if (placedSide === "right") {
      x2 = `${-arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    } else if (placedSide === "left") {
      x2 = `${rects.floating.width + arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    }
    return { data: { x: x2, y: y2 } };
  }
});
function getSideAndAlignFromPlacement2(placement) {
  const [side, align = "center"] = placement.split("-");
  return [side, align];
}
var Root24 = Popper2;
var Anchor3 = PopperAnchor2;
var Content3 = PopperContent2;
var Arrow4 = PopperArrow3;

// node_modules/@radix-ui/react-tooltip/node_modules/@radix-ui/react-portal/dist/index.mjs
var React53 = __toESM(require_react(), 1);
var import_react_dom4 = __toESM(require_react_dom(), 1);
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
"use client";
var PORTAL_NAME4 = "Portal";
var Portal3 = React53.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = React53.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? import_react_dom4.default.createPortal(/* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Primitive4.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal3.displayName = PORTAL_NAME4;

// node_modules/@radix-ui/react-visually-hidden/dist/index.mjs
var React57 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-visually-hidden/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React56 = __toESM(require_react(), 1);
var ReactDOM8 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-visually-hidden/node_modules/@radix-ui/react-slot/dist/index.mjs
var React55 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-visually-hidden/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React54 = __toESM(require_react(), 1);
function setRef7(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs7(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef7(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef7(refs[i3], null);
          }
        }
      };
    }
  };
}

// node_modules/@radix-ui/react-visually-hidden/node_modules/@radix-ui/react-slot/dist/index.mjs
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
var Slot6 = React55.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React55.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable6);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React55.Children.count(newElement) > 1)
          return React55.Children.only(null);
        return React55.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(SlotClone6, { ...slotProps, ref: forwardedRef, children: React55.isValidElement(newElement) ? React55.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(SlotClone6, { ...slotProps, ref: forwardedRef, children });
});
Slot6.displayName = "Slot";
var SlotClone6 = React55.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React55.isValidElement(children)) {
    const childrenRef = getElementRef7(children);
    return React55.cloneElement(children, {
      ...mergeProps6(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs7(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React55.Children.count(children) > 1 ? React55.Children.only(null) : null;
});
SlotClone6.displayName = "SlotClone";
var Slottable6 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(import_jsx_runtime26.Fragment, { children });
};
function isSlottable6(child) {
  return React55.isValidElement(child) && child.type === Slottable6;
}
function mergeProps6(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef7(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-visually-hidden/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var NODES5 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive5 = NODES5.reduce((primitive, node) => {
  const Node3 = React56.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot6 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});

// node_modules/@radix-ui/react-visually-hidden/dist/index.mjs
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var NAME3 = "VisuallyHidden";
var VisuallyHidden = React57.forwardRef(
  (props, forwardedRef) => {
    return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
      Primitive5.span,
      {
        ...props,
        ref: forwardedRef,
        style: {
          // See: https://github.com/twbs/bootstrap/blob/main/scss/mixins/_visually-hidden.scss
          position: "absolute",
          border: 0,
          width: 1,
          height: 1,
          padding: 0,
          margin: -1,
          overflow: "hidden",
          clip: "rect(0, 0, 0, 0)",
          whiteSpace: "nowrap",
          wordWrap: "normal",
          ...props.style
        }
      }
    );
  }
);
VisuallyHidden.displayName = NAME3;
var Root5 = VisuallyHidden;

// node_modules/@radix-ui/react-tooltip/dist/index.mjs
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
"use client";
var [createTooltipContext, createTooltipScope] = createContextScope("Tooltip", [
  createPopperScope2
]);
var usePopperScope2 = createPopperScope2();
var PROVIDER_NAME = "TooltipProvider";
var DEFAULT_DELAY_DURATION = 700;
var TOOLTIP_OPEN = "tooltip.open";
var [TooltipProviderContextProvider, useTooltipProviderContext] = createTooltipContext(PROVIDER_NAME);
var TooltipProvider = (props) => {
  const {
    __scopeTooltip,
    delayDuration = DEFAULT_DELAY_DURATION,
    skipDelayDuration = 300,
    disableHoverableContent = false,
    children
  } = props;
  const [isOpenDelayed, setIsOpenDelayed] = React58.useState(true);
  const isPointerInTransitRef = React58.useRef(false);
  const skipDelayTimerRef = React58.useRef(0);
  React58.useEffect(() => {
    const skipDelayTimer = skipDelayTimerRef.current;
    return () => window.clearTimeout(skipDelayTimer);
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
    TooltipProviderContextProvider,
    {
      scope: __scopeTooltip,
      isOpenDelayed,
      delayDuration,
      onOpen: React58.useCallback(() => {
        window.clearTimeout(skipDelayTimerRef.current);
        setIsOpenDelayed(false);
      }, []),
      onClose: React58.useCallback(() => {
        window.clearTimeout(skipDelayTimerRef.current);
        skipDelayTimerRef.current = window.setTimeout(
          () => setIsOpenDelayed(true),
          skipDelayDuration
        );
      }, [skipDelayDuration]),
      isPointerInTransitRef,
      onPointerInTransitChange: React58.useCallback((inTransit) => {
        isPointerInTransitRef.current = inTransit;
      }, []),
      disableHoverableContent,
      children
    }
  );
};
TooltipProvider.displayName = PROVIDER_NAME;
var TOOLTIP_NAME = "Tooltip";
var [TooltipContextProvider, useTooltipContext] = createTooltipContext(TOOLTIP_NAME);
var Tooltip = (props) => {
  const {
    __scopeTooltip,
    children,
    open: openProp,
    defaultOpen = false,
    onOpenChange,
    disableHoverableContent: disableHoverableContentProp,
    delayDuration: delayDurationProp
  } = props;
  const providerContext = useTooltipProviderContext(TOOLTIP_NAME, props.__scopeTooltip);
  const popperScope = usePopperScope2(__scopeTooltip);
  const [trigger, setTrigger] = React58.useState(null);
  const contentId = useId();
  const openTimerRef = React58.useRef(0);
  const disableHoverableContent = disableHoverableContentProp ?? providerContext.disableHoverableContent;
  const delayDuration = delayDurationProp ?? providerContext.delayDuration;
  const wasOpenDelayedRef = React58.useRef(false);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: (open2) => {
      if (open2) {
        providerContext.onOpen();
        document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));
      } else {
        providerContext.onClose();
      }
      onOpenChange?.(open2);
    }
  });
  const stateAttribute = React58.useMemo(() => {
    return open ? wasOpenDelayedRef.current ? "delayed-open" : "instant-open" : "closed";
  }, [open]);
  const handleOpen = React58.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = 0;
    wasOpenDelayedRef.current = false;
    setOpen(true);
  }, [setOpen]);
  const handleClose = React58.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = 0;
    setOpen(false);
  }, [setOpen]);
  const handleDelayedOpen = React58.useCallback(() => {
    window.clearTimeout(openTimerRef.current);
    openTimerRef.current = window.setTimeout(() => {
      wasOpenDelayedRef.current = true;
      setOpen(true);
      openTimerRef.current = 0;
    }, delayDuration);
  }, [delayDuration, setOpen]);
  React58.useEffect(() => {
    return () => {
      if (openTimerRef.current) {
        window.clearTimeout(openTimerRef.current);
        openTimerRef.current = 0;
      }
    };
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Root24, { ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
    TooltipContextProvider,
    {
      scope: __scopeTooltip,
      contentId,
      open,
      stateAttribute,
      trigger,
      onTriggerChange: setTrigger,
      onTriggerEnter: React58.useCallback(() => {
        if (providerContext.isOpenDelayed)
          handleDelayedOpen();
        else
          handleOpen();
      }, [providerContext.isOpenDelayed, handleDelayedOpen, handleOpen]),
      onTriggerLeave: React58.useCallback(() => {
        if (disableHoverableContent) {
          handleClose();
        } else {
          window.clearTimeout(openTimerRef.current);
          openTimerRef.current = 0;
        }
      }, [handleClose, disableHoverableContent]),
      onOpen: handleOpen,
      onClose: handleClose,
      disableHoverableContent,
      children
    }
  ) });
};
Tooltip.displayName = TOOLTIP_NAME;
var TRIGGER_NAME2 = "TooltipTrigger";
var TooltipTrigger = React58.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTooltip, ...triggerProps } = props;
    const context = useTooltipContext(TRIGGER_NAME2, __scopeTooltip);
    const providerContext = useTooltipProviderContext(TRIGGER_NAME2, __scopeTooltip);
    const popperScope = usePopperScope2(__scopeTooltip);
    const ref = React58.useRef(null);
    const composedRefs = useComposedRefs5(forwardedRef, ref, context.onTriggerChange);
    const isPointerDownRef = React58.useRef(false);
    const hasPointerMoveOpenedRef = React58.useRef(false);
    const handlePointerUp = React58.useCallback(() => isPointerDownRef.current = false, []);
    React58.useEffect(() => {
      return () => document.removeEventListener("pointerup", handlePointerUp);
    }, [handlePointerUp]);
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Anchor3, { asChild: true, ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
      Primitive4.button,
      {
        "aria-describedby": context.open ? context.contentId : void 0,
        "data-state": context.stateAttribute,
        ...triggerProps,
        ref: composedRefs,
        onPointerMove: composeEventHandlers4(props.onPointerMove, (event) => {
          if (event.pointerType === "touch")
            return;
          if (!hasPointerMoveOpenedRef.current && !providerContext.isPointerInTransitRef.current) {
            context.onTriggerEnter();
            hasPointerMoveOpenedRef.current = true;
          }
        }),
        onPointerLeave: composeEventHandlers4(props.onPointerLeave, () => {
          context.onTriggerLeave();
          hasPointerMoveOpenedRef.current = false;
        }),
        onPointerDown: composeEventHandlers4(props.onPointerDown, () => {
          isPointerDownRef.current = true;
          document.addEventListener("pointerup", handlePointerUp, { once: true });
        }),
        onFocus: composeEventHandlers4(props.onFocus, () => {
          if (!isPointerDownRef.current)
            context.onOpen();
        }),
        onBlur: composeEventHandlers4(props.onBlur, context.onClose),
        onClick: composeEventHandlers4(props.onClick, context.onClose)
      }
    ) });
  }
);
TooltipTrigger.displayName = TRIGGER_NAME2;
var PORTAL_NAME5 = "TooltipPortal";
var [PortalProvider2, usePortalContext2] = createTooltipContext(PORTAL_NAME5, {
  forceMount: void 0
});
var TooltipPortal = (props) => {
  const { __scopeTooltip, forceMount, children, container } = props;
  const context = useTooltipContext(PORTAL_NAME5, __scopeTooltip);
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(PortalProvider2, { scope: __scopeTooltip, forceMount, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Portal3, { asChild: true, container, children }) }) });
};
TooltipPortal.displayName = PORTAL_NAME5;
var CONTENT_NAME5 = "TooltipContent";
var TooltipContent = React58.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext2(CONTENT_NAME5, props.__scopeTooltip);
    const { forceMount = portalContext.forceMount, side = "top", ...contentProps } = props;
    const context = useTooltipContext(CONTENT_NAME5, props.__scopeTooltip);
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Presence, { present: forceMount || context.open, children: context.disableHoverableContent ? /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(TooltipContentImpl, { side, ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(TooltipContentHoverable, { side, ...contentProps, ref: forwardedRef }) });
  }
);
var TooltipContentHoverable = React58.forwardRef((props, forwardedRef) => {
  const context = useTooltipContext(CONTENT_NAME5, props.__scopeTooltip);
  const providerContext = useTooltipProviderContext(CONTENT_NAME5, props.__scopeTooltip);
  const ref = React58.useRef(null);
  const composedRefs = useComposedRefs5(forwardedRef, ref);
  const [pointerGraceArea, setPointerGraceArea] = React58.useState(null);
  const { trigger, onClose } = context;
  const content = ref.current;
  const { onPointerInTransitChange } = providerContext;
  const handleRemoveGraceArea = React58.useCallback(() => {
    setPointerGraceArea(null);
    onPointerInTransitChange(false);
  }, [onPointerInTransitChange]);
  const handleCreateGraceArea = React58.useCallback(
    (event, hoverTarget) => {
      const currentTarget = event.currentTarget;
      const exitPoint = { x: event.clientX, y: event.clientY };
      const exitSide = getExitSideFromRect(exitPoint, currentTarget.getBoundingClientRect());
      const paddedExitPoints = getPaddedExitPoints(exitPoint, exitSide);
      const hoverTargetPoints = getPointsFromRect(hoverTarget.getBoundingClientRect());
      const graceArea = getHull([...paddedExitPoints, ...hoverTargetPoints]);
      setPointerGraceArea(graceArea);
      onPointerInTransitChange(true);
    },
    [onPointerInTransitChange]
  );
  React58.useEffect(() => {
    return () => handleRemoveGraceArea();
  }, [handleRemoveGraceArea]);
  React58.useEffect(() => {
    if (trigger && content) {
      const handleTriggerLeave = (event) => handleCreateGraceArea(event, content);
      const handleContentLeave = (event) => handleCreateGraceArea(event, trigger);
      trigger.addEventListener("pointerleave", handleTriggerLeave);
      content.addEventListener("pointerleave", handleContentLeave);
      return () => {
        trigger.removeEventListener("pointerleave", handleTriggerLeave);
        content.removeEventListener("pointerleave", handleContentLeave);
      };
    }
  }, [trigger, content, handleCreateGraceArea, handleRemoveGraceArea]);
  React58.useEffect(() => {
    if (pointerGraceArea) {
      const handleTrackPointerGrace = (event) => {
        const target = event.target;
        const pointerPosition = { x: event.clientX, y: event.clientY };
        const hasEnteredTarget = trigger?.contains(target) || content?.contains(target);
        const isPointerOutsideGraceArea = !isPointInPolygon3(pointerPosition, pointerGraceArea);
        if (hasEnteredTarget) {
          handleRemoveGraceArea();
        } else if (isPointerOutsideGraceArea) {
          handleRemoveGraceArea();
          onClose();
        }
      };
      document.addEventListener("pointermove", handleTrackPointerGrace);
      return () => document.removeEventListener("pointermove", handleTrackPointerGrace);
    }
  }, [trigger, content, pointerGraceArea, onClose, handleRemoveGraceArea]);
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(TooltipContentImpl, { ...props, ref: composedRefs });
});
var [VisuallyHiddenContentContextProvider, useVisuallyHiddenContentContext] = createTooltipContext(TOOLTIP_NAME, { isInside: false });
var TooltipContentImpl = React58.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeTooltip,
      children,
      "aria-label": ariaLabel,
      onEscapeKeyDown,
      onPointerDownOutside,
      ...contentProps
    } = props;
    const context = useTooltipContext(CONTENT_NAME5, __scopeTooltip);
    const popperScope = usePopperScope2(__scopeTooltip);
    const { onClose } = context;
    React58.useEffect(() => {
      document.addEventListener(TOOLTIP_OPEN, onClose);
      return () => document.removeEventListener(TOOLTIP_OPEN, onClose);
    }, [onClose]);
    React58.useEffect(() => {
      if (context.trigger) {
        const handleScroll4 = (event) => {
          const target = event.target;
          if (target?.contains(context.trigger))
            onClose();
        };
        window.addEventListener("scroll", handleScroll4, { capture: true });
        return () => window.removeEventListener("scroll", handleScroll4, { capture: true });
      }
    }, [context.trigger, onClose]);
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
      DismissableLayer2,
      {
        asChild: true,
        disableOutsidePointerEvents: false,
        onEscapeKeyDown,
        onPointerDownOutside,
        onFocusOutside: (event) => event.preventDefault(),
        onDismiss: onClose,
        children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          Content3,
          {
            "data-state": context.stateAttribute,
            ...popperScope,
            ...contentProps,
            ref: forwardedRef,
            style: {
              ...contentProps.style,
              // re-namespace exposed content custom properties
              ...{
                "--radix-tooltip-content-transform-origin": "var(--radix-popper-transform-origin)",
                "--radix-tooltip-content-available-width": "var(--radix-popper-available-width)",
                "--radix-tooltip-content-available-height": "var(--radix-popper-available-height)",
                "--radix-tooltip-trigger-width": "var(--radix-popper-anchor-width)",
                "--radix-tooltip-trigger-height": "var(--radix-popper-anchor-height)"
              }
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Slottable5, { children }),
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(VisuallyHiddenContentContextProvider, { scope: __scopeTooltip, isInside: true, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Root5, { id: context.contentId, role: "tooltip", children: ariaLabel || children }) })
            ]
          }
        )
      }
    );
  }
);
TooltipContent.displayName = CONTENT_NAME5;
var ARROW_NAME5 = "TooltipArrow";
var TooltipArrow = React58.forwardRef(
  (props, forwardedRef) => {
    const { __scopeTooltip, ...arrowProps } = props;
    const popperScope = usePopperScope2(__scopeTooltip);
    const visuallyHiddenContentContext = useVisuallyHiddenContentContext(
      ARROW_NAME5,
      __scopeTooltip
    );
    return visuallyHiddenContentContext.isInside ? null : /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Arrow4, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
TooltipArrow.displayName = ARROW_NAME5;
function getExitSideFromRect(point, rect) {
  const top = Math.abs(rect.top - point.y);
  const bottom = Math.abs(rect.bottom - point.y);
  const right = Math.abs(rect.right - point.x);
  const left = Math.abs(rect.left - point.x);
  switch (Math.min(top, bottom, right, left)) {
    case left:
      return "left";
    case right:
      return "right";
    case top:
      return "top";
    case bottom:
      return "bottom";
    default:
      throw new Error("unreachable");
  }
}
function getPaddedExitPoints(exitPoint, exitSide, padding = 5) {
  const paddedExitPoints = [];
  switch (exitSide) {
    case "top":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y + padding },
        { x: exitPoint.x + padding, y: exitPoint.y + padding }
      );
      break;
    case "bottom":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y - padding },
        { x: exitPoint.x + padding, y: exitPoint.y - padding }
      );
      break;
    case "left":
      paddedExitPoints.push(
        { x: exitPoint.x + padding, y: exitPoint.y - padding },
        { x: exitPoint.x + padding, y: exitPoint.y + padding }
      );
      break;
    case "right":
      paddedExitPoints.push(
        { x: exitPoint.x - padding, y: exitPoint.y - padding },
        { x: exitPoint.x - padding, y: exitPoint.y + padding }
      );
      break;
  }
  return paddedExitPoints;
}
function getPointsFromRect(rect) {
  const { top, right, bottom, left } = rect;
  return [
    { x: left, y: top },
    { x: right, y: top },
    { x: right, y: bottom },
    { x: left, y: bottom }
  ];
}
function isPointInPolygon3(point, polygon) {
  const { x: x2, y: y2 } = point;
  let inside = false;
  for (let i3 = 0, j3 = polygon.length - 1; i3 < polygon.length; j3 = i3++) {
    const xi = polygon[i3].x;
    const yi = polygon[i3].y;
    const xj = polygon[j3].x;
    const yj = polygon[j3].y;
    const intersect2 = yi > y2 !== yj > y2 && x2 < (xj - xi) * (y2 - yi) / (yj - yi) + xi;
    if (intersect2)
      inside = !inside;
  }
  return inside;
}
function getHull(points) {
  const newPoints = points.slice();
  newPoints.sort((a3, b3) => {
    if (a3.x < b3.x)
      return -1;
    else if (a3.x > b3.x)
      return 1;
    else if (a3.y < b3.y)
      return -1;
    else if (a3.y > b3.y)
      return 1;
    else
      return 0;
  });
  return getHullPresorted(newPoints);
}
function getHullPresorted(points) {
  if (points.length <= 1)
    return points.slice();
  const upperHull = [];
  for (let i3 = 0; i3 < points.length; i3++) {
    const p3 = points[i3];
    while (upperHull.length >= 2) {
      const q3 = upperHull[upperHull.length - 1];
      const r4 = upperHull[upperHull.length - 2];
      if ((q3.x - r4.x) * (p3.y - r4.y) >= (q3.y - r4.y) * (p3.x - r4.x))
        upperHull.pop();
      else
        break;
    }
    upperHull.push(p3);
  }
  upperHull.pop();
  const lowerHull = [];
  for (let i3 = points.length - 1; i3 >= 0; i3--) {
    const p3 = points[i3];
    while (lowerHull.length >= 2) {
      const q3 = lowerHull[lowerHull.length - 1];
      const r4 = lowerHull[lowerHull.length - 2];
      if ((q3.x - r4.x) * (p3.y - r4.y) >= (q3.y - r4.y) * (p3.x - r4.x))
        lowerHull.pop();
      else
        break;
    }
    lowerHull.push(p3);
  }
  lowerHull.pop();
  if (upperHull.length === 1 && lowerHull.length === 1 && upperHull[0].x === lowerHull[0].x && upperHull[0].y === lowerHull[0].y) {
    return upperHull;
  } else {
    return upperHull.concat(lowerHull);
  }
}
var Provider2 = TooltipProvider;
var Root33 = Tooltip;
var Trigger2 = TooltipTrigger;
var Portal4 = TooltipPortal;
var Content23 = TooltipContent;

// src/components/ui/tooltip.tsx
var TooltipProvider2 = Provider2;
var Tooltip2 = Root33;
var TooltipTrigger2 = Trigger2;
var TooltipContent2 = React59.forwardRef(({ className, sideOffset = 4, ...props }, ref) => /* @__PURE__ */ React59.createElement(Portal4, { container: activeDocument.body }, /* @__PURE__ */ React59.createElement(
  Content23,
  {
    ref,
    sideOffset,
    className: cn(
      "z-50 overflow-hidden rounded-md bg-secondary border-border border border-solid px-3 py-1.5 text-xs text-normal animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    ),
    ...props
  }
)));
TooltipContent2.displayName = Content23.displayName;

// src/components/chat-components/ChatControls.tsx
var import_obsidian27 = require("obsidian");
async function refreshVaultIndex() {
  try {
    await VectorStoreManager.getInstance().indexVaultToVectorStore();
    new import_obsidian27.Notice("Vault index refreshed.");
  } catch (error) {
    console.error("Error refreshing vault index:", error);
    new import_obsidian27.Notice("Failed to refresh vault index. Check console for details.");
  }
}
function ChatControls({ onNewChat, onSaveAsNote }) {
  const settings = useSettingsValue();
  const [selectedChain, setSelectedChain] = useChainType();
  const isPlusUser = useIsPlusUser();
  return /* @__PURE__ */ import_react10.default.createElement("div", { className: "w-full py-1 flex justify-between items-center px-1" }, /* @__PURE__ */ import_react10.default.createElement("div", { className: "flex-1" }, /* @__PURE__ */ import_react10.default.createElement(DropdownMenu, null, /* @__PURE__ */ import_react10.default.createElement(DropdownMenuTrigger, { asChild: true }, /* @__PURE__ */ import_react10.default.createElement(Button, { variant: "ghost2", size: "fit", className: "ml-1" }, selectedChain === "llm_chain" /* LLM_CHAIN */ && "chat", selectedChain === "vault_qa" /* VAULT_QA_CHAIN */ && "vault QA", selectedChain === "copilot_plus" /* COPILOT_PLUS_CHAIN */ && /* @__PURE__ */ import_react10.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react10.default.createElement(Sparkles, { className: "size-4" }), "copilot plus (beta)"), /* @__PURE__ */ import_react10.default.createElement(ChevronDown, { className: "size-5 mt-0.5" }))), /* @__PURE__ */ import_react10.default.createElement(DropdownMenuContent2, { align: "start" }, /* @__PURE__ */ import_react10.default.createElement(DropdownMenuItem2, { onSelect: () => setSelectedChain("llm_chain" /* LLM_CHAIN */) }, "chat"), /* @__PURE__ */ import_react10.default.createElement(DropdownMenuItem2, { onSelect: () => setSelectedChain("vault_qa" /* VAULT_QA_CHAIN */) }, "vault QA"), isPlusUser ? /* @__PURE__ */ import_react10.default.createElement(DropdownMenuItem2, { onSelect: () => setSelectedChain("copilot_plus" /* COPILOT_PLUS_CHAIN */) }, /* @__PURE__ */ import_react10.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react10.default.createElement(Sparkles, { className: "size-4" }), "copilot plus (beta)")) : /* @__PURE__ */ import_react10.default.createElement(
    DropdownMenuItem2,
    {
      onSelect: () => {
        navigateToPlusPage(PLUS_UTM_MEDIUMS.CHAT_MODE_SELECT);
      }
    },
    "copilot plus (beta)",
    /* @__PURE__ */ import_react10.default.createElement(SquareArrowOutUpRight, { className: "size-3" })
  )))), /* @__PURE__ */ import_react10.default.createElement("div", null, /* @__PURE__ */ import_react10.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react10.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react10.default.createElement(Button, { variant: "ghost2", size: "icon", title: "New Chat", onClick: onNewChat }, /* @__PURE__ */ import_react10.default.createElement(MessageCirclePlus, { className: "size-4" }))), /* @__PURE__ */ import_react10.default.createElement(TooltipContent2, null, "New Chat")), /* @__PURE__ */ import_react10.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react10.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react10.default.createElement(Button, { variant: "ghost2", size: "icon", title: "Save Chat as Note", onClick: onSaveAsNote }, /* @__PURE__ */ import_react10.default.createElement(Download, { className: "size-4" }))), /* @__PURE__ */ import_react10.default.createElement(TooltipContent2, null, "Save Chat as Note")), /* @__PURE__ */ import_react10.default.createElement(DropdownMenu, null, /* @__PURE__ */ import_react10.default.createElement(DropdownMenuTrigger, { asChild: true }, /* @__PURE__ */ import_react10.default.createElement(Button, { variant: "ghost2", size: "icon", title: "Advanced Settings" }, /* @__PURE__ */ import_react10.default.createElement(Ellipsis, { className: "size-4" }))), /* @__PURE__ */ import_react10.default.createElement(DropdownMenuContent2, { align: "end", className: "w-64" }, /* @__PURE__ */ import_react10.default.createElement(
    DropdownMenuItem2,
    {
      className: "flex justify-between",
      onSelect: (e3) => {
        e3.preventDefault();
        updateSetting("showSuggestedPrompts", !settings.showSuggestedPrompts);
      }
    },
    /* @__PURE__ */ import_react10.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react10.default.createElement(Sparkles, { className: "size-4" }), "Suggested Prompt"),
    /* @__PURE__ */ import_react10.default.createElement(SettingSwitch, { checked: settings.showSuggestedPrompts })
  ), /* @__PURE__ */ import_react10.default.createElement(
    DropdownMenuItem2,
    {
      className: "flex justify-between",
      onSelect: (e3) => {
        e3.preventDefault();
        updateSetting("showRelevantNotes", !settings.showRelevantNotes);
      }
    },
    /* @__PURE__ */ import_react10.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react10.default.createElement(FileText, { className: "size-4" }), "Relevant Note"),
    /* @__PURE__ */ import_react10.default.createElement(SettingSwitch, { checked: settings.showRelevantNotes })
  ), /* @__PURE__ */ import_react10.default.createElement(
    DropdownMenuItem2,
    {
      className: "flex items-center gap-2",
      onSelect: () => refreshVaultIndex()
    },
    /* @__PURE__ */ import_react10.default.createElement(RefreshCw, { className: "size-4" }),
    "Refresh Vault Index"
  )))));
}

// src/components/modals/AddImageModal.tsx
var AddImageModal = class {
  constructor(app2, onImagesSelected) {
    this.app = app2;
    this.onImagesSelected = onImagesSelected;
  }
  open() {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.multiple = true;
    input.style.display = "none";
    input.addEventListener("change", () => {
      const files = Array.from(input.files || []);
      this.onImagesSelected(files);
      document.body.removeChild(input);
    });
    document.body.appendChild(input);
    input.click();
  }
};

// src/contextProcessor.ts
var import_obsidian28 = require("obsidian");
var ContextProcessor = class {
  constructor() {
  }
  static getInstance() {
    if (!ContextProcessor.instance) {
      ContextProcessor.instance = new ContextProcessor();
    }
    return ContextProcessor.instance;
  }
  async processEmbeddedPDFs(content, vault, fileParserManager) {
    const pdfRegex = /!\[\[(.*?\.pdf)\]\]/g;
    const matches = [...content.matchAll(pdfRegex)];
    for (const match2 of matches) {
      const pdfName = match2[1];
      const pdfFile = vault.getAbstractFileByPath(pdfName);
      if (pdfFile instanceof import_obsidian28.TFile) {
        try {
          const pdfContent = await fileParserManager.parseFile(pdfFile, vault);
          content = content.replace(match2[0], `

Embedded PDF (${pdfName}):
${pdfContent}

`);
        } catch (error) {
          console.error(`Error processing embedded PDF ${pdfName}:`, error);
          content = content.replace(
            match2[0],
            `

Embedded PDF (${pdfName}): [Error: Could not process PDF]

`
          );
        }
      }
    }
    return content;
  }
  async processContextNotes(customPromptProcessor, fileParserManager, vault, contextNotes, includeActiveNote, activeNote, currentChain) {
    const processedVars = await customPromptProcessor.getProcessedVariables();
    let additionalContext = "";
    const processNote = async (note) => {
      try {
        if (currentChain !== "copilot_plus" /* COPILOT_PLUS_CHAIN */ && note.extension !== "md") {
          if (!fileParserManager.supportsExtension(note.extension)) {
            console.warn(`Unsupported file type: ${note.extension}`);
          } else {
            console.warn(`File type ${note.extension} only supported in Copilot Plus mode`);
          }
          return;
        }
        if (!fileParserManager.supportsExtension(note.extension)) {
          console.warn(`Unsupported file type: ${note.extension}`);
          return;
        }
        let content = await fileParserManager.parseFile(note, vault);
        if (note.extension === "md" && currentChain === "copilot_plus" /* COPILOT_PLUS_CHAIN */) {
          content = await this.processEmbeddedPDFs(content, vault, fileParserManager);
        }
        additionalContext += `

[[${note.basename}.${note.extension}]]:

${content}`;
      } catch (error) {
        console.error(`Error processing file ${note.path}:`, error);
        additionalContext += `

[[${note.basename}]]: [Error: Could not process file]`;
      }
    };
    if (includeActiveNote && activeNote) {
      const activeNoteVar = `activeNote`;
      const activeNotePath = `[[${activeNote.basename}]]`;
      if (!processedVars.has(activeNoteVar) && !processedVars.has(activeNotePath)) {
        await processNote(activeNote);
      }
    }
    for (const note of contextNotes) {
      await processNote(note);
    }
    return additionalContext;
  }
  async hasEmbeddedPDFs(content) {
    const pdfRegex = /!\[\[(.*?\.pdf)\]\]/g;
    return pdfRegex.test(content);
  }
  async addNoteToContext(note, vault, contextNotes, activeNote, setContextNotes, setIncludeActiveNote) {
    if (contextNotes.some((existing) => existing.path === note.path) || activeNote && note.path === activeNote.path) {
      return;
    }
    const content = await vault.read(note);
    const hasEmbeddedPDFs = await this.hasEmbeddedPDFs(content);
    if (activeNote && note.path === activeNote.path) {
      setIncludeActiveNote(true);
    } else {
      setContextNotes((prev) => [
        ...prev,
        Object.assign(note, {
          wasAddedViaReference: true,
          hasEmbeddedPDFs
        })
      ]);
    }
  }
};

// src/components/chat-components/ChatInput.tsx
var import_obsidian30 = require("obsidian");
var import_react14 = __toESM(require_react());

// src/components/chat-components/ContextControl.tsx
var import_react12 = __toESM(require_react());

// src/components/modals/BaseNoteModal.tsx
var import_obsidian29 = require("obsidian");
var BaseNoteModal = class extends import_obsidian29.FuzzySuggestModal {
  constructor(app2) {
    super(app2);
    this.activeNote = app2.workspace.getActiveFile();
  }
  getOrderedNotes(excludeNotePaths = []) {
    const recentFiles = this.app.workspace.getLastOpenFiles().map((filePath) => this.app.vault.getAbstractFileByPath(filePath)).filter(
      (file) => file instanceof import_obsidian29.TFile && (file.extension === "md" || file.extension === "pdf") && !excludeNotePaths.includes(file.path) && file.path !== this.activeNote?.path
    );
    const allFiles = this.app.vault.getFiles().filter((file) => file.extension === "md" || file.extension === "pdf");
    const otherFiles = allFiles.filter(
      (file) => !recentFiles.some((recent) => recent.path === file.path) && !excludeNotePaths.includes(file.path) && file.path !== this.activeNote?.path
    );
    return [...this.activeNote ? [this.activeNote] : [], ...recentFiles, ...otherFiles];
  }
  formatNoteTitle(basename, isActive, extension) {
    let title = basename;
    if (isActive) {
      title += " (current)";
    }
    if (extension === "pdf") {
      title += " (PDF)";
    }
    return title;
  }
  renderSuggestion(match2, el) {
    const suggestionEl = el.createDiv({ cls: "suggestion-item pointer-events-none" });
    const titleEl = suggestionEl.createDiv({ cls: "suggestion-title" });
    const pathEl = suggestionEl.createDiv({ cls: "suggestion-path mt-1 text-muted text-xs" });
    if (match2.item instanceof import_obsidian29.TFile) {
      const file = match2.item;
      titleEl.setText(
        this.formatNoteTitle(file.basename, file === this.activeNote, file.extension)
      );
      pathEl.setText(file.path);
    }
  }
};

// src/components/modals/AddContextNoteModal.tsx
var AddContextNoteModal = class extends BaseNoteModal {
  constructor({ app: app2, onNoteSelect, excludeNotePaths }) {
    super(app2);
    this.onNoteSelect = onNoteSelect;
    this.availableNotes = this.getOrderedNotes(excludeNotePaths);
  }
  getItems() {
    return this.availableNotes;
  }
  getItemText(note) {
    const isActive = note.path === this.activeNote?.path;
    return this.formatNoteTitle(note.basename, isActive, note.extension);
  }
  onChooseItem(note, evt) {
    this.onNoteSelect(note);
  }
};

// src/components/chat-components/ChatContextMenu.tsx
var import_react11 = __toESM(require_react());

// src/components/ui/badge.tsx
var React61 = __toESM(require_react());
var badgeVariants = cva(
  "inline-flex items-center rounded-md px-2.5 py-0.5 text-normal text-ui-smaller transition-colors focus:outline-none",
  {
    variants: {
      variant: {
        default: "bg-primary-alt shadow",
        secondary: "bg-secondary-alt",
        destructive: "bg-modifier-error shadow",
        outline: "border border-border border-solid"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
);
var Badge = React61.forwardRef(
  ({ className, variant, ...props }, ref) => /* @__PURE__ */ React61.createElement("div", { ref, className: cn(badgeVariants({ variant }), className), ...props })
);
Badge.displayName = "Badge";

// src/components/chat-components/ChatContextMenu.tsx
function ContextNote({
  note,
  isActive = false,
  onRemoveContext
}) {
  return /* @__PURE__ */ import_react11.default.createElement(Badge, { className: "text-xs pl-2 pr-0.5 py-0 items-center" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react11.default.createElement("span", { className: "max-w-40 truncate" }, note.basename), isActive && /* @__PURE__ */ import_react11.default.createElement("span", { className: "text-xs text-faint" }, "Current"), note.extension === "pdf" && /* @__PURE__ */ import_react11.default.createElement("span", { className: "text-xs text-faint" }, "pdf")), /* @__PURE__ */ import_react11.default.createElement(
    Button,
    {
      variant: "ghost2",
      size: "fit",
      onClick: () => onRemoveContext(note.path),
      "aria-label": "Remove from context"
    },
    /* @__PURE__ */ import_react11.default.createElement(X, { className: "size-4" })
  ));
}
function ContextUrl({ url, onRemoveUrl }) {
  return /* @__PURE__ */ import_react11.default.createElement(Badge, { className: "text-xs pl-2 pr-0.5 py-0 items-center" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react11.default.createElement("span", { className: "max-w-40 truncate" }, url), /* @__PURE__ */ import_react11.default.createElement("span", { className: "text-xs text-faint" }, "Link")), /* @__PURE__ */ import_react11.default.createElement(
    Button,
    {
      variant: "ghost2",
      size: "fit",
      onClick: () => onRemoveUrl(url),
      "aria-label": "Remove from context"
    },
    /* @__PURE__ */ import_react11.default.createElement(X, { className: "size-4" })
  ));
}
var ChatContextMenu = ({
  activeNote,
  contextNotes,
  contextUrls,
  onAddContext,
  onRemoveContext,
  onRemoveUrl
}) => {
  const uniqueNotes = import_react11.default.useMemo(() => {
    const notesMap = new Map(contextNotes.map((note) => [note.path, note]));
    return Array.from(notesMap.values()).filter((note) => {
      if (note.wasAddedManually) {
        return true;
      }
      return !(activeNote && note.path === activeNote.path);
    });
  }, [contextNotes, activeNote]);
  const uniqueUrls = import_react11.default.useMemo(() => Array.from(new Set(contextUrls)), [contextUrls]);
  const hasContext = uniqueNotes.length > 0 || uniqueUrls.length > 0 || !!activeNote;
  return /* @__PURE__ */ import_react11.default.createElement("div", { className: "flex items-center w-full gap-1" }, /* @__PURE__ */ import_react11.default.createElement("div", { className: "flex items-start h-full" }, /* @__PURE__ */ import_react11.default.createElement(
    Button,
    {
      onClick: onAddContext,
      variant: "ghost2",
      size: "fit",
      className: "border border-border border-solid rounded-sm ml-1"
    },
    /* @__PURE__ */ import_react11.default.createElement(Plus, { className: "size-4" }),
    !hasContext && /* @__PURE__ */ import_react11.default.createElement("span", { className: "text-xs leading-4 pr-1" }, "Add context")
  )), /* @__PURE__ */ import_react11.default.createElement("div", { className: "flex gap-1 flex-wrap flex-1" }, activeNote && /* @__PURE__ */ import_react11.default.createElement(
    ContextNote,
    {
      key: activeNote.path,
      note: activeNote,
      isActive: true,
      onRemoveContext
    }
  ), uniqueNotes.map((note) => /* @__PURE__ */ import_react11.default.createElement(
    ContextNote,
    {
      key: note.path,
      note,
      isActive: false,
      onRemoveContext
    }
  )), uniqueUrls.map((url) => /* @__PURE__ */ import_react11.default.createElement(ContextUrl, { key: url, url, onRemoveUrl }))));
};

// src/components/chat-components/ContextControl.tsx
var ContextControl = ({
  app: app2,
  excludeNotePaths,
  contextNotes,
  setContextNotes,
  includeActiveNote,
  setIncludeActiveNote,
  activeNote,
  contextUrls,
  onRemoveUrl
}) => {
  const [selectedChain] = useChainType();
  const handleAddContext = () => {
    new AddContextNoteModal({
      app: app2,
      onNoteSelect: (note) => {
        if (activeNote && note.path === activeNote.path) {
          setIncludeActiveNote(true);
          setContextNotes((prev) => prev.filter((n4) => n4.path !== note.path));
        } else {
          setContextNotes((prev) => [...prev, Object.assign(note, { wasAddedManually: true })]);
        }
      },
      excludeNotePaths
    }).open();
  };
  const handleRemoveContext = (path) => {
    const noteToRemove = contextNotes.find((note) => note.path === path);
    const wasAddedManually = noteToRemove && noteToRemove.wasAddedManually;
    if (wasAddedManually) {
      setContextNotes((prev) => prev.filter((note) => note.path !== path));
    } else {
      setIncludeActiveNote(false);
      setContextNotes((prev) => prev.filter((note) => note.path !== path));
    }
  };
  if (selectedChain !== "copilot_plus" /* COPILOT_PLUS_CHAIN */) {
    return null;
  }
  return /* @__PURE__ */ import_react12.default.createElement(
    ChatContextMenu,
    {
      activeNote: includeActiveNote ? activeNote : null,
      contextNotes,
      onAddContext: handleAddContext,
      onRemoveContext: handleRemoveContext,
      contextUrls,
      onRemoveUrl
    }
  );
};
var ContextControl_default = ContextControl;

// node_modules/react-dropzone/dist/es/index.js
var import_react13 = __toESM(require_react());
var import_prop_types = __toESM(require_prop_types());

// node_modules/file-selector/node_modules/tslib/tslib.es6.mjs
function __awaiter5(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e3) {
        reject(e3);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e3) {
        reject(e3);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}

// node_modules/file-selector/dist/es2015/file.js
var COMMON_MIME_TYPES = /* @__PURE__ */ new Map([
  // https://github.com/guzzle/psr7/blob/2d9260799e713f1c475d3c5fdc3d6561ff7441b2/src/MimeType.php
  ["1km", "application/vnd.1000minds.decision-model+xml"],
  ["3dml", "text/vnd.in3d.3dml"],
  ["3ds", "image/x-3ds"],
  ["3g2", "video/3gpp2"],
  ["3gp", "video/3gp"],
  ["3gpp", "video/3gpp"],
  ["3mf", "model/3mf"],
  ["7z", "application/x-7z-compressed"],
  ["7zip", "application/x-7z-compressed"],
  ["123", "application/vnd.lotus-1-2-3"],
  ["aab", "application/x-authorware-bin"],
  ["aac", "audio/x-acc"],
  ["aam", "application/x-authorware-map"],
  ["aas", "application/x-authorware-seg"],
  ["abw", "application/x-abiword"],
  ["ac", "application/vnd.nokia.n-gage.ac+xml"],
  ["ac3", "audio/ac3"],
  ["acc", "application/vnd.americandynamics.acc"],
  ["ace", "application/x-ace-compressed"],
  ["acu", "application/vnd.acucobol"],
  ["acutc", "application/vnd.acucorp"],
  ["adp", "audio/adpcm"],
  ["aep", "application/vnd.audiograph"],
  ["afm", "application/x-font-type1"],
  ["afp", "application/vnd.ibm.modcap"],
  ["ahead", "application/vnd.ahead.space"],
  ["ai", "application/pdf"],
  ["aif", "audio/x-aiff"],
  ["aifc", "audio/x-aiff"],
  ["aiff", "audio/x-aiff"],
  ["air", "application/vnd.adobe.air-application-installer-package+zip"],
  ["ait", "application/vnd.dvb.ait"],
  ["ami", "application/vnd.amiga.ami"],
  ["amr", "audio/amr"],
  ["apk", "application/vnd.android.package-archive"],
  ["apng", "image/apng"],
  ["appcache", "text/cache-manifest"],
  ["application", "application/x-ms-application"],
  ["apr", "application/vnd.lotus-approach"],
  ["arc", "application/x-freearc"],
  ["arj", "application/x-arj"],
  ["asc", "application/pgp-signature"],
  ["asf", "video/x-ms-asf"],
  ["asm", "text/x-asm"],
  ["aso", "application/vnd.accpac.simply.aso"],
  ["asx", "video/x-ms-asf"],
  ["atc", "application/vnd.acucorp"],
  ["atom", "application/atom+xml"],
  ["atomcat", "application/atomcat+xml"],
  ["atomdeleted", "application/atomdeleted+xml"],
  ["atomsvc", "application/atomsvc+xml"],
  ["atx", "application/vnd.antix.game-component"],
  ["au", "audio/x-au"],
  ["avi", "video/x-msvideo"],
  ["avif", "image/avif"],
  ["aw", "application/applixware"],
  ["azf", "application/vnd.airzip.filesecure.azf"],
  ["azs", "application/vnd.airzip.filesecure.azs"],
  ["azv", "image/vnd.airzip.accelerator.azv"],
  ["azw", "application/vnd.amazon.ebook"],
  ["b16", "image/vnd.pco.b16"],
  ["bat", "application/x-msdownload"],
  ["bcpio", "application/x-bcpio"],
  ["bdf", "application/x-font-bdf"],
  ["bdm", "application/vnd.syncml.dm+wbxml"],
  ["bdoc", "application/x-bdoc"],
  ["bed", "application/vnd.realvnc.bed"],
  ["bh2", "application/vnd.fujitsu.oasysprs"],
  ["bin", "application/octet-stream"],
  ["blb", "application/x-blorb"],
  ["blorb", "application/x-blorb"],
  ["bmi", "application/vnd.bmi"],
  ["bmml", "application/vnd.balsamiq.bmml+xml"],
  ["bmp", "image/bmp"],
  ["book", "application/vnd.framemaker"],
  ["box", "application/vnd.previewsystems.box"],
  ["boz", "application/x-bzip2"],
  ["bpk", "application/octet-stream"],
  ["bpmn", "application/octet-stream"],
  ["bsp", "model/vnd.valve.source.compiled-map"],
  ["btif", "image/prs.btif"],
  ["buffer", "application/octet-stream"],
  ["bz", "application/x-bzip"],
  ["bz2", "application/x-bzip2"],
  ["c", "text/x-c"],
  ["c4d", "application/vnd.clonk.c4group"],
  ["c4f", "application/vnd.clonk.c4group"],
  ["c4g", "application/vnd.clonk.c4group"],
  ["c4p", "application/vnd.clonk.c4group"],
  ["c4u", "application/vnd.clonk.c4group"],
  ["c11amc", "application/vnd.cluetrust.cartomobile-config"],
  ["c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"],
  ["cab", "application/vnd.ms-cab-compressed"],
  ["caf", "audio/x-caf"],
  ["cap", "application/vnd.tcpdump.pcap"],
  ["car", "application/vnd.curl.car"],
  ["cat", "application/vnd.ms-pki.seccat"],
  ["cb7", "application/x-cbr"],
  ["cba", "application/x-cbr"],
  ["cbr", "application/x-cbr"],
  ["cbt", "application/x-cbr"],
  ["cbz", "application/x-cbr"],
  ["cc", "text/x-c"],
  ["cco", "application/x-cocoa"],
  ["cct", "application/x-director"],
  ["ccxml", "application/ccxml+xml"],
  ["cdbcmsg", "application/vnd.contact.cmsg"],
  ["cda", "application/x-cdf"],
  ["cdf", "application/x-netcdf"],
  ["cdfx", "application/cdfx+xml"],
  ["cdkey", "application/vnd.mediastation.cdkey"],
  ["cdmia", "application/cdmi-capability"],
  ["cdmic", "application/cdmi-container"],
  ["cdmid", "application/cdmi-domain"],
  ["cdmio", "application/cdmi-object"],
  ["cdmiq", "application/cdmi-queue"],
  ["cdr", "application/cdr"],
  ["cdx", "chemical/x-cdx"],
  ["cdxml", "application/vnd.chemdraw+xml"],
  ["cdy", "application/vnd.cinderella"],
  ["cer", "application/pkix-cert"],
  ["cfs", "application/x-cfs-compressed"],
  ["cgm", "image/cgm"],
  ["chat", "application/x-chat"],
  ["chm", "application/vnd.ms-htmlhelp"],
  ["chrt", "application/vnd.kde.kchart"],
  ["cif", "chemical/x-cif"],
  ["cii", "application/vnd.anser-web-certificate-issue-initiation"],
  ["cil", "application/vnd.ms-artgalry"],
  ["cjs", "application/node"],
  ["cla", "application/vnd.claymore"],
  ["class", "application/octet-stream"],
  ["clkk", "application/vnd.crick.clicker.keyboard"],
  ["clkp", "application/vnd.crick.clicker.palette"],
  ["clkt", "application/vnd.crick.clicker.template"],
  ["clkw", "application/vnd.crick.clicker.wordbank"],
  ["clkx", "application/vnd.crick.clicker"],
  ["clp", "application/x-msclip"],
  ["cmc", "application/vnd.cosmocaller"],
  ["cmdf", "chemical/x-cmdf"],
  ["cml", "chemical/x-cml"],
  ["cmp", "application/vnd.yellowriver-custom-menu"],
  ["cmx", "image/x-cmx"],
  ["cod", "application/vnd.rim.cod"],
  ["coffee", "text/coffeescript"],
  ["com", "application/x-msdownload"],
  ["conf", "text/plain"],
  ["cpio", "application/x-cpio"],
  ["cpp", "text/x-c"],
  ["cpt", "application/mac-compactpro"],
  ["crd", "application/x-mscardfile"],
  ["crl", "application/pkix-crl"],
  ["crt", "application/x-x509-ca-cert"],
  ["crx", "application/x-chrome-extension"],
  ["cryptonote", "application/vnd.rig.cryptonote"],
  ["csh", "application/x-csh"],
  ["csl", "application/vnd.citationstyles.style+xml"],
  ["csml", "chemical/x-csml"],
  ["csp", "application/vnd.commonspace"],
  ["csr", "application/octet-stream"],
  ["css", "text/css"],
  ["cst", "application/x-director"],
  ["csv", "text/csv"],
  ["cu", "application/cu-seeme"],
  ["curl", "text/vnd.curl"],
  ["cww", "application/prs.cww"],
  ["cxt", "application/x-director"],
  ["cxx", "text/x-c"],
  ["dae", "model/vnd.collada+xml"],
  ["daf", "application/vnd.mobius.daf"],
  ["dart", "application/vnd.dart"],
  ["dataless", "application/vnd.fdsn.seed"],
  ["davmount", "application/davmount+xml"],
  ["dbf", "application/vnd.dbf"],
  ["dbk", "application/docbook+xml"],
  ["dcr", "application/x-director"],
  ["dcurl", "text/vnd.curl.dcurl"],
  ["dd2", "application/vnd.oma.dd2+xml"],
  ["ddd", "application/vnd.fujixerox.ddd"],
  ["ddf", "application/vnd.syncml.dmddf+xml"],
  ["dds", "image/vnd.ms-dds"],
  ["deb", "application/x-debian-package"],
  ["def", "text/plain"],
  ["deploy", "application/octet-stream"],
  ["der", "application/x-x509-ca-cert"],
  ["dfac", "application/vnd.dreamfactory"],
  ["dgc", "application/x-dgc-compressed"],
  ["dic", "text/x-c"],
  ["dir", "application/x-director"],
  ["dis", "application/vnd.mobius.dis"],
  ["disposition-notification", "message/disposition-notification"],
  ["dist", "application/octet-stream"],
  ["distz", "application/octet-stream"],
  ["djv", "image/vnd.djvu"],
  ["djvu", "image/vnd.djvu"],
  ["dll", "application/octet-stream"],
  ["dmg", "application/x-apple-diskimage"],
  ["dmn", "application/octet-stream"],
  ["dmp", "application/vnd.tcpdump.pcap"],
  ["dms", "application/octet-stream"],
  ["dna", "application/vnd.dna"],
  ["doc", "application/msword"],
  ["docm", "application/vnd.ms-word.template.macroEnabled.12"],
  ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  ["dot", "application/msword"],
  ["dotm", "application/vnd.ms-word.template.macroEnabled.12"],
  ["dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"],
  ["dp", "application/vnd.osgi.dp"],
  ["dpg", "application/vnd.dpgraph"],
  ["dra", "audio/vnd.dra"],
  ["drle", "image/dicom-rle"],
  ["dsc", "text/prs.lines.tag"],
  ["dssc", "application/dssc+der"],
  ["dtb", "application/x-dtbook+xml"],
  ["dtd", "application/xml-dtd"],
  ["dts", "audio/vnd.dts"],
  ["dtshd", "audio/vnd.dts.hd"],
  ["dump", "application/octet-stream"],
  ["dvb", "video/vnd.dvb.file"],
  ["dvi", "application/x-dvi"],
  ["dwd", "application/atsc-dwd+xml"],
  ["dwf", "model/vnd.dwf"],
  ["dwg", "image/vnd.dwg"],
  ["dxf", "image/vnd.dxf"],
  ["dxp", "application/vnd.spotfire.dxp"],
  ["dxr", "application/x-director"],
  ["ear", "application/java-archive"],
  ["ecelp4800", "audio/vnd.nuera.ecelp4800"],
  ["ecelp7470", "audio/vnd.nuera.ecelp7470"],
  ["ecelp9600", "audio/vnd.nuera.ecelp9600"],
  ["ecma", "application/ecmascript"],
  ["edm", "application/vnd.novadigm.edm"],
  ["edx", "application/vnd.novadigm.edx"],
  ["efif", "application/vnd.picsel"],
  ["ei6", "application/vnd.pg.osasli"],
  ["elc", "application/octet-stream"],
  ["emf", "image/emf"],
  ["eml", "message/rfc822"],
  ["emma", "application/emma+xml"],
  ["emotionml", "application/emotionml+xml"],
  ["emz", "application/x-msmetafile"],
  ["eol", "audio/vnd.digital-winds"],
  ["eot", "application/vnd.ms-fontobject"],
  ["eps", "application/postscript"],
  ["epub", "application/epub+zip"],
  ["es", "application/ecmascript"],
  ["es3", "application/vnd.eszigno3+xml"],
  ["esa", "application/vnd.osgi.subsystem"],
  ["esf", "application/vnd.epson.esf"],
  ["et3", "application/vnd.eszigno3+xml"],
  ["etx", "text/x-setext"],
  ["eva", "application/x-eva"],
  ["evy", "application/x-envoy"],
  ["exe", "application/octet-stream"],
  ["exi", "application/exi"],
  ["exp", "application/express"],
  ["exr", "image/aces"],
  ["ext", "application/vnd.novadigm.ext"],
  ["ez", "application/andrew-inset"],
  ["ez2", "application/vnd.ezpix-album"],
  ["ez3", "application/vnd.ezpix-package"],
  ["f", "text/x-fortran"],
  ["f4v", "video/mp4"],
  ["f77", "text/x-fortran"],
  ["f90", "text/x-fortran"],
  ["fbs", "image/vnd.fastbidsheet"],
  ["fcdt", "application/vnd.adobe.formscentral.fcdt"],
  ["fcs", "application/vnd.isac.fcs"],
  ["fdf", "application/vnd.fdf"],
  ["fdt", "application/fdt+xml"],
  ["fe_launch", "application/vnd.denovo.fcselayout-link"],
  ["fg5", "application/vnd.fujitsu.oasysgp"],
  ["fgd", "application/x-director"],
  ["fh", "image/x-freehand"],
  ["fh4", "image/x-freehand"],
  ["fh5", "image/x-freehand"],
  ["fh7", "image/x-freehand"],
  ["fhc", "image/x-freehand"],
  ["fig", "application/x-xfig"],
  ["fits", "image/fits"],
  ["flac", "audio/x-flac"],
  ["fli", "video/x-fli"],
  ["flo", "application/vnd.micrografx.flo"],
  ["flv", "video/x-flv"],
  ["flw", "application/vnd.kde.kivio"],
  ["flx", "text/vnd.fmi.flexstor"],
  ["fly", "text/vnd.fly"],
  ["fm", "application/vnd.framemaker"],
  ["fnc", "application/vnd.frogans.fnc"],
  ["fo", "application/vnd.software602.filler.form+xml"],
  ["for", "text/x-fortran"],
  ["fpx", "image/vnd.fpx"],
  ["frame", "application/vnd.framemaker"],
  ["fsc", "application/vnd.fsc.weblaunch"],
  ["fst", "image/vnd.fst"],
  ["ftc", "application/vnd.fluxtime.clip"],
  ["fti", "application/vnd.anser-web-funds-transfer-initiation"],
  ["fvt", "video/vnd.fvt"],
  ["fxp", "application/vnd.adobe.fxp"],
  ["fxpl", "application/vnd.adobe.fxp"],
  ["fzs", "application/vnd.fuzzysheet"],
  ["g2w", "application/vnd.geoplan"],
  ["g3", "image/g3fax"],
  ["g3w", "application/vnd.geospace"],
  ["gac", "application/vnd.groove-account"],
  ["gam", "application/x-tads"],
  ["gbr", "application/rpki-ghostbusters"],
  ["gca", "application/x-gca-compressed"],
  ["gdl", "model/vnd.gdl"],
  ["gdoc", "application/vnd.google-apps.document"],
  ["geo", "application/vnd.dynageo"],
  ["geojson", "application/geo+json"],
  ["gex", "application/vnd.geometry-explorer"],
  ["ggb", "application/vnd.geogebra.file"],
  ["ggt", "application/vnd.geogebra.tool"],
  ["ghf", "application/vnd.groove-help"],
  ["gif", "image/gif"],
  ["gim", "application/vnd.groove-identity-message"],
  ["glb", "model/gltf-binary"],
  ["gltf", "model/gltf+json"],
  ["gml", "application/gml+xml"],
  ["gmx", "application/vnd.gmx"],
  ["gnumeric", "application/x-gnumeric"],
  ["gpg", "application/gpg-keys"],
  ["gph", "application/vnd.flographit"],
  ["gpx", "application/gpx+xml"],
  ["gqf", "application/vnd.grafeq"],
  ["gqs", "application/vnd.grafeq"],
  ["gram", "application/srgs"],
  ["gramps", "application/x-gramps-xml"],
  ["gre", "application/vnd.geometry-explorer"],
  ["grv", "application/vnd.groove-injector"],
  ["grxml", "application/srgs+xml"],
  ["gsf", "application/x-font-ghostscript"],
  ["gsheet", "application/vnd.google-apps.spreadsheet"],
  ["gslides", "application/vnd.google-apps.presentation"],
  ["gtar", "application/x-gtar"],
  ["gtm", "application/vnd.groove-tool-message"],
  ["gtw", "model/vnd.gtw"],
  ["gv", "text/vnd.graphviz"],
  ["gxf", "application/gxf"],
  ["gxt", "application/vnd.geonext"],
  ["gz", "application/gzip"],
  ["gzip", "application/gzip"],
  ["h", "text/x-c"],
  ["h261", "video/h261"],
  ["h263", "video/h263"],
  ["h264", "video/h264"],
  ["hal", "application/vnd.hal+xml"],
  ["hbci", "application/vnd.hbci"],
  ["hbs", "text/x-handlebars-template"],
  ["hdd", "application/x-virtualbox-hdd"],
  ["hdf", "application/x-hdf"],
  ["heic", "image/heic"],
  ["heics", "image/heic-sequence"],
  ["heif", "image/heif"],
  ["heifs", "image/heif-sequence"],
  ["hej2", "image/hej2k"],
  ["held", "application/atsc-held+xml"],
  ["hh", "text/x-c"],
  ["hjson", "application/hjson"],
  ["hlp", "application/winhlp"],
  ["hpgl", "application/vnd.hp-hpgl"],
  ["hpid", "application/vnd.hp-hpid"],
  ["hps", "application/vnd.hp-hps"],
  ["hqx", "application/mac-binhex40"],
  ["hsj2", "image/hsj2"],
  ["htc", "text/x-component"],
  ["htke", "application/vnd.kenameaapp"],
  ["htm", "text/html"],
  ["html", "text/html"],
  ["hvd", "application/vnd.yamaha.hv-dic"],
  ["hvp", "application/vnd.yamaha.hv-voice"],
  ["hvs", "application/vnd.yamaha.hv-script"],
  ["i2g", "application/vnd.intergeo"],
  ["icc", "application/vnd.iccprofile"],
  ["ice", "x-conference/x-cooltalk"],
  ["icm", "application/vnd.iccprofile"],
  ["ico", "image/x-icon"],
  ["ics", "text/calendar"],
  ["ief", "image/ief"],
  ["ifb", "text/calendar"],
  ["ifm", "application/vnd.shana.informed.formdata"],
  ["iges", "model/iges"],
  ["igl", "application/vnd.igloader"],
  ["igm", "application/vnd.insors.igm"],
  ["igs", "model/iges"],
  ["igx", "application/vnd.micrografx.igx"],
  ["iif", "application/vnd.shana.informed.interchange"],
  ["img", "application/octet-stream"],
  ["imp", "application/vnd.accpac.simply.imp"],
  ["ims", "application/vnd.ms-ims"],
  ["in", "text/plain"],
  ["ini", "text/plain"],
  ["ink", "application/inkml+xml"],
  ["inkml", "application/inkml+xml"],
  ["install", "application/x-install-instructions"],
  ["iota", "application/vnd.astraea-software.iota"],
  ["ipfix", "application/ipfix"],
  ["ipk", "application/vnd.shana.informed.package"],
  ["irm", "application/vnd.ibm.rights-management"],
  ["irp", "application/vnd.irepository.package+xml"],
  ["iso", "application/x-iso9660-image"],
  ["itp", "application/vnd.shana.informed.formtemplate"],
  ["its", "application/its+xml"],
  ["ivp", "application/vnd.immervision-ivp"],
  ["ivu", "application/vnd.immervision-ivu"],
  ["jad", "text/vnd.sun.j2me.app-descriptor"],
  ["jade", "text/jade"],
  ["jam", "application/vnd.jam"],
  ["jar", "application/java-archive"],
  ["jardiff", "application/x-java-archive-diff"],
  ["java", "text/x-java-source"],
  ["jhc", "image/jphc"],
  ["jisp", "application/vnd.jisp"],
  ["jls", "image/jls"],
  ["jlt", "application/vnd.hp-jlyt"],
  ["jng", "image/x-jng"],
  ["jnlp", "application/x-java-jnlp-file"],
  ["joda", "application/vnd.joost.joda-archive"],
  ["jp2", "image/jp2"],
  ["jpe", "image/jpeg"],
  ["jpeg", "image/jpeg"],
  ["jpf", "image/jpx"],
  ["jpg", "image/jpeg"],
  ["jpg2", "image/jp2"],
  ["jpgm", "video/jpm"],
  ["jpgv", "video/jpeg"],
  ["jph", "image/jph"],
  ["jpm", "video/jpm"],
  ["jpx", "image/jpx"],
  ["js", "application/javascript"],
  ["json", "application/json"],
  ["json5", "application/json5"],
  ["jsonld", "application/ld+json"],
  // https://jsonlines.org/
  ["jsonl", "application/jsonl"],
  ["jsonml", "application/jsonml+json"],
  ["jsx", "text/jsx"],
  ["jxr", "image/jxr"],
  ["jxra", "image/jxra"],
  ["jxrs", "image/jxrs"],
  ["jxs", "image/jxs"],
  ["jxsc", "image/jxsc"],
  ["jxsi", "image/jxsi"],
  ["jxss", "image/jxss"],
  ["kar", "audio/midi"],
  ["karbon", "application/vnd.kde.karbon"],
  ["kdb", "application/octet-stream"],
  ["kdbx", "application/x-keepass2"],
  ["key", "application/x-iwork-keynote-sffkey"],
  ["kfo", "application/vnd.kde.kformula"],
  ["kia", "application/vnd.kidspiration"],
  ["kml", "application/vnd.google-earth.kml+xml"],
  ["kmz", "application/vnd.google-earth.kmz"],
  ["kne", "application/vnd.kinar"],
  ["knp", "application/vnd.kinar"],
  ["kon", "application/vnd.kde.kontour"],
  ["kpr", "application/vnd.kde.kpresenter"],
  ["kpt", "application/vnd.kde.kpresenter"],
  ["kpxx", "application/vnd.ds-keypoint"],
  ["ksp", "application/vnd.kde.kspread"],
  ["ktr", "application/vnd.kahootz"],
  ["ktx", "image/ktx"],
  ["ktx2", "image/ktx2"],
  ["ktz", "application/vnd.kahootz"],
  ["kwd", "application/vnd.kde.kword"],
  ["kwt", "application/vnd.kde.kword"],
  ["lasxml", "application/vnd.las.las+xml"],
  ["latex", "application/x-latex"],
  ["lbd", "application/vnd.llamagraphics.life-balance.desktop"],
  ["lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"],
  ["les", "application/vnd.hhe.lesson-player"],
  ["less", "text/less"],
  ["lgr", "application/lgr+xml"],
  ["lha", "application/octet-stream"],
  ["link66", "application/vnd.route66.link66+xml"],
  ["list", "text/plain"],
  ["list3820", "application/vnd.ibm.modcap"],
  ["listafp", "application/vnd.ibm.modcap"],
  ["litcoffee", "text/coffeescript"],
  ["lnk", "application/x-ms-shortcut"],
  ["log", "text/plain"],
  ["lostxml", "application/lost+xml"],
  ["lrf", "application/octet-stream"],
  ["lrm", "application/vnd.ms-lrm"],
  ["ltf", "application/vnd.frogans.ltf"],
  ["lua", "text/x-lua"],
  ["luac", "application/x-lua-bytecode"],
  ["lvp", "audio/vnd.lucent.voice"],
  ["lwp", "application/vnd.lotus-wordpro"],
  ["lzh", "application/octet-stream"],
  ["m1v", "video/mpeg"],
  ["m2a", "audio/mpeg"],
  ["m2v", "video/mpeg"],
  ["m3a", "audio/mpeg"],
  ["m3u", "text/plain"],
  ["m3u8", "application/vnd.apple.mpegurl"],
  ["m4a", "audio/x-m4a"],
  ["m4p", "application/mp4"],
  ["m4s", "video/iso.segment"],
  ["m4u", "application/vnd.mpegurl"],
  ["m4v", "video/x-m4v"],
  ["m13", "application/x-msmediaview"],
  ["m14", "application/x-msmediaview"],
  ["m21", "application/mp21"],
  ["ma", "application/mathematica"],
  ["mads", "application/mads+xml"],
  ["maei", "application/mmt-aei+xml"],
  ["mag", "application/vnd.ecowin.chart"],
  ["maker", "application/vnd.framemaker"],
  ["man", "text/troff"],
  ["manifest", "text/cache-manifest"],
  ["map", "application/json"],
  ["mar", "application/octet-stream"],
  ["markdown", "text/markdown"],
  ["mathml", "application/mathml+xml"],
  ["mb", "application/mathematica"],
  ["mbk", "application/vnd.mobius.mbk"],
  ["mbox", "application/mbox"],
  ["mc1", "application/vnd.medcalcdata"],
  ["mcd", "application/vnd.mcd"],
  ["mcurl", "text/vnd.curl.mcurl"],
  ["md", "text/markdown"],
  ["mdb", "application/x-msaccess"],
  ["mdi", "image/vnd.ms-modi"],
  ["mdx", "text/mdx"],
  ["me", "text/troff"],
  ["mesh", "model/mesh"],
  ["meta4", "application/metalink4+xml"],
  ["metalink", "application/metalink+xml"],
  ["mets", "application/mets+xml"],
  ["mfm", "application/vnd.mfmp"],
  ["mft", "application/rpki-manifest"],
  ["mgp", "application/vnd.osgeo.mapguide.package"],
  ["mgz", "application/vnd.proteus.magazine"],
  ["mid", "audio/midi"],
  ["midi", "audio/midi"],
  ["mie", "application/x-mie"],
  ["mif", "application/vnd.mif"],
  ["mime", "message/rfc822"],
  ["mj2", "video/mj2"],
  ["mjp2", "video/mj2"],
  ["mjs", "application/javascript"],
  ["mk3d", "video/x-matroska"],
  ["mka", "audio/x-matroska"],
  ["mkd", "text/x-markdown"],
  ["mks", "video/x-matroska"],
  ["mkv", "video/x-matroska"],
  ["mlp", "application/vnd.dolby.mlp"],
  ["mmd", "application/vnd.chipnuts.karaoke-mmd"],
  ["mmf", "application/vnd.smaf"],
  ["mml", "text/mathml"],
  ["mmr", "image/vnd.fujixerox.edmics-mmr"],
  ["mng", "video/x-mng"],
  ["mny", "application/x-msmoney"],
  ["mobi", "application/x-mobipocket-ebook"],
  ["mods", "application/mods+xml"],
  ["mov", "video/quicktime"],
  ["movie", "video/x-sgi-movie"],
  ["mp2", "audio/mpeg"],
  ["mp2a", "audio/mpeg"],
  ["mp3", "audio/mpeg"],
  ["mp4", "video/mp4"],
  ["mp4a", "audio/mp4"],
  ["mp4s", "application/mp4"],
  ["mp4v", "video/mp4"],
  ["mp21", "application/mp21"],
  ["mpc", "application/vnd.mophun.certificate"],
  ["mpd", "application/dash+xml"],
  ["mpe", "video/mpeg"],
  ["mpeg", "video/mpeg"],
  ["mpg", "video/mpeg"],
  ["mpg4", "video/mp4"],
  ["mpga", "audio/mpeg"],
  ["mpkg", "application/vnd.apple.installer+xml"],
  ["mpm", "application/vnd.blueice.multipass"],
  ["mpn", "application/vnd.mophun.application"],
  ["mpp", "application/vnd.ms-project"],
  ["mpt", "application/vnd.ms-project"],
  ["mpy", "application/vnd.ibm.minipay"],
  ["mqy", "application/vnd.mobius.mqy"],
  ["mrc", "application/marc"],
  ["mrcx", "application/marcxml+xml"],
  ["ms", "text/troff"],
  ["mscml", "application/mediaservercontrol+xml"],
  ["mseed", "application/vnd.fdsn.mseed"],
  ["mseq", "application/vnd.mseq"],
  ["msf", "application/vnd.epson.msf"],
  ["msg", "application/vnd.ms-outlook"],
  ["msh", "model/mesh"],
  ["msi", "application/x-msdownload"],
  ["msl", "application/vnd.mobius.msl"],
  ["msm", "application/octet-stream"],
  ["msp", "application/octet-stream"],
  ["msty", "application/vnd.muvee.style"],
  ["mtl", "model/mtl"],
  ["mts", "model/vnd.mts"],
  ["mus", "application/vnd.musician"],
  ["musd", "application/mmt-usd+xml"],
  ["musicxml", "application/vnd.recordare.musicxml+xml"],
  ["mvb", "application/x-msmediaview"],
  ["mvt", "application/vnd.mapbox-vector-tile"],
  ["mwf", "application/vnd.mfer"],
  ["mxf", "application/mxf"],
  ["mxl", "application/vnd.recordare.musicxml"],
  ["mxmf", "audio/mobile-xmf"],
  ["mxml", "application/xv+xml"],
  ["mxs", "application/vnd.triscape.mxs"],
  ["mxu", "video/vnd.mpegurl"],
  ["n-gage", "application/vnd.nokia.n-gage.symbian.install"],
  ["n3", "text/n3"],
  ["nb", "application/mathematica"],
  ["nbp", "application/vnd.wolfram.player"],
  ["nc", "application/x-netcdf"],
  ["ncx", "application/x-dtbncx+xml"],
  ["nfo", "text/x-nfo"],
  ["ngdat", "application/vnd.nokia.n-gage.data"],
  ["nitf", "application/vnd.nitf"],
  ["nlu", "application/vnd.neurolanguage.nlu"],
  ["nml", "application/vnd.enliven"],
  ["nnd", "application/vnd.noblenet-directory"],
  ["nns", "application/vnd.noblenet-sealer"],
  ["nnw", "application/vnd.noblenet-web"],
  ["npx", "image/vnd.net-fpx"],
  ["nq", "application/n-quads"],
  ["nsc", "application/x-conference"],
  ["nsf", "application/vnd.lotus-notes"],
  ["nt", "application/n-triples"],
  ["ntf", "application/vnd.nitf"],
  ["numbers", "application/x-iwork-numbers-sffnumbers"],
  ["nzb", "application/x-nzb"],
  ["oa2", "application/vnd.fujitsu.oasys2"],
  ["oa3", "application/vnd.fujitsu.oasys3"],
  ["oas", "application/vnd.fujitsu.oasys"],
  ["obd", "application/x-msbinder"],
  ["obgx", "application/vnd.openblox.game+xml"],
  ["obj", "model/obj"],
  ["oda", "application/oda"],
  ["odb", "application/vnd.oasis.opendocument.database"],
  ["odc", "application/vnd.oasis.opendocument.chart"],
  ["odf", "application/vnd.oasis.opendocument.formula"],
  ["odft", "application/vnd.oasis.opendocument.formula-template"],
  ["odg", "application/vnd.oasis.opendocument.graphics"],
  ["odi", "application/vnd.oasis.opendocument.image"],
  ["odm", "application/vnd.oasis.opendocument.text-master"],
  ["odp", "application/vnd.oasis.opendocument.presentation"],
  ["ods", "application/vnd.oasis.opendocument.spreadsheet"],
  ["odt", "application/vnd.oasis.opendocument.text"],
  ["oga", "audio/ogg"],
  ["ogex", "model/vnd.opengex"],
  ["ogg", "audio/ogg"],
  ["ogv", "video/ogg"],
  ["ogx", "application/ogg"],
  ["omdoc", "application/omdoc+xml"],
  ["onepkg", "application/onenote"],
  ["onetmp", "application/onenote"],
  ["onetoc", "application/onenote"],
  ["onetoc2", "application/onenote"],
  ["opf", "application/oebps-package+xml"],
  ["opml", "text/x-opml"],
  ["oprc", "application/vnd.palm"],
  ["opus", "audio/ogg"],
  ["org", "text/x-org"],
  ["osf", "application/vnd.yamaha.openscoreformat"],
  ["osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"],
  ["osm", "application/vnd.openstreetmap.data+xml"],
  ["otc", "application/vnd.oasis.opendocument.chart-template"],
  ["otf", "font/otf"],
  ["otg", "application/vnd.oasis.opendocument.graphics-template"],
  ["oth", "application/vnd.oasis.opendocument.text-web"],
  ["oti", "application/vnd.oasis.opendocument.image-template"],
  ["otp", "application/vnd.oasis.opendocument.presentation-template"],
  ["ots", "application/vnd.oasis.opendocument.spreadsheet-template"],
  ["ott", "application/vnd.oasis.opendocument.text-template"],
  ["ova", "application/x-virtualbox-ova"],
  ["ovf", "application/x-virtualbox-ovf"],
  ["owl", "application/rdf+xml"],
  ["oxps", "application/oxps"],
  ["oxt", "application/vnd.openofficeorg.extension"],
  ["p", "text/x-pascal"],
  ["p7a", "application/x-pkcs7-signature"],
  ["p7b", "application/x-pkcs7-certificates"],
  ["p7c", "application/pkcs7-mime"],
  ["p7m", "application/pkcs7-mime"],
  ["p7r", "application/x-pkcs7-certreqresp"],
  ["p7s", "application/pkcs7-signature"],
  ["p8", "application/pkcs8"],
  ["p10", "application/x-pkcs10"],
  ["p12", "application/x-pkcs12"],
  ["pac", "application/x-ns-proxy-autoconfig"],
  ["pages", "application/x-iwork-pages-sffpages"],
  ["pas", "text/x-pascal"],
  ["paw", "application/vnd.pawaafile"],
  ["pbd", "application/vnd.powerbuilder6"],
  ["pbm", "image/x-portable-bitmap"],
  ["pcap", "application/vnd.tcpdump.pcap"],
  ["pcf", "application/x-font-pcf"],
  ["pcl", "application/vnd.hp-pcl"],
  ["pclxl", "application/vnd.hp-pclxl"],
  ["pct", "image/x-pict"],
  ["pcurl", "application/vnd.curl.pcurl"],
  ["pcx", "image/x-pcx"],
  ["pdb", "application/x-pilot"],
  ["pde", "text/x-processing"],
  ["pdf", "application/pdf"],
  ["pem", "application/x-x509-user-cert"],
  ["pfa", "application/x-font-type1"],
  ["pfb", "application/x-font-type1"],
  ["pfm", "application/x-font-type1"],
  ["pfr", "application/font-tdpfr"],
  ["pfx", "application/x-pkcs12"],
  ["pgm", "image/x-portable-graymap"],
  ["pgn", "application/x-chess-pgn"],
  ["pgp", "application/pgp"],
  ["php", "application/x-httpd-php"],
  ["php3", "application/x-httpd-php"],
  ["php4", "application/x-httpd-php"],
  ["phps", "application/x-httpd-php-source"],
  ["phtml", "application/x-httpd-php"],
  ["pic", "image/x-pict"],
  ["pkg", "application/octet-stream"],
  ["pki", "application/pkixcmp"],
  ["pkipath", "application/pkix-pkipath"],
  ["pkpass", "application/vnd.apple.pkpass"],
  ["pl", "application/x-perl"],
  ["plb", "application/vnd.3gpp.pic-bw-large"],
  ["plc", "application/vnd.mobius.plc"],
  ["plf", "application/vnd.pocketlearn"],
  ["pls", "application/pls+xml"],
  ["pm", "application/x-perl"],
  ["pml", "application/vnd.ctc-posml"],
  ["png", "image/png"],
  ["pnm", "image/x-portable-anymap"],
  ["portpkg", "application/vnd.macports.portpkg"],
  ["pot", "application/vnd.ms-powerpoint"],
  ["potm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"],
  ["potx", "application/vnd.openxmlformats-officedocument.presentationml.template"],
  ["ppa", "application/vnd.ms-powerpoint"],
  ["ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"],
  ["ppd", "application/vnd.cups-ppd"],
  ["ppm", "image/x-portable-pixmap"],
  ["pps", "application/vnd.ms-powerpoint"],
  ["ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"],
  ["ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"],
  ["ppt", "application/powerpoint"],
  ["pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"],
  ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  ["pqa", "application/vnd.palm"],
  ["prc", "application/x-pilot"],
  ["pre", "application/vnd.lotus-freelance"],
  ["prf", "application/pics-rules"],
  ["provx", "application/provenance+xml"],
  ["ps", "application/postscript"],
  ["psb", "application/vnd.3gpp.pic-bw-small"],
  ["psd", "application/x-photoshop"],
  ["psf", "application/x-font-linux-psf"],
  ["pskcxml", "application/pskc+xml"],
  ["pti", "image/prs.pti"],
  ["ptid", "application/vnd.pvi.ptid1"],
  ["pub", "application/x-mspublisher"],
  ["pvb", "application/vnd.3gpp.pic-bw-var"],
  ["pwn", "application/vnd.3m.post-it-notes"],
  ["pya", "audio/vnd.ms-playready.media.pya"],
  ["pyv", "video/vnd.ms-playready.media.pyv"],
  ["qam", "application/vnd.epson.quickanime"],
  ["qbo", "application/vnd.intu.qbo"],
  ["qfx", "application/vnd.intu.qfx"],
  ["qps", "application/vnd.publishare-delta-tree"],
  ["qt", "video/quicktime"],
  ["qwd", "application/vnd.quark.quarkxpress"],
  ["qwt", "application/vnd.quark.quarkxpress"],
  ["qxb", "application/vnd.quark.quarkxpress"],
  ["qxd", "application/vnd.quark.quarkxpress"],
  ["qxl", "application/vnd.quark.quarkxpress"],
  ["qxt", "application/vnd.quark.quarkxpress"],
  ["ra", "audio/x-realaudio"],
  ["ram", "audio/x-pn-realaudio"],
  ["raml", "application/raml+yaml"],
  ["rapd", "application/route-apd+xml"],
  ["rar", "application/x-rar"],
  ["ras", "image/x-cmu-raster"],
  ["rcprofile", "application/vnd.ipunplugged.rcprofile"],
  ["rdf", "application/rdf+xml"],
  ["rdz", "application/vnd.data-vision.rdz"],
  ["relo", "application/p2p-overlay+xml"],
  ["rep", "application/vnd.businessobjects"],
  ["res", "application/x-dtbresource+xml"],
  ["rgb", "image/x-rgb"],
  ["rif", "application/reginfo+xml"],
  ["rip", "audio/vnd.rip"],
  ["ris", "application/x-research-info-systems"],
  ["rl", "application/resource-lists+xml"],
  ["rlc", "image/vnd.fujixerox.edmics-rlc"],
  ["rld", "application/resource-lists-diff+xml"],
  ["rm", "audio/x-pn-realaudio"],
  ["rmi", "audio/midi"],
  ["rmp", "audio/x-pn-realaudio-plugin"],
  ["rms", "application/vnd.jcp.javame.midlet-rms"],
  ["rmvb", "application/vnd.rn-realmedia-vbr"],
  ["rnc", "application/relax-ng-compact-syntax"],
  ["rng", "application/xml"],
  ["roa", "application/rpki-roa"],
  ["roff", "text/troff"],
  ["rp9", "application/vnd.cloanto.rp9"],
  ["rpm", "audio/x-pn-realaudio-plugin"],
  ["rpss", "application/vnd.nokia.radio-presets"],
  ["rpst", "application/vnd.nokia.radio-preset"],
  ["rq", "application/sparql-query"],
  ["rs", "application/rls-services+xml"],
  ["rsa", "application/x-pkcs7"],
  ["rsat", "application/atsc-rsat+xml"],
  ["rsd", "application/rsd+xml"],
  ["rsheet", "application/urc-ressheet+xml"],
  ["rss", "application/rss+xml"],
  ["rtf", "text/rtf"],
  ["rtx", "text/richtext"],
  ["run", "application/x-makeself"],
  ["rusd", "application/route-usd+xml"],
  ["rv", "video/vnd.rn-realvideo"],
  ["s", "text/x-asm"],
  ["s3m", "audio/s3m"],
  ["saf", "application/vnd.yamaha.smaf-audio"],
  ["sass", "text/x-sass"],
  ["sbml", "application/sbml+xml"],
  ["sc", "application/vnd.ibm.secure-container"],
  ["scd", "application/x-msschedule"],
  ["scm", "application/vnd.lotus-screencam"],
  ["scq", "application/scvp-cv-request"],
  ["scs", "application/scvp-cv-response"],
  ["scss", "text/x-scss"],
  ["scurl", "text/vnd.curl.scurl"],
  ["sda", "application/vnd.stardivision.draw"],
  ["sdc", "application/vnd.stardivision.calc"],
  ["sdd", "application/vnd.stardivision.impress"],
  ["sdkd", "application/vnd.solent.sdkm+xml"],
  ["sdkm", "application/vnd.solent.sdkm+xml"],
  ["sdp", "application/sdp"],
  ["sdw", "application/vnd.stardivision.writer"],
  ["sea", "application/octet-stream"],
  ["see", "application/vnd.seemail"],
  ["seed", "application/vnd.fdsn.seed"],
  ["sema", "application/vnd.sema"],
  ["semd", "application/vnd.semd"],
  ["semf", "application/vnd.semf"],
  ["senmlx", "application/senml+xml"],
  ["sensmlx", "application/sensml+xml"],
  ["ser", "application/java-serialized-object"],
  ["setpay", "application/set-payment-initiation"],
  ["setreg", "application/set-registration-initiation"],
  ["sfd-hdstx", "application/vnd.hydrostatix.sof-data"],
  ["sfs", "application/vnd.spotfire.sfs"],
  ["sfv", "text/x-sfv"],
  ["sgi", "image/sgi"],
  ["sgl", "application/vnd.stardivision.writer-global"],
  ["sgm", "text/sgml"],
  ["sgml", "text/sgml"],
  ["sh", "application/x-sh"],
  ["shar", "application/x-shar"],
  ["shex", "text/shex"],
  ["shf", "application/shf+xml"],
  ["shtml", "text/html"],
  ["sid", "image/x-mrsid-image"],
  ["sieve", "application/sieve"],
  ["sig", "application/pgp-signature"],
  ["sil", "audio/silk"],
  ["silo", "model/mesh"],
  ["sis", "application/vnd.symbian.install"],
  ["sisx", "application/vnd.symbian.install"],
  ["sit", "application/x-stuffit"],
  ["sitx", "application/x-stuffitx"],
  ["siv", "application/sieve"],
  ["skd", "application/vnd.koan"],
  ["skm", "application/vnd.koan"],
  ["skp", "application/vnd.koan"],
  ["skt", "application/vnd.koan"],
  ["sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"],
  ["sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"],
  ["slim", "text/slim"],
  ["slm", "text/slim"],
  ["sls", "application/route-s-tsid+xml"],
  ["slt", "application/vnd.epson.salt"],
  ["sm", "application/vnd.stepmania.stepchart"],
  ["smf", "application/vnd.stardivision.math"],
  ["smi", "application/smil"],
  ["smil", "application/smil"],
  ["smv", "video/x-smv"],
  ["smzip", "application/vnd.stepmania.package"],
  ["snd", "audio/basic"],
  ["snf", "application/x-font-snf"],
  ["so", "application/octet-stream"],
  ["spc", "application/x-pkcs7-certificates"],
  ["spdx", "text/spdx"],
  ["spf", "application/vnd.yamaha.smaf-phrase"],
  ["spl", "application/x-futuresplash"],
  ["spot", "text/vnd.in3d.spot"],
  ["spp", "application/scvp-vp-response"],
  ["spq", "application/scvp-vp-request"],
  ["spx", "audio/ogg"],
  ["sql", "application/x-sql"],
  ["src", "application/x-wais-source"],
  ["srt", "application/x-subrip"],
  ["sru", "application/sru+xml"],
  ["srx", "application/sparql-results+xml"],
  ["ssdl", "application/ssdl+xml"],
  ["sse", "application/vnd.kodak-descriptor"],
  ["ssf", "application/vnd.epson.ssf"],
  ["ssml", "application/ssml+xml"],
  ["sst", "application/octet-stream"],
  ["st", "application/vnd.sailingtracker.track"],
  ["stc", "application/vnd.sun.xml.calc.template"],
  ["std", "application/vnd.sun.xml.draw.template"],
  ["stf", "application/vnd.wt.stf"],
  ["sti", "application/vnd.sun.xml.impress.template"],
  ["stk", "application/hyperstudio"],
  ["stl", "model/stl"],
  ["stpx", "model/step+xml"],
  ["stpxz", "model/step-xml+zip"],
  ["stpz", "model/step+zip"],
  ["str", "application/vnd.pg.format"],
  ["stw", "application/vnd.sun.xml.writer.template"],
  ["styl", "text/stylus"],
  ["stylus", "text/stylus"],
  ["sub", "text/vnd.dvb.subtitle"],
  ["sus", "application/vnd.sus-calendar"],
  ["susp", "application/vnd.sus-calendar"],
  ["sv4cpio", "application/x-sv4cpio"],
  ["sv4crc", "application/x-sv4crc"],
  ["svc", "application/vnd.dvb.service"],
  ["svd", "application/vnd.svd"],
  ["svg", "image/svg+xml"],
  ["svgz", "image/svg+xml"],
  ["swa", "application/x-director"],
  ["swf", "application/x-shockwave-flash"],
  ["swi", "application/vnd.aristanetworks.swi"],
  ["swidtag", "application/swid+xml"],
  ["sxc", "application/vnd.sun.xml.calc"],
  ["sxd", "application/vnd.sun.xml.draw"],
  ["sxg", "application/vnd.sun.xml.writer.global"],
  ["sxi", "application/vnd.sun.xml.impress"],
  ["sxm", "application/vnd.sun.xml.math"],
  ["sxw", "application/vnd.sun.xml.writer"],
  ["t", "text/troff"],
  ["t3", "application/x-t3vm-image"],
  ["t38", "image/t38"],
  ["taglet", "application/vnd.mynfc"],
  ["tao", "application/vnd.tao.intent-module-archive"],
  ["tap", "image/vnd.tencent.tap"],
  ["tar", "application/x-tar"],
  ["tcap", "application/vnd.3gpp2.tcap"],
  ["tcl", "application/x-tcl"],
  ["td", "application/urc-targetdesc+xml"],
  ["teacher", "application/vnd.smart.teacher"],
  ["tei", "application/tei+xml"],
  ["teicorpus", "application/tei+xml"],
  ["tex", "application/x-tex"],
  ["texi", "application/x-texinfo"],
  ["texinfo", "application/x-texinfo"],
  ["text", "text/plain"],
  ["tfi", "application/thraud+xml"],
  ["tfm", "application/x-tex-tfm"],
  ["tfx", "image/tiff-fx"],
  ["tga", "image/x-tga"],
  ["tgz", "application/x-tar"],
  ["thmx", "application/vnd.ms-officetheme"],
  ["tif", "image/tiff"],
  ["tiff", "image/tiff"],
  ["tk", "application/x-tcl"],
  ["tmo", "application/vnd.tmobile-livetv"],
  ["toml", "application/toml"],
  ["torrent", "application/x-bittorrent"],
  ["tpl", "application/vnd.groove-tool-template"],
  ["tpt", "application/vnd.trid.tpt"],
  ["tr", "text/troff"],
  ["tra", "application/vnd.trueapp"],
  ["trig", "application/trig"],
  ["trm", "application/x-msterminal"],
  ["ts", "video/mp2t"],
  ["tsd", "application/timestamped-data"],
  ["tsv", "text/tab-separated-values"],
  ["ttc", "font/collection"],
  ["ttf", "font/ttf"],
  ["ttl", "text/turtle"],
  ["ttml", "application/ttml+xml"],
  ["twd", "application/vnd.simtech-mindmapper"],
  ["twds", "application/vnd.simtech-mindmapper"],
  ["txd", "application/vnd.genomatix.tuxedo"],
  ["txf", "application/vnd.mobius.txf"],
  ["txt", "text/plain"],
  ["u8dsn", "message/global-delivery-status"],
  ["u8hdr", "message/global-headers"],
  ["u8mdn", "message/global-disposition-notification"],
  ["u8msg", "message/global"],
  ["u32", "application/x-authorware-bin"],
  ["ubj", "application/ubjson"],
  ["udeb", "application/x-debian-package"],
  ["ufd", "application/vnd.ufdl"],
  ["ufdl", "application/vnd.ufdl"],
  ["ulx", "application/x-glulx"],
  ["umj", "application/vnd.umajin"],
  ["unityweb", "application/vnd.unity"],
  ["uoml", "application/vnd.uoml+xml"],
  ["uri", "text/uri-list"],
  ["uris", "text/uri-list"],
  ["urls", "text/uri-list"],
  ["usdz", "model/vnd.usdz+zip"],
  ["ustar", "application/x-ustar"],
  ["utz", "application/vnd.uiq.theme"],
  ["uu", "text/x-uuencode"],
  ["uva", "audio/vnd.dece.audio"],
  ["uvd", "application/vnd.dece.data"],
  ["uvf", "application/vnd.dece.data"],
  ["uvg", "image/vnd.dece.graphic"],
  ["uvh", "video/vnd.dece.hd"],
  ["uvi", "image/vnd.dece.graphic"],
  ["uvm", "video/vnd.dece.mobile"],
  ["uvp", "video/vnd.dece.pd"],
  ["uvs", "video/vnd.dece.sd"],
  ["uvt", "application/vnd.dece.ttml+xml"],
  ["uvu", "video/vnd.uvvu.mp4"],
  ["uvv", "video/vnd.dece.video"],
  ["uvva", "audio/vnd.dece.audio"],
  ["uvvd", "application/vnd.dece.data"],
  ["uvvf", "application/vnd.dece.data"],
  ["uvvg", "image/vnd.dece.graphic"],
  ["uvvh", "video/vnd.dece.hd"],
  ["uvvi", "image/vnd.dece.graphic"],
  ["uvvm", "video/vnd.dece.mobile"],
  ["uvvp", "video/vnd.dece.pd"],
  ["uvvs", "video/vnd.dece.sd"],
  ["uvvt", "application/vnd.dece.ttml+xml"],
  ["uvvu", "video/vnd.uvvu.mp4"],
  ["uvvv", "video/vnd.dece.video"],
  ["uvvx", "application/vnd.dece.unspecified"],
  ["uvvz", "application/vnd.dece.zip"],
  ["uvx", "application/vnd.dece.unspecified"],
  ["uvz", "application/vnd.dece.zip"],
  ["vbox", "application/x-virtualbox-vbox"],
  ["vbox-extpack", "application/x-virtualbox-vbox-extpack"],
  ["vcard", "text/vcard"],
  ["vcd", "application/x-cdlink"],
  ["vcf", "text/x-vcard"],
  ["vcg", "application/vnd.groove-vcard"],
  ["vcs", "text/x-vcalendar"],
  ["vcx", "application/vnd.vcx"],
  ["vdi", "application/x-virtualbox-vdi"],
  ["vds", "model/vnd.sap.vds"],
  ["vhd", "application/x-virtualbox-vhd"],
  ["vis", "application/vnd.visionary"],
  ["viv", "video/vnd.vivo"],
  ["vlc", "application/videolan"],
  ["vmdk", "application/x-virtualbox-vmdk"],
  ["vob", "video/x-ms-vob"],
  ["vor", "application/vnd.stardivision.writer"],
  ["vox", "application/x-authorware-bin"],
  ["vrml", "model/vrml"],
  ["vsd", "application/vnd.visio"],
  ["vsf", "application/vnd.vsf"],
  ["vss", "application/vnd.visio"],
  ["vst", "application/vnd.visio"],
  ["vsw", "application/vnd.visio"],
  ["vtf", "image/vnd.valve.source.texture"],
  ["vtt", "text/vtt"],
  ["vtu", "model/vnd.vtu"],
  ["vxml", "application/voicexml+xml"],
  ["w3d", "application/x-director"],
  ["wad", "application/x-doom"],
  ["wadl", "application/vnd.sun.wadl+xml"],
  ["war", "application/java-archive"],
  ["wasm", "application/wasm"],
  ["wav", "audio/x-wav"],
  ["wax", "audio/x-ms-wax"],
  ["wbmp", "image/vnd.wap.wbmp"],
  ["wbs", "application/vnd.criticaltools.wbs+xml"],
  ["wbxml", "application/wbxml"],
  ["wcm", "application/vnd.ms-works"],
  ["wdb", "application/vnd.ms-works"],
  ["wdp", "image/vnd.ms-photo"],
  ["weba", "audio/webm"],
  ["webapp", "application/x-web-app-manifest+json"],
  ["webm", "video/webm"],
  ["webmanifest", "application/manifest+json"],
  ["webp", "image/webp"],
  ["wg", "application/vnd.pmi.widget"],
  ["wgt", "application/widget"],
  ["wks", "application/vnd.ms-works"],
  ["wm", "video/x-ms-wm"],
  ["wma", "audio/x-ms-wma"],
  ["wmd", "application/x-ms-wmd"],
  ["wmf", "image/wmf"],
  ["wml", "text/vnd.wap.wml"],
  ["wmlc", "application/wmlc"],
  ["wmls", "text/vnd.wap.wmlscript"],
  ["wmlsc", "application/vnd.wap.wmlscriptc"],
  ["wmv", "video/x-ms-wmv"],
  ["wmx", "video/x-ms-wmx"],
  ["wmz", "application/x-msmetafile"],
  ["woff", "font/woff"],
  ["woff2", "font/woff2"],
  ["word", "application/msword"],
  ["wpd", "application/vnd.wordperfect"],
  ["wpl", "application/vnd.ms-wpl"],
  ["wps", "application/vnd.ms-works"],
  ["wqd", "application/vnd.wqd"],
  ["wri", "application/x-mswrite"],
  ["wrl", "model/vrml"],
  ["wsc", "message/vnd.wfa.wsc"],
  ["wsdl", "application/wsdl+xml"],
  ["wspolicy", "application/wspolicy+xml"],
  ["wtb", "application/vnd.webturbo"],
  ["wvx", "video/x-ms-wvx"],
  ["x3d", "model/x3d+xml"],
  ["x3db", "model/x3d+fastinfoset"],
  ["x3dbz", "model/x3d+binary"],
  ["x3dv", "model/x3d-vrml"],
  ["x3dvz", "model/x3d+vrml"],
  ["x3dz", "model/x3d+xml"],
  ["x32", "application/x-authorware-bin"],
  ["x_b", "model/vnd.parasolid.transmit.binary"],
  ["x_t", "model/vnd.parasolid.transmit.text"],
  ["xaml", "application/xaml+xml"],
  ["xap", "application/x-silverlight-app"],
  ["xar", "application/vnd.xara"],
  ["xav", "application/xcap-att+xml"],
  ["xbap", "application/x-ms-xbap"],
  ["xbd", "application/vnd.fujixerox.docuworks.binder"],
  ["xbm", "image/x-xbitmap"],
  ["xca", "application/xcap-caps+xml"],
  ["xcs", "application/calendar+xml"],
  ["xdf", "application/xcap-diff+xml"],
  ["xdm", "application/vnd.syncml.dm+xml"],
  ["xdp", "application/vnd.adobe.xdp+xml"],
  ["xdssc", "application/dssc+xml"],
  ["xdw", "application/vnd.fujixerox.docuworks"],
  ["xel", "application/xcap-el+xml"],
  ["xenc", "application/xenc+xml"],
  ["xer", "application/patch-ops-error+xml"],
  ["xfdf", "application/vnd.adobe.xfdf"],
  ["xfdl", "application/vnd.xfdl"],
  ["xht", "application/xhtml+xml"],
  ["xhtml", "application/xhtml+xml"],
  ["xhvml", "application/xv+xml"],
  ["xif", "image/vnd.xiff"],
  ["xl", "application/excel"],
  ["xla", "application/vnd.ms-excel"],
  ["xlam", "application/vnd.ms-excel.addin.macroEnabled.12"],
  ["xlc", "application/vnd.ms-excel"],
  ["xlf", "application/xliff+xml"],
  ["xlm", "application/vnd.ms-excel"],
  ["xls", "application/vnd.ms-excel"],
  ["xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"],
  ["xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"],
  ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  ["xlt", "application/vnd.ms-excel"],
  ["xltm", "application/vnd.ms-excel.template.macroEnabled.12"],
  ["xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"],
  ["xlw", "application/vnd.ms-excel"],
  ["xm", "audio/xm"],
  ["xml", "application/xml"],
  ["xns", "application/xcap-ns+xml"],
  ["xo", "application/vnd.olpc-sugar"],
  ["xop", "application/xop+xml"],
  ["xpi", "application/x-xpinstall"],
  ["xpl", "application/xproc+xml"],
  ["xpm", "image/x-xpixmap"],
  ["xpr", "application/vnd.is-xpr"],
  ["xps", "application/vnd.ms-xpsdocument"],
  ["xpw", "application/vnd.intercon.formnet"],
  ["xpx", "application/vnd.intercon.formnet"],
  ["xsd", "application/xml"],
  ["xsl", "application/xml"],
  ["xslt", "application/xslt+xml"],
  ["xsm", "application/vnd.syncml+xml"],
  ["xspf", "application/xspf+xml"],
  ["xul", "application/vnd.mozilla.xul+xml"],
  ["xvm", "application/xv+xml"],
  ["xvml", "application/xv+xml"],
  ["xwd", "image/x-xwindowdump"],
  ["xyz", "chemical/x-xyz"],
  ["xz", "application/x-xz"],
  ["yaml", "text/yaml"],
  ["yang", "application/yang"],
  ["yin", "application/yin+xml"],
  ["yml", "text/yaml"],
  ["ymp", "text/x-suse-ymp"],
  ["z", "application/x-compress"],
  ["z1", "application/x-zmachine"],
  ["z2", "application/x-zmachine"],
  ["z3", "application/x-zmachine"],
  ["z4", "application/x-zmachine"],
  ["z5", "application/x-zmachine"],
  ["z6", "application/x-zmachine"],
  ["z7", "application/x-zmachine"],
  ["z8", "application/x-zmachine"],
  ["zaz", "application/vnd.zzazz.deck+xml"],
  ["zip", "application/zip"],
  ["zir", "application/vnd.zul"],
  ["zirz", "application/vnd.zul"],
  ["zmm", "application/vnd.handheld-entertainment+xml"],
  ["zsh", "text/x-scriptzsh"]
]);
function toFileWithPath(file, path, h3) {
  const f3 = withMimeType(file);
  const { webkitRelativePath } = file;
  const p3 = typeof path === "string" ? path : typeof webkitRelativePath === "string" && webkitRelativePath.length > 0 ? webkitRelativePath : `./${file.name}`;
  if (typeof f3.path !== "string") {
    setObjProp(f3, "path", p3);
  }
  if (h3 !== void 0) {
    Object.defineProperty(f3, "handle", {
      value: h3,
      writable: false,
      configurable: false,
      enumerable: true
    });
  }
  setObjProp(f3, "relativePath", p3);
  return f3;
}
function withMimeType(file) {
  const { name } = file;
  const hasExtension = name && name.lastIndexOf(".") !== -1;
  if (hasExtension && !file.type) {
    const ext = name.split(".").pop().toLowerCase();
    const type = COMMON_MIME_TYPES.get(ext);
    if (type) {
      Object.defineProperty(file, "type", {
        value: type,
        writable: false,
        configurable: false,
        enumerable: true
      });
    }
  }
  return file;
}
function setObjProp(f3, key, value) {
  Object.defineProperty(f3, key, {
    value,
    writable: false,
    configurable: false,
    enumerable: true
  });
}

// node_modules/file-selector/dist/es2015/file-selector.js
var FILES_TO_IGNORE = [
  // Thumbnail cache files for macOS and Windows
  ".DS_Store",
  // macOs
  "Thumbs.db"
  // Windows
];
function fromEvent(evt) {
  return __awaiter5(this, void 0, void 0, function* () {
    if (isObject(evt) && isDataTransfer(evt.dataTransfer)) {
      return getDataTransferFiles(evt.dataTransfer, evt.type);
    } else if (isChangeEvt(evt)) {
      return getInputFiles(evt);
    } else if (Array.isArray(evt) && evt.every((item) => "getFile" in item && typeof item.getFile === "function")) {
      return getFsHandleFiles(evt);
    }
    return [];
  });
}
function isDataTransfer(value) {
  return isObject(value);
}
function isChangeEvt(value) {
  return isObject(value) && isObject(value.target);
}
function isObject(v5) {
  return typeof v5 === "object" && v5 !== null;
}
function getInputFiles(evt) {
  return fromList(evt.target.files).map((file) => toFileWithPath(file));
}
function getFsHandleFiles(handles) {
  return __awaiter5(this, void 0, void 0, function* () {
    const files = yield Promise.all(handles.map((h3) => h3.getFile()));
    return files.map((file) => toFileWithPath(file));
  });
}
function getDataTransferFiles(dt, type) {
  return __awaiter5(this, void 0, void 0, function* () {
    if (dt.items) {
      const items = fromList(dt.items).filter((item) => item.kind === "file");
      if (type !== "drop") {
        return items;
      }
      const files = yield Promise.all(items.map(toFilePromises));
      return noIgnoredFiles(flatten(files));
    }
    return noIgnoredFiles(fromList(dt.files).map((file) => toFileWithPath(file)));
  });
}
function noIgnoredFiles(files) {
  return files.filter((file) => FILES_TO_IGNORE.indexOf(file.name) === -1);
}
function fromList(items) {
  if (items === null) {
    return [];
  }
  const files = [];
  for (let i3 = 0; i3 < items.length; i3++) {
    const file = items[i3];
    files.push(file);
  }
  return files;
}
function toFilePromises(item) {
  if (typeof item.webkitGetAsEntry !== "function") {
    return fromDataTransferItem(item);
  }
  const entry = item.webkitGetAsEntry();
  if (entry && entry.isDirectory) {
    return fromDirEntry(entry);
  }
  return fromDataTransferItem(item, entry);
}
function flatten(items) {
  return items.reduce((acc, files) => [
    ...acc,
    ...Array.isArray(files) ? flatten(files) : [files]
  ], []);
}
function fromDataTransferItem(item, entry) {
  return __awaiter5(this, void 0, void 0, function* () {
    var _a5;
    if (globalThis.isSecureContext && typeof item.getAsFileSystemHandle === "function") {
      const h3 = yield item.getAsFileSystemHandle();
      if (h3 === null) {
        throw new Error(`${item} is not a File`);
      }
      if (h3 !== void 0) {
        const file2 = yield h3.getFile();
        file2.handle = h3;
        return toFileWithPath(file2);
      }
    }
    const file = item.getAsFile();
    if (!file) {
      throw new Error(`${item} is not a File`);
    }
    const fwp = toFileWithPath(file, (_a5 = entry === null || entry === void 0 ? void 0 : entry.fullPath) !== null && _a5 !== void 0 ? _a5 : void 0);
    return fwp;
  });
}
function fromEntry(entry) {
  return __awaiter5(this, void 0, void 0, function* () {
    return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);
  });
}
function fromDirEntry(entry) {
  const reader = entry.createReader();
  return new Promise((resolve, reject) => {
    const entries = [];
    function readEntries() {
      reader.readEntries((batch) => __awaiter5(this, void 0, void 0, function* () {
        if (!batch.length) {
          try {
            const files = yield Promise.all(entries);
            resolve(files);
          } catch (err) {
            reject(err);
          }
        } else {
          const items = Promise.all(batch.map(fromEntry));
          entries.push(items);
          readEntries();
        }
      }), (err) => {
        reject(err);
      });
    }
    readEntries();
  });
}
function fromFileEntry(entry) {
  return __awaiter5(this, void 0, void 0, function* () {
    return new Promise((resolve, reject) => {
      entry.file((file) => {
        const fwp = toFileWithPath(file, entry.fullPath);
        resolve(fwp);
      }, (err) => {
        reject(err);
      });
    });
  });
}

// node_modules/react-dropzone/dist/es/utils/index.js
var import_attr_accept = __toESM(require_es());
function _toConsumableArray(arr2) {
  return _arrayWithoutHoles(arr2) || _iterableToArray(arr2) || _unsupportedIterableToArray(arr2) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
    return Array.from(iter);
}
function _arrayWithoutHoles(arr2) {
  if (Array.isArray(arr2))
    return _arrayLikeToArray(arr2);
}
function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function(sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source = null != arguments[i3] ? arguments[i3] : {};
    i3 % 2 ? ownKeys(Object(source), true).forEach(function(key) {
      _defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _slicedToArray(arr2, i3) {
  return _arrayWithHoles(arr2) || _iterableToArrayLimit(arr2, i3) || _unsupportedIterableToArray(arr2, i3) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o3, minLen) {
  if (!o3)
    return;
  if (typeof o3 === "string")
    return _arrayLikeToArray(o3, minLen);
  var n4 = Object.prototype.toString.call(o3).slice(8, -1);
  if (n4 === "Object" && o3.constructor)
    n4 = o3.constructor.name;
  if (n4 === "Map" || n4 === "Set")
    return Array.from(o3);
  if (n4 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n4))
    return _arrayLikeToArray(o3, minLen);
}
function _arrayLikeToArray(arr2, len) {
  if (len == null || len > arr2.length)
    len = arr2.length;
  for (var i3 = 0, arr22 = new Array(len); i3 < len; i3++) {
    arr22[i3] = arr2[i3];
  }
  return arr22;
}
function _iterableToArrayLimit(arr2, i3) {
  var _i = arr2 == null ? null : typeof Symbol !== "undefined" && arr2[Symbol.iterator] || arr2["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e;
  try {
    for (_i = _i.call(arr2); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i3 && _arr.length === i3)
        break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e;
    }
  }
  return _arr;
}
function _arrayWithHoles(arr2) {
  if (Array.isArray(arr2))
    return arr2;
}
var accepts = typeof import_attr_accept.default === "function" ? import_attr_accept.default : import_attr_accept.default.default;
var FILE_INVALID_TYPE = "file-invalid-type";
var FILE_TOO_LARGE = "file-too-large";
var FILE_TOO_SMALL = "file-too-small";
var TOO_MANY_FILES = "too-many-files";
var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr2() {
  var accept = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
  var acceptArr = accept.split(",");
  var msg = acceptArr.length > 1 ? "one of ".concat(acceptArr.join(", ")) : acceptArr[0];
  return {
    code: FILE_INVALID_TYPE,
    message: "File type must be ".concat(msg)
  };
};
var getTooLargeRejectionErr = function getTooLargeRejectionErr2(maxSize) {
  return {
    code: FILE_TOO_LARGE,
    message: "File is larger than ".concat(maxSize, " ").concat(maxSize === 1 ? "byte" : "bytes")
  };
};
var getTooSmallRejectionErr = function getTooSmallRejectionErr2(minSize) {
  return {
    code: FILE_TOO_SMALL,
    message: "File is smaller than ".concat(minSize, " ").concat(minSize === 1 ? "byte" : "bytes")
  };
};
var TOO_MANY_FILES_REJECTION = {
  code: TOO_MANY_FILES,
  message: "Too many files"
};
function fileAccepted(file, accept) {
  var isAcceptable = file.type === "application/x-moz-file" || accepts(file, accept);
  return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];
}
function fileMatchSize(file, minSize, maxSize) {
  if (isDefined(file.size)) {
    if (isDefined(minSize) && isDefined(maxSize)) {
      if (file.size > maxSize)
        return [false, getTooLargeRejectionErr(maxSize)];
      if (file.size < minSize)
        return [false, getTooSmallRejectionErr(minSize)];
    } else if (isDefined(minSize) && file.size < minSize)
      return [false, getTooSmallRejectionErr(minSize)];
    else if (isDefined(maxSize) && file.size > maxSize)
      return [false, getTooLargeRejectionErr(maxSize)];
  }
  return [true, null];
}
function isDefined(value) {
  return value !== void 0 && value !== null;
}
function allFilesAccepted(_ref) {
  var files = _ref.files, accept = _ref.accept, minSize = _ref.minSize, maxSize = _ref.maxSize, multiple = _ref.multiple, maxFiles = _ref.maxFiles, validator2 = _ref.validator;
  if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) {
    return false;
  }
  return files.every(function(file) {
    var _fileAccepted = fileAccepted(file, accept), _fileAccepted2 = _slicedToArray(_fileAccepted, 1), accepted = _fileAccepted2[0];
    var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray(_fileMatchSize, 1), sizeMatch = _fileMatchSize2[0];
    var customErrors = validator2 ? validator2(file) : null;
    return accepted && sizeMatch && !customErrors;
  });
}
function isPropagationStopped(event) {
  if (typeof event.isPropagationStopped === "function") {
    return event.isPropagationStopped();
  } else if (typeof event.cancelBubble !== "undefined") {
    return event.cancelBubble;
  }
  return false;
}
function isEvtWithFiles(event) {
  if (!event.dataTransfer) {
    return !!event.target && !!event.target.files;
  }
  return Array.prototype.some.call(event.dataTransfer.types, function(type) {
    return type === "Files" || type === "application/x-moz-file";
  });
}
function onDocumentDragOver(event) {
  event.preventDefault();
}
function isIe(userAgent) {
  return userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1;
}
function isEdge(userAgent) {
  return userAgent.indexOf("Edge/") !== -1;
}
function isIeOrEdge() {
  var userAgent = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.navigator.userAgent;
  return isIe(userAgent) || isEdge(userAgent);
}
function composeEventHandlers5() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return function(event) {
    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }
    return fns.some(function(fn) {
      if (!isPropagationStopped(event) && fn) {
        fn.apply(void 0, [event].concat(args));
      }
      return isPropagationStopped(event);
    });
  };
}
function canUseFileSystemAccessAPI() {
  return "showOpenFilePicker" in window;
}
function pickerOptionsFromAccept(accept) {
  if (isDefined(accept)) {
    var acceptForPicker = Object.entries(accept).filter(function(_ref2) {
      var _ref3 = _slicedToArray(_ref2, 2), mimeType = _ref3[0], ext = _ref3[1];
      var ok = true;
      if (!isMIMEType(mimeType)) {
        console.warn('Skipped "'.concat(mimeType, '" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.'));
        ok = false;
      }
      if (!Array.isArray(ext) || !ext.every(isExt)) {
        console.warn('Skipped "'.concat(mimeType, '" because an invalid file extension was provided.'));
        ok = false;
      }
      return ok;
    }).reduce(function(agg, _ref4) {
      var _ref5 = _slicedToArray(_ref4, 2), mimeType = _ref5[0], ext = _ref5[1];
      return _objectSpread(_objectSpread({}, agg), {}, _defineProperty({}, mimeType, ext));
    }, {});
    return [{
      // description is required due to https://crbug.com/1264708
      description: "Files",
      accept: acceptForPicker
    }];
  }
  return accept;
}
function acceptPropAsAcceptAttr(accept) {
  if (isDefined(accept)) {
    return Object.entries(accept).reduce(function(a3, _ref6) {
      var _ref7 = _slicedToArray(_ref6, 2), mimeType = _ref7[0], ext = _ref7[1];
      return [].concat(_toConsumableArray(a3), [mimeType], _toConsumableArray(ext));
    }, []).filter(function(v5) {
      return isMIMEType(v5) || isExt(v5);
    }).join(",");
  }
  return void 0;
}
function isAbort(v5) {
  return v5 instanceof DOMException && (v5.name === "AbortError" || v5.code === v5.ABORT_ERR);
}
function isSecurityError(v5) {
  return v5 instanceof DOMException && (v5.name === "SecurityError" || v5.code === v5.SECURITY_ERR);
}
function isMIMEType(v5) {
  return v5 === "audio/*" || v5 === "video/*" || v5 === "image/*" || v5 === "text/*" || v5 === "application/*" || /\w+\/[-+.\w]+/g.test(v5);
}
function isExt(v5) {
  return /^.*\.[\w]+$/.test(v5);
}

// node_modules/react-dropzone/dist/es/index.js
var _excluded = ["children"];
var _excluded2 = ["open"];
var _excluded3 = ["refKey", "role", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"];
var _excluded4 = ["refKey", "onChange", "onClick"];
function _toConsumableArray2(arr2) {
  return _arrayWithoutHoles2(arr2) || _iterableToArray2(arr2) || _unsupportedIterableToArray2(arr2) || _nonIterableSpread2();
}
function _nonIterableSpread2() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArray2(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
    return Array.from(iter);
}
function _arrayWithoutHoles2(arr2) {
  if (Array.isArray(arr2))
    return _arrayLikeToArray2(arr2);
}
function _slicedToArray2(arr2, i3) {
  return _arrayWithHoles2(arr2) || _iterableToArrayLimit2(arr2, i3) || _unsupportedIterableToArray2(arr2, i3) || _nonIterableRest2();
}
function _nonIterableRest2() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray2(o3, minLen) {
  if (!o3)
    return;
  if (typeof o3 === "string")
    return _arrayLikeToArray2(o3, minLen);
  var n4 = Object.prototype.toString.call(o3).slice(8, -1);
  if (n4 === "Object" && o3.constructor)
    n4 = o3.constructor.name;
  if (n4 === "Map" || n4 === "Set")
    return Array.from(o3);
  if (n4 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n4))
    return _arrayLikeToArray2(o3, minLen);
}
function _arrayLikeToArray2(arr2, len) {
  if (len == null || len > arr2.length)
    len = arr2.length;
  for (var i3 = 0, arr22 = new Array(len); i3 < len; i3++) {
    arr22[i3] = arr2[i3];
  }
  return arr22;
}
function _iterableToArrayLimit2(arr2, i3) {
  var _i = arr2 == null ? null : typeof Symbol !== "undefined" && arr2[Symbol.iterator] || arr2["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e;
  try {
    for (_i = _i.call(arr2); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i3 && _arr.length === i3)
        break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e;
    }
  }
  return _arr;
}
function _arrayWithHoles2(arr2) {
  if (Array.isArray(arr2))
    return arr2;
}
function ownKeys2(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function(sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread2(target) {
  for (var i3 = 1; i3 < arguments.length; i3++) {
    var source = null != arguments[i3] ? arguments[i3] : {};
    i3 % 2 ? ownKeys2(Object(source), true).forEach(function(key) {
      _defineProperty2(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null)
    return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i3;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i3 = 0; i3 < sourceSymbolKeys.length; i3++) {
      key = sourceSymbolKeys[i3];
      if (excluded.indexOf(key) >= 0)
        continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key))
        continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i3;
  for (i3 = 0; i3 < sourceKeys.length; i3++) {
    key = sourceKeys[i3];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source[key];
  }
  return target;
}
var Dropzone = /* @__PURE__ */ (0, import_react13.forwardRef)(function(_ref, ref) {
  var children = _ref.children, params = _objectWithoutProperties(_ref, _excluded);
  var _useDropzone = useDropzone(params), open = _useDropzone.open, props = _objectWithoutProperties(_useDropzone, _excluded2);
  (0, import_react13.useImperativeHandle)(ref, function() {
    return {
      open
    };
  }, [open]);
  return /* @__PURE__ */ import_react13.default.createElement(import_react13.Fragment, null, children(_objectSpread2(_objectSpread2({}, props), {}, {
    open
  })));
});
Dropzone.displayName = "Dropzone";
var defaultProps = {
  disabled: false,
  getFilesFromEvent: fromEvent,
  maxSize: Infinity,
  minSize: 0,
  multiple: true,
  maxFiles: 0,
  preventDropOnDocument: true,
  noClick: false,
  noKeyboard: false,
  noDrag: false,
  noDragEventsBubbling: false,
  validator: null,
  useFsAccessApi: false,
  autoFocus: false
};
Dropzone.defaultProps = defaultProps;
Dropzone.propTypes = {
  /**
   * Render function that exposes the dropzone state and prop getter fns
   *
   * @param {object} params
   * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render
   * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render
   * @param {Function} params.open Open the native file selection dialog
   * @param {boolean} params.isFocused Dropzone area is in focus
   * @param {boolean} params.isFileDialogActive File dialog is opened
   * @param {boolean} params.isDragActive Active drag is in progress
   * @param {boolean} params.isDragAccept Dragged files are accepted
   * @param {boolean} params.isDragReject Some dragged files are rejected
   * @param {File[]} params.acceptedFiles Accepted files
   * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected
   */
  children: import_prop_types.default.func,
  /**
   * Set accepted file types.
   * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
   * Keep in mind that mime type determination is not reliable across platforms. CSV files,
   * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
   * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).
   */
  accept: import_prop_types.default.objectOf(import_prop_types.default.arrayOf(import_prop_types.default.string)),
  /**
   * Allow drag 'n' drop (or selection from the file dialog) of multiple files
   */
  multiple: import_prop_types.default.bool,
  /**
   * If false, allow dropped items to take over the current browser window
   */
  preventDropOnDocument: import_prop_types.default.bool,
  /**
   * If true, disables click to open the native file selection dialog
   */
  noClick: import_prop_types.default.bool,
  /**
   * If true, disables SPACE/ENTER to open the native file selection dialog.
   * Note that it also stops tracking the focus state.
   */
  noKeyboard: import_prop_types.default.bool,
  /**
   * If true, disables drag 'n' drop
   */
  noDrag: import_prop_types.default.bool,
  /**
   * If true, stops drag event propagation to parents
   */
  noDragEventsBubbling: import_prop_types.default.bool,
  /**
   * Minimum file size (in bytes)
   */
  minSize: import_prop_types.default.number,
  /**
   * Maximum file size (in bytes)
   */
  maxSize: import_prop_types.default.number,
  /**
   * Maximum accepted number of files
   * The default value is 0 which means there is no limitation to how many files are accepted.
   */
  maxFiles: import_prop_types.default.number,
  /**
   * Enable/disable the dropzone
   */
  disabled: import_prop_types.default.bool,
  /**
   * Use this to provide a custom file aggregator
   *
   * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
   */
  getFilesFromEvent: import_prop_types.default.func,
  /**
   * Cb for when closing the file dialog with no selection
   */
  onFileDialogCancel: import_prop_types.default.func,
  /**
   * Cb for when opening the file dialog
   */
  onFileDialogOpen: import_prop_types.default.func,
  /**
   * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
   * to open the file picker instead of using an `<input type="file">` click event.
   */
  useFsAccessApi: import_prop_types.default.bool,
  /**
   * Set to true to focus the root element on render
   */
  autoFocus: import_prop_types.default.bool,
  /**
   * Cb for when the `dragenter` event occurs.
   *
   * @param {DragEvent} event
   */
  onDragEnter: import_prop_types.default.func,
  /**
   * Cb for when the `dragleave` event occurs
   *
   * @param {DragEvent} event
   */
  onDragLeave: import_prop_types.default.func,
  /**
   * Cb for when the `dragover` event occurs
   *
   * @param {DragEvent} event
   */
  onDragOver: import_prop_types.default.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
   *
   * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
   * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.
   * If `multiple` is set to false and additional files are dropped,
   * all files besides the first will be rejected.
   * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
   *
   * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
   * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
   *
   * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.
   * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
   *
   * ```js
   * function onDrop(acceptedFiles) {
   *   const req = request.post('/upload')
   *   acceptedFiles.forEach(file => {
   *     req.attach(file.name, file)
   *   })
   *   req.end(callback)
   * }
   * ```
   *
   * @param {File[]} acceptedFiles
   * @param {FileRejection[]} fileRejections
   * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
   */
  onDrop: import_prop_types.default.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that if no files are accepted, this callback is not invoked.
   *
   * @param {File[]} files
   * @param {(DragEvent|Event)} event
   */
  onDropAccepted: import_prop_types.default.func,
  /**
   * Cb for when the `drop` event occurs.
   * Note that if no files are rejected, this callback is not invoked.
   *
   * @param {FileRejection[]} fileRejections
   * @param {(DragEvent|Event)} event
   */
  onDropRejected: import_prop_types.default.func,
  /**
   * Cb for when there's some error from any of the promises.
   *
   * @param {Error} error
   */
  onError: import_prop_types.default.func,
  /**
   * Custom validation function. It must return null if there's no errors.
   * @param {File} file
   * @returns {FileError|FileError[]|null}
   */
  validator: import_prop_types.default.func
};
var initialState = {
  isFocused: false,
  isFileDialogActive: false,
  isDragActive: false,
  isDragAccept: false,
  isDragReject: false,
  acceptedFiles: [],
  fileRejections: []
};
function useDropzone() {
  var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  var _defaultProps$props = _objectSpread2(_objectSpread2({}, defaultProps), props), accept = _defaultProps$props.accept, disabled = _defaultProps$props.disabled, getFilesFromEvent = _defaultProps$props.getFilesFromEvent, maxSize = _defaultProps$props.maxSize, minSize = _defaultProps$props.minSize, multiple = _defaultProps$props.multiple, maxFiles = _defaultProps$props.maxFiles, onDragEnter = _defaultProps$props.onDragEnter, onDragLeave = _defaultProps$props.onDragLeave, onDragOver = _defaultProps$props.onDragOver, onDrop = _defaultProps$props.onDrop, onDropAccepted = _defaultProps$props.onDropAccepted, onDropRejected = _defaultProps$props.onDropRejected, onFileDialogCancel = _defaultProps$props.onFileDialogCancel, onFileDialogOpen = _defaultProps$props.onFileDialogOpen, useFsAccessApi = _defaultProps$props.useFsAccessApi, autoFocus = _defaultProps$props.autoFocus, preventDropOnDocument = _defaultProps$props.preventDropOnDocument, noClick = _defaultProps$props.noClick, noKeyboard = _defaultProps$props.noKeyboard, noDrag = _defaultProps$props.noDrag, noDragEventsBubbling = _defaultProps$props.noDragEventsBubbling, onError = _defaultProps$props.onError, validator2 = _defaultProps$props.validator;
  var acceptAttr = (0, import_react13.useMemo)(function() {
    return acceptPropAsAcceptAttr(accept);
  }, [accept]);
  var pickerTypes = (0, import_react13.useMemo)(function() {
    return pickerOptionsFromAccept(accept);
  }, [accept]);
  var onFileDialogOpenCb = (0, import_react13.useMemo)(function() {
    return typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop;
  }, [onFileDialogOpen]);
  var onFileDialogCancelCb = (0, import_react13.useMemo)(function() {
    return typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop;
  }, [onFileDialogCancel]);
  var rootRef = (0, import_react13.useRef)(null);
  var inputRef = (0, import_react13.useRef)(null);
  var _useReducer = (0, import_react13.useReducer)(reducer, initialState), _useReducer2 = _slicedToArray2(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1];
  var isFocused = state.isFocused, isFileDialogActive = state.isFileDialogActive;
  var fsAccessApiWorksRef = (0, import_react13.useRef)(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI());
  var onWindowFocus = function onWindowFocus2() {
    if (!fsAccessApiWorksRef.current && isFileDialogActive) {
      setTimeout(function() {
        if (inputRef.current) {
          var files = inputRef.current.files;
          if (!files.length) {
            dispatch({
              type: "closeDialog"
            });
            onFileDialogCancelCb();
          }
        }
      }, 300);
    }
  };
  (0, import_react13.useEffect)(function() {
    window.addEventListener("focus", onWindowFocus, false);
    return function() {
      window.removeEventListener("focus", onWindowFocus, false);
    };
  }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]);
  var dragTargetsRef = (0, import_react13.useRef)([]);
  var onDocumentDrop = function onDocumentDrop2(event) {
    if (rootRef.current && rootRef.current.contains(event.target)) {
      return;
    }
    event.preventDefault();
    dragTargetsRef.current = [];
  };
  (0, import_react13.useEffect)(function() {
    if (preventDropOnDocument) {
      document.addEventListener("dragover", onDocumentDragOver, false);
      document.addEventListener("drop", onDocumentDrop, false);
    }
    return function() {
      if (preventDropOnDocument) {
        document.removeEventListener("dragover", onDocumentDragOver);
        document.removeEventListener("drop", onDocumentDrop);
      }
    };
  }, [rootRef, preventDropOnDocument]);
  (0, import_react13.useEffect)(function() {
    if (!disabled && autoFocus && rootRef.current) {
      rootRef.current.focus();
    }
    return function() {
    };
  }, [rootRef, autoFocus, disabled]);
  var onErrCb = (0, import_react13.useCallback)(function(e3) {
    if (onError) {
      onError(e3);
    } else {
      console.error(e3);
    }
  }, [onError]);
  var onDragEnterCb = (0, import_react13.useCallback)(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    dragTargetsRef.current = [].concat(_toConsumableArray2(dragTargetsRef.current), [event.target]);
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function(files) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        var fileCount = files.length;
        var isDragAccept = fileCount > 0 && allFilesAccepted({
          files,
          accept: acceptAttr,
          minSize,
          maxSize,
          multiple,
          maxFiles,
          validator: validator2
        });
        var isDragReject = fileCount > 0 && !isDragAccept;
        dispatch({
          isDragAccept,
          isDragReject,
          isDragActive: true,
          type: "setDraggedFiles"
        });
        if (onDragEnter) {
          onDragEnter(event);
        }
      }).catch(function(e3) {
        return onErrCb(e3);
      });
    }
  }, [getFilesFromEvent, onDragEnter, onErrCb, noDragEventsBubbling, acceptAttr, minSize, maxSize, multiple, maxFiles, validator2]);
  var onDragOverCb = (0, import_react13.useCallback)(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    var hasFiles = isEvtWithFiles(event);
    if (hasFiles && event.dataTransfer) {
      try {
        event.dataTransfer.dropEffect = "copy";
      } catch (_unused) {
      }
    }
    if (hasFiles && onDragOver) {
      onDragOver(event);
    }
    return false;
  }, [onDragOver, noDragEventsBubbling]);
  var onDragLeaveCb = (0, import_react13.useCallback)(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    var targets = dragTargetsRef.current.filter(function(target) {
      return rootRef.current && rootRef.current.contains(target);
    });
    var targetIdx = targets.indexOf(event.target);
    if (targetIdx !== -1) {
      targets.splice(targetIdx, 1);
    }
    dragTargetsRef.current = targets;
    if (targets.length > 0) {
      return;
    }
    dispatch({
      type: "setDraggedFiles",
      isDragActive: false,
      isDragAccept: false,
      isDragReject: false
    });
    if (isEvtWithFiles(event) && onDragLeave) {
      onDragLeave(event);
    }
  }, [rootRef, onDragLeave, noDragEventsBubbling]);
  var setFiles = (0, import_react13.useCallback)(function(files, event) {
    var acceptedFiles = [];
    var fileRejections = [];
    files.forEach(function(file) {
      var _fileAccepted = fileAccepted(file, acceptAttr), _fileAccepted2 = _slicedToArray2(_fileAccepted, 2), accepted = _fileAccepted2[0], acceptError = _fileAccepted2[1];
      var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray2(_fileMatchSize, 2), sizeMatch = _fileMatchSize2[0], sizeError = _fileMatchSize2[1];
      var customErrors = validator2 ? validator2(file) : null;
      if (accepted && sizeMatch && !customErrors) {
        acceptedFiles.push(file);
      } else {
        var errors2 = [acceptError, sizeError];
        if (customErrors) {
          errors2 = errors2.concat(customErrors);
        }
        fileRejections.push({
          file,
          errors: errors2.filter(function(e3) {
            return e3;
          })
        });
      }
    });
    if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {
      acceptedFiles.forEach(function(file) {
        fileRejections.push({
          file,
          errors: [TOO_MANY_FILES_REJECTION]
        });
      });
      acceptedFiles.splice(0);
    }
    dispatch({
      acceptedFiles,
      fileRejections,
      isDragReject: fileRejections.length > 0,
      type: "setFiles"
    });
    if (onDrop) {
      onDrop(acceptedFiles, fileRejections, event);
    }
    if (fileRejections.length > 0 && onDropRejected) {
      onDropRejected(fileRejections, event);
    }
    if (acceptedFiles.length > 0 && onDropAccepted) {
      onDropAccepted(acceptedFiles, event);
    }
  }, [dispatch, multiple, acceptAttr, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator2]);
  var onDropCb = (0, import_react13.useCallback)(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    dragTargetsRef.current = [];
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function(files) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        setFiles(files, event);
      }).catch(function(e3) {
        return onErrCb(e3);
      });
    }
    dispatch({
      type: "reset"
    });
  }, [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]);
  var openFileDialog = (0, import_react13.useCallback)(function() {
    if (fsAccessApiWorksRef.current) {
      dispatch({
        type: "openDialog"
      });
      onFileDialogOpenCb();
      var opts = {
        multiple,
        types: pickerTypes
      };
      window.showOpenFilePicker(opts).then(function(handles) {
        return getFilesFromEvent(handles);
      }).then(function(files) {
        setFiles(files, null);
        dispatch({
          type: "closeDialog"
        });
      }).catch(function(e3) {
        if (isAbort(e3)) {
          onFileDialogCancelCb(e3);
          dispatch({
            type: "closeDialog"
          });
        } else if (isSecurityError(e3)) {
          fsAccessApiWorksRef.current = false;
          if (inputRef.current) {
            inputRef.current.value = null;
            inputRef.current.click();
          } else {
            onErrCb(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."));
          }
        } else {
          onErrCb(e3);
        }
      });
      return;
    }
    if (inputRef.current) {
      dispatch({
        type: "openDialog"
      });
      onFileDialogOpenCb();
      inputRef.current.value = null;
      inputRef.current.click();
    }
  }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, onErrCb, pickerTypes, multiple]);
  var onKeyDownCb = (0, import_react13.useCallback)(function(event) {
    if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
      return;
    }
    if (event.key === " " || event.key === "Enter" || event.keyCode === 32 || event.keyCode === 13) {
      event.preventDefault();
      openFileDialog();
    }
  }, [rootRef, openFileDialog]);
  var onFocusCb = (0, import_react13.useCallback)(function() {
    dispatch({
      type: "focus"
    });
  }, []);
  var onBlurCb = (0, import_react13.useCallback)(function() {
    dispatch({
      type: "blur"
    });
  }, []);
  var onClickCb = (0, import_react13.useCallback)(function() {
    if (noClick) {
      return;
    }
    if (isIeOrEdge()) {
      setTimeout(openFileDialog, 0);
    } else {
      openFileDialog();
    }
  }, [noClick, openFileDialog]);
  var composeHandler = function composeHandler2(fn) {
    return disabled ? null : fn;
  };
  var composeKeyboardHandler = function composeKeyboardHandler2(fn) {
    return noKeyboard ? null : composeHandler(fn);
  };
  var composeDragHandler = function composeDragHandler2(fn) {
    return noDrag ? null : composeHandler(fn);
  };
  var stopPropagation = function stopPropagation2(event) {
    if (noDragEventsBubbling) {
      event.stopPropagation();
    }
  };
  var getRootProps = (0, import_react13.useMemo)(function() {
    return function() {
      var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref2$refKey = _ref2.refKey, refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey, role = _ref2.role, onKeyDown = _ref2.onKeyDown, onFocus = _ref2.onFocus, onBlur = _ref2.onBlur, onClick = _ref2.onClick, onDragEnter2 = _ref2.onDragEnter, onDragOver2 = _ref2.onDragOver, onDragLeave2 = _ref2.onDragLeave, onDrop2 = _ref2.onDrop, rest = _objectWithoutProperties(_ref2, _excluded3);
      return _objectSpread2(_objectSpread2(_defineProperty2({
        onKeyDown: composeKeyboardHandler(composeEventHandlers5(onKeyDown, onKeyDownCb)),
        onFocus: composeKeyboardHandler(composeEventHandlers5(onFocus, onFocusCb)),
        onBlur: composeKeyboardHandler(composeEventHandlers5(onBlur, onBlurCb)),
        onClick: composeHandler(composeEventHandlers5(onClick, onClickCb)),
        onDragEnter: composeDragHandler(composeEventHandlers5(onDragEnter2, onDragEnterCb)),
        onDragOver: composeDragHandler(composeEventHandlers5(onDragOver2, onDragOverCb)),
        onDragLeave: composeDragHandler(composeEventHandlers5(onDragLeave2, onDragLeaveCb)),
        onDrop: composeDragHandler(composeEventHandlers5(onDrop2, onDropCb)),
        role: typeof role === "string" && role !== "" ? role : "presentation"
      }, refKey, rootRef), !disabled && !noKeyboard ? {
        tabIndex: 0
      } : {}), rest);
    };
  }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);
  var onInputElementClick = (0, import_react13.useCallback)(function(event) {
    event.stopPropagation();
  }, []);
  var getInputProps = (0, import_react13.useMemo)(function() {
    return function() {
      var _ref3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref3$refKey = _ref3.refKey, refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey, onChange = _ref3.onChange, onClick = _ref3.onClick, rest = _objectWithoutProperties(_ref3, _excluded4);
      var inputProps = _defineProperty2({
        accept: acceptAttr,
        multiple,
        type: "file",
        style: {
          border: 0,
          clip: "rect(0, 0, 0, 0)",
          clipPath: "inset(50%)",
          height: "1px",
          margin: "0 -1px -1px 0",
          overflow: "hidden",
          padding: 0,
          position: "absolute",
          width: "1px",
          whiteSpace: "nowrap"
        },
        onChange: composeHandler(composeEventHandlers5(onChange, onDropCb)),
        onClick: composeHandler(composeEventHandlers5(onClick, onInputElementClick)),
        tabIndex: -1
      }, refKey, inputRef);
      return _objectSpread2(_objectSpread2({}, inputProps), rest);
    };
  }, [inputRef, accept, multiple, onDropCb, disabled]);
  return _objectSpread2(_objectSpread2({}, state), {}, {
    isFocused: isFocused && !disabled,
    getRootProps,
    getInputProps,
    rootRef,
    inputRef,
    open: composeHandler(openFileDialog)
  });
}
function reducer(state, action) {
  switch (action.type) {
    case "focus":
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isFocused: true
      });
    case "blur":
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isFocused: false
      });
    case "openDialog":
      return _objectSpread2(_objectSpread2({}, initialState), {}, {
        isFileDialogActive: true
      });
    case "closeDialog":
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isFileDialogActive: false
      });
    case "setDraggedFiles":
      return _objectSpread2(_objectSpread2({}, state), {}, {
        isDragActive: action.isDragActive,
        isDragAccept: action.isDragAccept,
        isDragReject: action.isDragReject
      });
    case "setFiles":
      return _objectSpread2(_objectSpread2({}, state), {}, {
        acceptedFiles: action.acceptedFiles,
        fileRejections: action.fileRejections,
        isDragReject: action.isDragReject
      });
    case "reset":
      return _objectSpread2({}, initialState);
    default:
      return state;
  }
}
function noop() {
}

// src/components/chat-components/ChatInput.tsx
var ChatInput = (0, import_react14.forwardRef)(
  ({
    inputMessage,
    setInputMessage,
    handleSendMessage,
    isGenerating,
    onStopGenerating,
    app: app2,
    navigateHistory,
    contextNotes,
    setContextNotes,
    includeActiveNote,
    setIncludeActiveNote,
    mention,
    selectedImages,
    onAddImage,
    setSelectedImages
  }, ref) => {
    const [historyIndex, setHistoryIndex] = (0, import_react14.useState)(-1);
    const [tempInput, setTempInput] = (0, import_react14.useState)("");
    const [isModelDropdownOpen, setIsModelDropdownOpen] = (0, import_react14.useState)(false);
    const [contextUrls, setContextUrls] = (0, import_react14.useState)([]);
    const textAreaRef = (0, import_react14.useRef)(null);
    const containerRef = (0, import_react14.useRef)(null);
    const [currentModelKey, setCurrentModelKey] = useModelKey();
    const [currentChain] = useChainType();
    const [currentActiveNote, setCurrentActiveNote] = (0, import_react14.useState)(
      app2.workspace.getActiveFile()
    );
    const settings = useSettingsValue();
    const isCopilotPlus = currentChain === "copilot_plus" /* COPILOT_PLUS_CHAIN */;
    (0, import_react14.useImperativeHandle)(ref, () => ({
      focus: () => {
        textAreaRef.current?.focus();
      }
    }));
    const onSendMessage = (includeVault) => {
      if (!isCopilotPlus) {
        handleSendMessage();
        return;
      }
      handleSendMessage({
        toolCalls: includeVault ? ["@vault"] : [],
        contextNotes,
        urls: contextUrls
      });
    };
    const handleInputChange = async (event) => {
      const inputValue = event.target.value;
      const cursorPos = event.target.selectionStart;
      setInputMessage(inputValue);
      adjustTextareaHeight();
      const urls = mention.extractAllUrls(inputValue);
      const newUrls = urls.filter((url) => !contextUrls.includes(url));
      if (newUrls.length > 0) {
        setContextUrls((prev) => Array.from(/* @__PURE__ */ new Set([...prev, ...newUrls])));
      }
      if (cursorPos >= 2 && inputValue.slice(cursorPos - 2, cursorPos) === "[[") {
        showNoteTitleModal(cursorPos);
      } else if (inputValue === "/") {
        showCustomPromptModal();
      } else if (inputValue.slice(-1) === "@" && isCopilotPlus) {
        showCopilotPlusOptionsModal();
      }
    };
    const adjustTextareaHeight = () => {
      if (textAreaRef.current) {
        textAreaRef.current.style.height = "auto";
        textAreaRef.current.style.height = `${textAreaRef.current.scrollHeight}px`;
      }
    };
    (0, import_react14.useEffect)(() => {
      adjustTextareaHeight();
    }, [inputMessage]);
    const showNoteTitleModal = (cursorPos) => {
      const fetchNoteTitles = async () => {
        const contextProcessor = ContextProcessor.getInstance();
        new AddContextNoteModal({
          app: app2,
          onNoteSelect: async (note) => {
            const before = inputMessage.slice(0, cursorPos - 2);
            const after = inputMessage.slice(cursorPos - 1);
            const newInputMessage = `${before}[[${note.basename}]]${after}`;
            setInputMessage(newInputMessage);
            const activeNote = app2.workspace.getActiveFile();
            if (note) {
              await contextProcessor.addNoteToContext(
                note,
                app2.vault,
                contextNotes,
                activeNote,
                setContextNotes,
                setIncludeActiveNote
              );
            }
            setTimeout(() => {
              if (textAreaRef.current) {
                const newCursorPos = cursorPos + note.basename.length + 2;
                textAreaRef.current.setSelectionRange(newCursorPos, newCursorPos);
              }
            }, 0);
          },
          excludeNotePaths
        }).open();
      };
      fetchNoteTitles();
    };
    const showCustomPromptModal = async () => {
      const customPromptProcessor = CustomPromptProcessor.getInstance(app2.vault);
      const prompts = await customPromptProcessor.getAllPrompts();
      const promptTitles = prompts.map((prompt) => prompt.title);
      new ListPromptModal(app2, promptTitles, async (promptTitle) => {
        const selectedPrompt = prompts.find((prompt) => prompt.title === promptTitle);
        if (selectedPrompt) {
          customPromptProcessor.recordPromptUsage(selectedPrompt.title);
          setInputMessage(selectedPrompt.content);
        }
      }).open();
    };
    const showCopilotPlusOptionsModal = () => {
      const optionsWithDescriptions = COPILOT_TOOL_NAMES.map((option) => ({
        title: option,
        description: getToolDescription(option)
      }));
      new ListPromptModal(
        app2,
        optionsWithDescriptions.map((o3) => o3.title),
        (selectedOption) => {
          setInputMessage(inputMessage + selectedOption + " ");
        },
        // Add descriptions as a separate array
        optionsWithDescriptions.map((o3) => o3.description)
      ).open();
    };
    const handleKeyDown = (e3) => {
      if (e3.nativeEvent.isComposing)
        return;
      const textarea = textAreaRef.current;
      if (!textarea)
        return;
      const { selectionStart, value } = textarea;
      const lines = value.split("\n");
      const currentLineIndex = value.substring(0, selectionStart).split("\n").length - 1;
      if (e3.key === "Enter" && e3.shiftKey && (import_obsidian30.Platform.isMacOS ? e3.metaKey : e3.ctrlKey)) {
        e3.preventDefault();
        e3.stopPropagation();
        onSendMessage(true);
        setHistoryIndex(-1);
        setTempInput("");
        return;
      }
      if (e3.key === "Enter" && !e3.shiftKey) {
        e3.preventDefault();
        onSendMessage(false);
        setHistoryIndex(-1);
        setTempInput("");
      } else if (e3.key === "ArrowUp") {
        if (currentLineIndex > 0 || selectionStart > 0) {
          return;
        }
        e3.preventDefault();
        if (historyIndex === -1 && value.trim() !== "") {
          setTempInput(value);
        }
        const newMessage = navigateHistory("up");
        if (newMessage !== inputMessage) {
          setHistoryIndex(historyIndex + 1);
          setInputMessage(newMessage);
          setTimeout(() => {
            if (textarea) {
              textarea.selectionStart = textarea.selectionEnd = 0;
            }
          }, 0);
        }
      } else if (e3.key === "ArrowDown") {
        if (currentLineIndex < lines.length - 1 || selectionStart < value.length) {
          return;
        }
        e3.preventDefault();
        if (historyIndex > -1) {
          const newMessage = navigateHistory("down");
          setHistoryIndex(historyIndex - 1);
          if (historyIndex === 0) {
            setInputMessage(tempInput);
          } else {
            setInputMessage(newMessage);
          }
          setTimeout(() => {
            if (textarea) {
              textarea.selectionStart = textarea.selectionEnd = 0;
            }
          }, 0);
        }
      }
    };
    const handlePaste = (0, import_react14.useCallback)(
      async (e3) => {
        const items = e3.clipboardData?.items;
        if (!items || !isCopilotPlus)
          return;
        const imageItems = Array.from(items).filter((item) => item.type.indexOf("image") !== -1);
        if (imageItems.length > 0) {
          e3.preventDefault();
          const files = await Promise.all(
            imageItems.map((item) => {
              const file = item.getAsFile();
              if (!file)
                return null;
              return file;
            })
          );
          const validFiles = files.filter((file) => file !== null);
          if (validFiles.length > 0) {
            onAddImage(validFiles);
          }
        }
      },
      [onAddImage, isCopilotPlus]
    );
    (0, import_react14.useEffect)(() => {
      const currentTitles = new Set(extractNoteTitles(inputMessage));
      const currentUrls = mention.extractAllUrls(inputMessage);
      setContextNotes(
        (prev) => prev.filter((note) => {
          const wasAddedManually = note.wasAddedManually === true;
          if (wasAddedManually)
            return true;
          const wasAddedViaReference = note.wasAddedViaReference === true;
          if (note.path === currentActiveNote?.path) {
            if (wasAddedViaReference) {
              return currentTitles.has(note.basename);
            } else {
              return includeActiveNote;
            }
          } else {
            if (wasAddedViaReference) {
              return currentTitles.has(note.basename);
            } else {
              return true;
            }
          }
        })
      );
      setContextUrls((prev) => prev.filter((url) => currentUrls.includes(url)));
    }, [inputMessage, includeActiveNote, currentActiveNote, mention, setContextNotes]);
    (0, import_react14.useEffect)(() => {
      let timeoutId;
      const handleActiveLeafChange = () => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          const activeNote = app2.workspace.getActiveFile();
          setCurrentActiveNote(activeNote);
        }, 100);
      };
      const eventRef = app2.workspace.on("active-leaf-change", handleActiveLeafChange);
      return () => {
        clearTimeout(timeoutId);
        app2.workspace.offref(eventRef);
      };
    }, [app2.workspace]);
    const { getRootProps, getInputProps, isDragActive } = useDropzone({
      accept: {
        "image/*": [".png", ".gif", ".jpeg", ".jpg", ".webp"]
      },
      onDrop: (acceptedFiles) => {
        onAddImage(acceptedFiles);
      },
      noClick: true,
      // Prevents clicking on textarea from opening file dialog
      noDragEventsBubbling: true
    });
    const excludeNotePaths = (0, import_react14.useMemo)(
      () => [
        ...contextNotes.map((note) => note.path),
        ...includeActiveNote && currentActiveNote ? [currentActiveNote.path] : []
      ].filter((note) => note != null),
      [contextNotes, includeActiveNote, currentActiveNote]
    );
    return /* @__PURE__ */ import_react14.default.createElement(
      "div",
      {
        className: "flex flex-col gap-0.5 w-full border border-border border-solid rounded-md pt-2 pb-1 px-1",
        ref: containerRef
      },
      /* @__PURE__ */ import_react14.default.createElement(
        ContextControl_default,
        {
          app: app2,
          excludeNotePaths,
          contextNotes,
          setContextNotes,
          includeActiveNote,
          setIncludeActiveNote,
          activeNote: currentActiveNote,
          contextUrls,
          onRemoveUrl: (url) => setContextUrls((prev) => prev.filter((u3) => u3 !== url))
        }
      ),
      selectedImages.length > 0 && /* @__PURE__ */ import_react14.default.createElement("div", { className: "selected-images" }, selectedImages.map((file, index2) => /* @__PURE__ */ import_react14.default.createElement("div", { key: index2, className: "image-preview-container" }, /* @__PURE__ */ import_react14.default.createElement(
        "img",
        {
          src: URL.createObjectURL(file),
          alt: file.name,
          className: "selected-image-preview"
        }
      ), /* @__PURE__ */ import_react14.default.createElement(
        "button",
        {
          className: "remove-image-button",
          onClick: () => setSelectedImages((prev) => prev.filter((_2, i3) => i3 !== index2)),
          title: "Remove image"
        },
        /* @__PURE__ */ import_react14.default.createElement(X, { className: "size-4" })
      )))),
      /* @__PURE__ */ import_react14.default.createElement("div", { className: "relative", ...isCopilotPlus ? getRootProps() : {} }, /* @__PURE__ */ import_react14.default.createElement(
        "textarea",
        {
          ref: textAreaRef,
          className: "w-full bg-transparent focus-visible:ring-0 border-none min-h-10 max-h-40 overflow-y-auto resize-none px-2 rounded-md text-sm text-normal",
          placeholder: "Ask anything. [[ for notes. / for custom prompts. " + (isCopilotPlus ? "@ for tools." : ""),
          value: inputMessage,
          onChange: handleInputChange,
          onKeyDown: handleKeyDown,
          onPaste: handlePaste
        }
      ), isCopilotPlus && /* @__PURE__ */ import_react14.default.createElement(import_react14.default.Fragment, null, /* @__PURE__ */ import_react14.default.createElement("input", { ...getInputProps() }), isDragActive && /* @__PURE__ */ import_react14.default.createElement("div", { className: "absolute inset-0 bg-primary border border-dashed border-primary rounded-md flex items-center justify-center" }, /* @__PURE__ */ import_react14.default.createElement("span", { className: "text-primary" }, "Drop images here...")))),
      /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex gap-1 justify-between px-1" }, /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react14.default.createElement(DropdownMenu2, { open: isModelDropdownOpen, onOpenChange: setIsModelDropdownOpen }, /* @__PURE__ */ import_react14.default.createElement(DropdownMenuTrigger2, { asChild: true }, /* @__PURE__ */ import_react14.default.createElement(Button, { variant: "ghost2", size: "fit" }, settings.activeModels.find(
        (model) => getModelKeyFromModel(model) === currentModelKey
      )?.name || "Select Model", /* @__PURE__ */ import_react14.default.createElement(ChevronDown, { className: "size-5 mt-0.5" }))), /* @__PURE__ */ import_react14.default.createElement(DropdownMenuContent2, { align: "start" }, settings.activeModels.filter((model) => model.enabled).map((model) => /* @__PURE__ */ import_react14.default.createElement(
        DropdownMenuItem2,
        {
          key: getModelKeyFromModel(model),
          onSelect: () => setCurrentModelKey(getModelKeyFromModel(model))
        },
        model.name
      )))), isCopilotPlus && /* @__PURE__ */ import_react14.default.createElement(
        Button,
        {
          variant: "ghost2",
          size: "fit",
          onClick: () => {
            new AddImageModal(app2, onAddImage).open();
          }
        },
        /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ import_react14.default.createElement("span", null, "image"), /* @__PURE__ */ import_react14.default.createElement(Image, { className: "!size-3" }))
      )), /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center gap-1" }, isGenerating && /* @__PURE__ */ import_react14.default.createElement(
        Button,
        {
          variant: "ghost2",
          size: "fit",
          className: "text-muted",
          onClick: () => onStopGenerating()
        },
        /* @__PURE__ */ import_react14.default.createElement(CircleStop, { className: "size-4" })
      ), /* @__PURE__ */ import_react14.default.createElement(
        Button,
        {
          variant: "ghost2",
          size: "fit",
          className: "text-muted",
          onClick: () => onSendMessage(false)
        },
        /* @__PURE__ */ import_react14.default.createElement(CornerDownLeft, { className: "!size-3" }),
        /* @__PURE__ */ import_react14.default.createElement("span", null, "chat")
      ), currentChain === "copilot_plus" && /* @__PURE__ */ import_react14.default.createElement(
        Button,
        {
          variant: "ghost2",
          size: "fit",
          className: "text-muted",
          onClick: () => onSendMessage(true)
        },
        /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center gap-1" }, import_obsidian30.Platform.isMacOS ? /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center" }, /* @__PURE__ */ import_react14.default.createElement(Command, { className: "!size-3" }), /* @__PURE__ */ import_react14.default.createElement(ArrowBigUp, { className: "!size-3" }), /* @__PURE__ */ import_react14.default.createElement(CornerDownLeft, { className: "!size-3" })) : /* @__PURE__ */ import_react14.default.createElement("div", { className: "flex items-center" }, /* @__PURE__ */ import_react14.default.createElement("span", null, "Ctrl"), /* @__PURE__ */ import_react14.default.createElement(ArrowBigUp, { className: "size-4" }), /* @__PURE__ */ import_react14.default.createElement(CornerDownLeft, { className: "!size-3" })), /* @__PURE__ */ import_react14.default.createElement("span", null, "vault"))
      )))
    );
  }
);
ChatInput.displayName = "ChatInput";
var ChatInput_default = ChatInput;

// src/components/chat-components/ChatButtons.tsx
var import_obsidian31 = require("obsidian");
var import_react15 = __toESM(require_react());
var ChatButtons = ({
  message,
  onCopy,
  isCopied,
  onInsertIntoEditor,
  onRegenerate,
  onEdit,
  onDelete,
  onShowSources,
  hasSources
}) => {
  return /* @__PURE__ */ import_react15.default.createElement(
    "div",
    {
      className: cn("flex", {
        "group-hover:opacity-100 opacity-0": !import_obsidian31.Platform.isMobile
      })
    },
    /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { variant: "ghost2", size: "fit", onClick: onCopy, title: "Copy" }, isCopied ? /* @__PURE__ */ import_react15.default.createElement(Check, { className: "size-4" }) : /* @__PURE__ */ import_react15.default.createElement(Copy, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Copy")),
    message.sender === USER_SENDER ? /* @__PURE__ */ import_react15.default.createElement(import_react15.default.Fragment, null, /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { onClick: onEdit, variant: "ghost2", size: "fit", title: "Edit" }, /* @__PURE__ */ import_react15.default.createElement(SquarePen, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Edit")), /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { onClick: onDelete, variant: "ghost2", size: "fit", title: "Delete" }, /* @__PURE__ */ import_react15.default.createElement(Trash2, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Delete"))) : /* @__PURE__ */ import_react15.default.createElement(import_react15.default.Fragment, null, hasSources && /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { onClick: onShowSources, variant: "ghost2", size: "fit", title: "Show Sources" }, /* @__PURE__ */ import_react15.default.createElement(LibraryBig, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Show Sources")), /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(
      Button,
      {
        onClick: onInsertIntoEditor,
        variant: "ghost2",
        size: "fit",
        title: "Insert to note at cursor"
      },
      /* @__PURE__ */ import_react15.default.createElement(TextCursorInput, { className: "size-4" })
    )), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Insert to note at cursor")), /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { onClick: onRegenerate, variant: "ghost2", size: "fit", title: "Regenerate" }, /* @__PURE__ */ import_react15.default.createElement(RotateCw, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Regenerate")), /* @__PURE__ */ import_react15.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react15.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react15.default.createElement(Button, { onClick: onDelete, variant: "ghost2", size: "fit", title: "Delete" }, /* @__PURE__ */ import_react15.default.createElement(Trash2, { className: "size-4" }))), /* @__PURE__ */ import_react15.default.createElement(TooltipContent2, null, "Delete")))
  );
};

// src/components/modals/SourcesModal.tsx
var import_obsidian32 = require("obsidian");
var SourcesModal = class extends import_obsidian32.Modal {
  constructor(app2, sources) {
    super(app2);
    this.sources = sources;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h2", { text: "Sources" });
    const highScoreSources = this.sources.filter(
      (source) => source.score >= CONTEXT_SCORE_THRESHOLD
    );
    const lowScoreSources = this.sources.filter((source) => source.score < CONTEXT_SCORE_THRESHOLD);
    if (highScoreSources.length > 0) {
      contentEl.createEl("h3", { text: "High Relevance Sources" });
      this.createSourceList(contentEl, highScoreSources);
    }
    if (lowScoreSources.length > 0) {
      contentEl.createEl("h3", { text: "Lower Relevance Sources" });
      this.createSourceList(contentEl, lowScoreSources);
    }
  }
  createSourceList(container, sources) {
    const list = container.createEl("ul");
    list.style.listStyleType = "none";
    list.style.padding = "0";
    sources.forEach((source) => {
      const item = list.createEl("li");
      item.style.marginBottom = "1em";
      const link = item.createEl("a", {
        href: `obsidian://open?vault=${encodeURIComponent(this.app.vault.getName())}&file=${encodeURIComponent(source.title)}`,
        text: source.title
      });
      link.addEventListener("click", (e3) => {
        e3.preventDefault();
        this.app.workspace.openLinkText(source.title, "");
      });
      if (source.score && source.score <= 1) {
        item.appendChild(document.createTextNode(` - Relevance score: ${source.score.toFixed(3)}`));
      }
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/components/chat-components/ChatSingleMessage.tsx
var import_obsidian33 = require("obsidian");
var import_react16 = __toESM(require_react());
function MessageContext({ context }) {
  if (!context || context.notes.length === 0 && context.urls.length === 0) {
    return null;
  }
  return /* @__PURE__ */ import_react16.default.createElement("div", { className: "flex gap-2 flex-wrap" }, context.notes.map((note) => /* @__PURE__ */ import_react16.default.createElement(Tooltip2, { key: note.path }, /* @__PURE__ */ import_react16.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react16.default.createElement(Badge, { variant: "secondary" }, /* @__PURE__ */ import_react16.default.createElement("span", { className: "max-w-40 truncate" }, note.basename))), /* @__PURE__ */ import_react16.default.createElement(TooltipContent2, null, note.path))), context.urls.map((url) => /* @__PURE__ */ import_react16.default.createElement(Tooltip2, { key: url }, /* @__PURE__ */ import_react16.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react16.default.createElement(Badge, { variant: "secondary" }, /* @__PURE__ */ import_react16.default.createElement("span", { className: "max-w-40 truncate" }, url))), /* @__PURE__ */ import_react16.default.createElement(TooltipContent2, null, url))));
}
var ChatSingleMessage = ({
  message,
  app: app2,
  isStreaming,
  onRegenerate,
  onEdit,
  onDelete
}) => {
  const [isCopied, setIsCopied] = (0, import_react16.useState)(false);
  const [isEditing, setIsEditing] = (0, import_react16.useState)(false);
  const [editedMessage, setEditedMessage] = (0, import_react16.useState)(message.message);
  const contentRef = (0, import_react16.useRef)(null);
  const componentRef = (0, import_react16.useRef)(null);
  const textareaRef = (0, import_react16.useRef)(null);
  const copyToClipboard = () => {
    if (!navigator.clipboard || !navigator.clipboard.writeText) {
      return;
    }
    navigator.clipboard.writeText(message.message).then(() => {
      setIsCopied(true);
      setTimeout(() => {
        setIsCopied(false);
      }, 2e3);
    });
  };
  const preprocess = (0, import_react16.useCallback)(
    (content) => {
      const latexProcessed = content.replace(/\\\[\s*/g, "$$").replace(/\s*\\\]/g, "$$").replace(/\\\(\s*/g, "$").replace(/\s*\\\)/g, "$");
      const activeFile = app2.workspace.getActiveFile();
      const sourcePath = activeFile ? activeFile.path : "";
      const noteImageProcessed = latexProcessed.replace(
        /!\[\[(.*?)\]\]/g,
        (match2, imageName) => {
          const imageFile = app2.metadataCache.getFirstLinkpathDest(imageName, sourcePath);
          if (imageFile) {
            const imageUrl = app2.vault.getResourcePath(imageFile);
            return `![](${imageUrl})`;
          }
          return match2;
        }
      );
      return noteImageProcessed;
    },
    [app2]
  );
  (0, import_react16.useEffect)(() => {
    if (contentRef.current && message.sender !== USER_SENDER) {
      contentRef.current.innerHTML = "";
      if (!componentRef.current) {
        componentRef.current = new import_obsidian33.Component();
      }
      const processedMessage = preprocess(message.message);
      import_obsidian33.MarkdownRenderer.renderMarkdown(
        processedMessage,
        contentRef.current,
        "",
        // Empty string for sourcePath as we don't have a specific source file
        componentRef.current
      );
    }
    return () => {
      if (componentRef.current) {
        componentRef.current.unload();
        componentRef.current = null;
      }
    };
  }, [message, app2, componentRef, isStreaming, preprocess]);
  (0, import_react16.useEffect)(() => {
    if (isEditing && textareaRef.current) {
      adjustTextareaHeight(textareaRef.current);
    }
  }, [isEditing]);
  (0, import_react16.useEffect)(() => {
    setEditedMessage(message.message);
  }, [message.message]);
  const adjustTextareaHeight = (element) => {
    element.style.height = "auto";
    element.style.height = `${element.scrollHeight}px`;
  };
  const handleTextareaChange = (e3) => {
    setEditedMessage(e3.target.value);
    adjustTextareaHeight(e3.target);
  };
  const handleKeyDown = (event) => {
    if (event.nativeEvent.isComposing)
      return;
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      handleSaveEdit();
    }
  };
  const handleEdit = () => {
    setIsEditing(true);
  };
  const handleSaveEdit = () => {
    setIsEditing(false);
    if (onEdit) {
      onEdit(editedMessage);
    }
  };
  const handleShowSources = () => {
    if (message.sources && message.sources.length > 0) {
      new SourcesModal(app2, message.sources).open();
    }
  };
  const renderMessageContent = () => {
    if (message.content) {
      return /* @__PURE__ */ import_react16.default.createElement("div", { className: "message-content-items" }, message.content.map((item, index2) => {
        if (item.type === "text") {
          return /* @__PURE__ */ import_react16.default.createElement("div", { key: index2, className: "message-text-content" }, message.sender === USER_SENDER && isEditing ? /* @__PURE__ */ import_react16.default.createElement(
            "textarea",
            {
              ref: textareaRef,
              value: editedMessage,
              onChange: handleTextareaChange,
              onKeyDown: handleKeyDown,
              onBlur: handleSaveEdit,
              autoFocus: true,
              className: "edit-textarea"
            }
          ) : message.sender === USER_SENDER ? /* @__PURE__ */ import_react16.default.createElement("div", { className: "whitespace-pre-wrap break-words font-normal text-[calc(var(--font-text-size)_-_2px)]" }, message.message) : /* @__PURE__ */ import_react16.default.createElement("div", { ref: contentRef }));
        } else if (item.type === "image_url") {
          return /* @__PURE__ */ import_react16.default.createElement("div", { key: index2, className: "message-image-content" }, /* @__PURE__ */ import_react16.default.createElement(
            "img",
            {
              src: item.image_url.url,
              alt: "User uploaded image",
              className: "chat-message-image"
            }
          ));
        }
        return null;
      }));
    }
    return message.sender === USER_SENDER && isEditing ? /* @__PURE__ */ import_react16.default.createElement(
      "textarea",
      {
        ref: textareaRef,
        value: editedMessage,
        onChange: handleTextareaChange,
        onKeyDown: handleKeyDown,
        onBlur: handleSaveEdit,
        autoFocus: true,
        className: "edit-textarea"
      }
    ) : message.sender === USER_SENDER ? /* @__PURE__ */ import_react16.default.createElement("div", { className: "whitespace-pre-wrap break-words font-normal text-[calc(var(--font-text-size)_-_2px)]" }, message.message) : /* @__PURE__ */ import_react16.default.createElement("div", { ref: contentRef });
  };
  return /* @__PURE__ */ import_react16.default.createElement("div", { className: "flex flex-col w-full my-1" }, /* @__PURE__ */ import_react16.default.createElement(
    "div",
    {
      className: cn(
        "flex rounded-md p-2 mx-2 gap-2 group",
        message.sender === USER_SENDER && "border border-border border-solid"
      )
    },
    /* @__PURE__ */ import_react16.default.createElement("div", { className: "w-6 shrink-0" }, message.sender === USER_SENDER ? /* @__PURE__ */ import_react16.default.createElement(User, null) : /* @__PURE__ */ import_react16.default.createElement(Bot, null)),
    /* @__PURE__ */ import_react16.default.createElement("div", { className: "flex flex-col flex-grow max-w-full gap-2" }, !isEditing && /* @__PURE__ */ import_react16.default.createElement(MessageContext, { context: message.context }), /* @__PURE__ */ import_react16.default.createElement("div", { className: "message-content" }, renderMessageContent()), !isStreaming && /* @__PURE__ */ import_react16.default.createElement("div", { className: "flex justify-between items-center" }, /* @__PURE__ */ import_react16.default.createElement("div", { className: "text-faint text-xs" }, message.timestamp?.display), /* @__PURE__ */ import_react16.default.createElement(
      ChatButtons,
      {
        message,
        onCopy: copyToClipboard,
        isCopied,
        onInsertIntoEditor: () => insertIntoEditor(message.message),
        onRegenerate,
        onEdit: handleEdit,
        onDelete,
        onShowSources: handleShowSources,
        hasSources: message.sources && message.sources.length > 0 ? true : false
      }
    )))
  ));
};
var ChatSingleMessage_default = ChatSingleMessage;

// node_modules/@radix-ui/react-collapsible/dist/index.mjs
var React71 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers6(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React68 = __toESM(require_react(), 1);
function setRef8(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs8(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef8(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef8(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs6(...refs) {
  return React68.useCallback(composeRefs8(...refs), refs);
}

// node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React70 = __toESM(require_react(), 1);
var ReactDOM9 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/react-slot/dist/index.mjs
var React69 = __toESM(require_react(), 1);
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var Slot7 = React69.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React69.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable7);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React69.Children.count(newElement) > 1)
          return React69.Children.only(null);
        return React69.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(SlotClone7, { ...slotProps, ref: forwardedRef, children: React69.isValidElement(newElement) ? React69.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(SlotClone7, { ...slotProps, ref: forwardedRef, children });
});
Slot7.displayName = "Slot";
var SlotClone7 = React69.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React69.isValidElement(children)) {
    const childrenRef = getElementRef8(children);
    return React69.cloneElement(children, {
      ...mergeProps7(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs8(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React69.Children.count(children) > 1 ? React69.Children.only(null) : null;
});
SlotClone7.displayName = "SlotClone";
var Slottable7 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_jsx_runtime30.Fragment, { children });
};
function isSlottable7(child) {
  return React69.isValidElement(child) && child.type === Slottable7;
}
function mergeProps7(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef8(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-collapsible/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var NODES6 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive6 = NODES6.reduce((primitive, node) => {
  const Node3 = React70.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot7 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});

// node_modules/@radix-ui/react-collapsible/dist/index.mjs
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
"use client";
var COLLAPSIBLE_NAME = "Collapsible";
var [createCollapsibleContext, createCollapsibleScope] = createContextScope(COLLAPSIBLE_NAME);
var [CollapsibleProvider, useCollapsibleContext] = createCollapsibleContext(COLLAPSIBLE_NAME);
var Collapsible = React71.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeCollapsible,
      open: openProp,
      defaultOpen,
      disabled,
      onOpenChange,
      ...collapsibleProps
    } = props;
    const [open = false, setOpen] = useControllableState({
      prop: openProp,
      defaultProp: defaultOpen,
      onChange: onOpenChange
    });
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      CollapsibleProvider,
      {
        scope: __scopeCollapsible,
        disabled,
        contentId: useId(),
        open,
        onOpenToggle: React71.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
        children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
          Primitive6.div,
          {
            "data-state": getState(open),
            "data-disabled": disabled ? "" : void 0,
            ...collapsibleProps,
            ref: forwardedRef
          }
        )
      }
    );
  }
);
Collapsible.displayName = COLLAPSIBLE_NAME;
var TRIGGER_NAME3 = "CollapsibleTrigger";
var CollapsibleTrigger = React71.forwardRef(
  (props, forwardedRef) => {
    const { __scopeCollapsible, ...triggerProps } = props;
    const context = useCollapsibleContext(TRIGGER_NAME3, __scopeCollapsible);
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      Primitive6.button,
      {
        type: "button",
        "aria-controls": context.contentId,
        "aria-expanded": context.open || false,
        "data-state": getState(context.open),
        "data-disabled": context.disabled ? "" : void 0,
        disabled: context.disabled,
        ...triggerProps,
        ref: forwardedRef,
        onClick: composeEventHandlers6(props.onClick, context.onOpenToggle)
      }
    );
  }
);
CollapsibleTrigger.displayName = TRIGGER_NAME3;
var CONTENT_NAME6 = "CollapsibleContent";
var CollapsibleContent = React71.forwardRef(
  (props, forwardedRef) => {
    const { forceMount, ...contentProps } = props;
    const context = useCollapsibleContext(CONTENT_NAME6, props.__scopeCollapsible);
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Presence, { present: forceMount || context.open, children: ({ present }) => /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(CollapsibleContentImpl, { ...contentProps, ref: forwardedRef, present }) });
  }
);
CollapsibleContent.displayName = CONTENT_NAME6;
var CollapsibleContentImpl = React71.forwardRef((props, forwardedRef) => {
  const { __scopeCollapsible, present, children, ...contentProps } = props;
  const context = useCollapsibleContext(CONTENT_NAME6, __scopeCollapsible);
  const [isPresent, setIsPresent] = React71.useState(present);
  const ref = React71.useRef(null);
  const composedRefs = useComposedRefs6(forwardedRef, ref);
  const heightRef = React71.useRef(0);
  const height = heightRef.current;
  const widthRef = React71.useRef(0);
  const width = widthRef.current;
  const isOpen = context.open || isPresent;
  const isMountAnimationPreventedRef = React71.useRef(isOpen);
  const originalStylesRef = React71.useRef(void 0);
  React71.useEffect(() => {
    const rAF = requestAnimationFrame(() => isMountAnimationPreventedRef.current = false);
    return () => cancelAnimationFrame(rAF);
  }, []);
  useLayoutEffect2(() => {
    const node = ref.current;
    if (node) {
      originalStylesRef.current = originalStylesRef.current || {
        transitionDuration: node.style.transitionDuration,
        animationName: node.style.animationName
      };
      node.style.transitionDuration = "0s";
      node.style.animationName = "none";
      const rect = node.getBoundingClientRect();
      heightRef.current = rect.height;
      widthRef.current = rect.width;
      if (!isMountAnimationPreventedRef.current) {
        node.style.transitionDuration = originalStylesRef.current.transitionDuration;
        node.style.animationName = originalStylesRef.current.animationName;
      }
      setIsPresent(present);
    }
  }, [context.open, present]);
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
    Primitive6.div,
    {
      "data-state": getState(context.open),
      "data-disabled": context.disabled ? "" : void 0,
      id: context.contentId,
      hidden: !isOpen,
      ...contentProps,
      ref: composedRefs,
      style: {
        [`--radix-collapsible-content-height`]: height ? `${height}px` : void 0,
        [`--radix-collapsible-content-width`]: width ? `${width}px` : void 0,
        ...props.style
      },
      children: isOpen && children
    }
  );
});
function getState(open) {
  return open ? "open" : "closed";
}
var Root6 = Collapsible;

// src/components/ui/collapsible.tsx
var Collapsible2 = Root6;
var CollapsibleTrigger2 = CollapsibleTrigger;
var CollapsibleContent2 = CollapsibleContent;

// src/components/ui/popover.tsx
var React84 = __toESM(require_react());

// node_modules/@radix-ui/react-popover/dist/index.mjs
var React83 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers7(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React72 = __toESM(require_react(), 1);
function setRef9(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs9(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef9(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef9(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs7(...refs) {
  return React72.useCallback(composeRefs9(...refs), refs);
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var React75 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React74 = __toESM(require_react(), 1);
var ReactDOM10 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-slot/dist/index.mjs
var React73 = __toESM(require_react(), 1);
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var Slot8 = React73.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React73.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable8);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React73.Children.count(newElement) > 1)
          return React73.Children.only(null);
        return React73.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(SlotClone8, { ...slotProps, ref: forwardedRef, children: React73.isValidElement(newElement) ? React73.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(SlotClone8, { ...slotProps, ref: forwardedRef, children });
});
Slot8.displayName = "Slot";
var SlotClone8 = React73.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React73.isValidElement(children)) {
    const childrenRef = getElementRef9(children);
    return React73.cloneElement(children, {
      ...mergeProps8(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs9(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React73.Children.count(children) > 1 ? React73.Children.only(null) : null;
});
SlotClone8.displayName = "SlotClone";
var Slottable8 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_jsx_runtime33.Fragment, { children });
};
function isSlottable8(child) {
  return React73.isValidElement(child) && child.type === Slottable8;
}
function mergeProps8(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef9(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var NODES7 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive7 = NODES7.reduce((primitive, node) => {
  const Node3 = React74.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot8 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});
function dispatchDiscreteCustomEvent3(target, event) {
  if (target)
    ReactDOM10.flushSync(() => target.dispatchEvent(event));
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
"use client";
var DISMISSABLE_LAYER_NAME3 = "DismissableLayer";
var CONTEXT_UPDATE3 = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE3 = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE3 = "dismissableLayer.focusOutside";
var originalBodyPointerEvents3;
var DismissableLayerContext3 = React75.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer3 = React75.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = React75.useContext(DismissableLayerContext3);
    const [node, setNode] = React75.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = React75.useState({});
    const composedRefs = useComposedRefs7(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside3((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside3((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch)
        return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    React75.useEffect(() => {
      if (!node)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents3 = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate3();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents3;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    React75.useEffect(() => {
      return () => {
        if (!node)
          return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate3();
      };
    }, [node, context]);
    React75.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE3, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE3, handleUpdate);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
      Primitive7.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers7(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers7(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers7(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer3.displayName = DISMISSABLE_LAYER_NAME3;
var BRANCH_NAME3 = "DismissableLayerBranch";
var DismissableLayerBranch3 = React75.forwardRef((props, forwardedRef) => {
  const context = React75.useContext(DismissableLayerContext3);
  const ref = React75.useRef(null);
  const composedRefs = useComposedRefs7(forwardedRef, ref);
  React75.useEffect(() => {
    const node = ref.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Primitive7.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch3.displayName = BRANCH_NAME3;
function usePointerDownOutside3(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
  const isPointerInsideReactTreeRef = React75.useRef(false);
  const handleClickRef = React75.useRef(() => {
  });
  React75.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent3(
            POINTER_DOWN_OUTSIDE3,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside3(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef(onFocusOutside);
  const isFocusInsideReactTreeRef = React75.useRef(false);
  React75.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent3(FOCUS_OUTSIDE3, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate3() {
  const event = new CustomEvent(CONTEXT_UPDATE3);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent3(name, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });
  if (handler)
    target.addEventListener(name, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent3(target, event);
  } else {
    target.dispatchEvent(event);
  }
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-focus-scope/dist/index.mjs
var React76 = __toESM(require_react(), 1);
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
"use client";
var AUTOFOCUS_ON_MOUNT2 = "focusScope.autoFocusOnMount";
var AUTOFOCUS_ON_UNMOUNT2 = "focusScope.autoFocusOnUnmount";
var EVENT_OPTIONS3 = { bubbles: false, cancelable: true };
var FOCUS_SCOPE_NAME2 = "FocusScope";
var FocusScope2 = React76.forwardRef((props, forwardedRef) => {
  const {
    loop = false,
    trapped = false,
    onMountAutoFocus: onMountAutoFocusProp,
    onUnmountAutoFocus: onUnmountAutoFocusProp,
    ...scopeProps
  } = props;
  const [container, setContainer] = React76.useState(null);
  const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
  const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
  const lastFocusedElementRef = React76.useRef(null);
  const composedRefs = useComposedRefs7(forwardedRef, (node) => setContainer(node));
  const focusScope = React76.useRef({
    paused: false,
    pause() {
      this.paused = true;
    },
    resume() {
      this.paused = false;
    }
  }).current;
  React76.useEffect(() => {
    if (trapped) {
      let handleFocusIn2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const target = event.target;
        if (container.contains(target)) {
          lastFocusedElementRef.current = target;
        } else {
          focus2(lastFocusedElementRef.current, { select: true });
        }
      }, handleFocusOut2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget === null)
          return;
        if (!container.contains(relatedTarget)) {
          focus2(lastFocusedElementRef.current, { select: true });
        }
      }, handleMutations2 = function(mutations) {
        const focusedElement = document.activeElement;
        if (focusedElement !== document.body)
          return;
        for (const mutation of mutations) {
          if (mutation.removedNodes.length > 0)
            focus2(container);
        }
      };
      var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
      document.addEventListener("focusin", handleFocusIn2);
      document.addEventListener("focusout", handleFocusOut2);
      const mutationObserver = new MutationObserver(handleMutations2);
      if (container)
        mutationObserver.observe(container, { childList: true, subtree: true });
      return () => {
        document.removeEventListener("focusin", handleFocusIn2);
        document.removeEventListener("focusout", handleFocusOut2);
        mutationObserver.disconnect();
      };
    }
  }, [trapped, container, focusScope.paused]);
  React76.useEffect(() => {
    if (container) {
      focusScopesStack2.add(focusScope);
      const previouslyFocusedElement = document.activeElement;
      const hasFocusedCandidate = container.contains(previouslyFocusedElement);
      if (!hasFocusedCandidate) {
        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT2, EVENT_OPTIONS3);
        container.addEventListener(AUTOFOCUS_ON_MOUNT2, onMountAutoFocus);
        container.dispatchEvent(mountEvent);
        if (!mountEvent.defaultPrevented) {
          focusFirst4(removeLinks2(getTabbableCandidates2(container)), { select: true });
          if (document.activeElement === previouslyFocusedElement) {
            focus2(container);
          }
        }
      }
      return () => {
        container.removeEventListener(AUTOFOCUS_ON_MOUNT2, onMountAutoFocus);
        setTimeout(() => {
          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT2, EVENT_OPTIONS3);
          container.addEventListener(AUTOFOCUS_ON_UNMOUNT2, onUnmountAutoFocus);
          container.dispatchEvent(unmountEvent);
          if (!unmountEvent.defaultPrevented) {
            focus2(previouslyFocusedElement ?? document.body, { select: true });
          }
          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT2, onUnmountAutoFocus);
          focusScopesStack2.remove(focusScope);
        }, 0);
      };
    }
  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
  const handleKeyDown = React76.useCallback(
    (event) => {
      if (!loop && !trapped)
        return;
      if (focusScope.paused)
        return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container2 = event.currentTarget;
        const [first, last] = getTabbableEdges2(container2);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container2)
            event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop)
              focus2(first, { select: true });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop)
              focus2(last, { select: true });
          }
        }
      }
    },
    [loop, trapped, focusScope.paused]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Primitive7.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
});
FocusScope2.displayName = FOCUS_SCOPE_NAME2;
function focusFirst4(candidates, { select = false } = {}) {
  const previouslyFocusedElement = document.activeElement;
  for (const candidate of candidates) {
    focus2(candidate, { select });
    if (document.activeElement !== previouslyFocusedElement)
      return;
  }
}
function getTabbableEdges2(container) {
  const candidates = getTabbableCandidates2(container);
  const first = findVisible2(candidates, container);
  const last = findVisible2(candidates.reverse(), container);
  return [first, last];
}
function getTabbableCandidates2(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput)
        return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode())
    nodes.push(walker.currentNode);
  return nodes;
}
function findVisible2(elements, container) {
  for (const element of elements) {
    if (!isHidden2(element, { upTo: container }))
      return element;
  }
}
function isHidden2(node, { upTo }) {
  if (getComputedStyle(node).visibility === "hidden")
    return true;
  while (node) {
    if (upTo !== void 0 && node === upTo)
      return false;
    if (getComputedStyle(node).display === "none")
      return true;
    node = node.parentElement;
  }
  return false;
}
function isSelectableInput2(element) {
  return element instanceof HTMLInputElement && "select" in element;
}
function focus2(element, { select = false } = {}) {
  if (element && element.focus) {
    const previouslyFocusedElement = document.activeElement;
    element.focus({ preventScroll: true });
    if (element !== previouslyFocusedElement && isSelectableInput2(element) && select)
      element.select();
  }
}
var focusScopesStack2 = createFocusScopesStack2();
function createFocusScopesStack2() {
  let stack = [];
  return {
    add(focusScope) {
      const activeFocusScope = stack[0];
      if (focusScope !== activeFocusScope) {
        activeFocusScope?.pause();
      }
      stack = arrayRemove2(stack, focusScope);
      stack.unshift(focusScope);
    },
    remove(focusScope) {
      stack = arrayRemove2(stack, focusScope);
      stack[0]?.resume();
    }
  };
}
function arrayRemove2(array, item) {
  const updatedArray = [...array];
  const index2 = updatedArray.indexOf(item);
  if (index2 !== -1) {
    updatedArray.splice(index2, 1);
  }
  return updatedArray;
}
function removeLinks2(items) {
  return items.filter((item) => item.tagName !== "A");
}

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-popper/dist/index.mjs
var React78 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-arrow/dist/index.mjs
var React77 = __toESM(require_react(), 1);
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var NAME4 = "Arrow";
var Arrow5 = React77.forwardRef((props, forwardedRef) => {
  const { children, width = 10, height = 5, ...arrowProps } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
    Primitive7.svg,
    {
      ...arrowProps,
      ref: forwardedRef,
      width,
      height,
      viewBox: "0 0 30 10",
      preserveAspectRatio: "none",
      children: props.asChild ? children : /* @__PURE__ */ (0, import_jsx_runtime37.jsx)("polygon", { points: "0,0 30,0 15,10" })
    }
  );
});
Arrow5.displayName = NAME4;
var Root7 = Arrow5;

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-popper/dist/index.mjs
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
"use client";
var POPPER_NAME3 = "Popper";
var [createPopperContext3, createPopperScope3] = createContextScope(POPPER_NAME3);
var [PopperProvider3, usePopperContext3] = createPopperContext3(POPPER_NAME3);
var Popper3 = (props) => {
  const { __scopePopper, children } = props;
  const [anchor, setAnchor] = React78.useState(null);
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(PopperProvider3, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });
};
Popper3.displayName = POPPER_NAME3;
var ANCHOR_NAME4 = "PopperAnchor";
var PopperAnchor3 = React78.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopper, virtualRef, ...anchorProps } = props;
    const context = usePopperContext3(ANCHOR_NAME4, __scopePopper);
    const ref = React78.useRef(null);
    const composedRefs = useComposedRefs7(forwardedRef, ref);
    React78.useEffect(() => {
      context.onAnchorChange(virtualRef?.current || ref.current);
    });
    return virtualRef ? null : /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Primitive7.div, { ...anchorProps, ref: composedRefs });
  }
);
PopperAnchor3.displayName = ANCHOR_NAME4;
var CONTENT_NAME7 = "PopperContent";
var [PopperContentProvider3, useContentContext3] = createPopperContext3(CONTENT_NAME7);
var PopperContent3 = React78.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopper,
      side = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      arrowPadding = 0,
      avoidCollisions = true,
      collisionBoundary = [],
      collisionPadding: collisionPaddingProp = 0,
      sticky = "partial",
      hideWhenDetached = false,
      updatePositionStrategy = "optimized",
      onPlaced,
      ...contentProps
    } = props;
    const context = usePopperContext3(CONTENT_NAME7, __scopePopper);
    const [content, setContent] = React78.useState(null);
    const composedRefs = useComposedRefs7(forwardedRef, (node) => setContent(node));
    const [arrow4, setArrow] = React78.useState(null);
    const arrowSize = useSize(arrow4);
    const arrowWidth = arrowSize?.width ?? 0;
    const arrowHeight = arrowSize?.height ?? 0;
    const desiredPlacement = side + (align !== "center" ? "-" + align : "");
    const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };
    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];
    const hasExplicitBoundaries = boundary.length > 0;
    const detectOverflowOptions = {
      padding: collisionPadding,
      boundary: boundary.filter(isNotNull3),
      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
      altBoundary: hasExplicitBoundaries
    };
    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({
      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
      strategy: "fixed",
      placement: desiredPlacement,
      whileElementsMounted: (...args) => {
        const cleanup = autoUpdate(...args, {
          animationFrame: updatePositionStrategy === "always"
        });
        return cleanup;
      },
      elements: {
        reference: context.anchor
      },
      middleware: [
        offset4({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),
        avoidCollisions && shift3({
          mainAxis: true,
          crossAxis: false,
          limiter: sticky === "partial" ? limitShift3() : void 0,
          ...detectOverflowOptions
        }),
        avoidCollisions && flip3({ ...detectOverflowOptions }),
        size3({
          ...detectOverflowOptions,
          apply: ({ elements, rects, availableWidth, availableHeight }) => {
            const { width: anchorWidth, height: anchorHeight } = rects.reference;
            const contentStyle = elements.floating.style;
            contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`);
            contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`);
            contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`);
            contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`);
          }
        }),
        arrow4 && arrow3({ element: arrow4, padding: arrowPadding }),
        transformOrigin3({ arrowWidth, arrowHeight }),
        hideWhenDetached && hide3({ strategy: "referenceHidden", ...detectOverflowOptions })
      ]
    });
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement3(placement);
    const handlePlaced = useCallbackRef(onPlaced);
    useLayoutEffect2(() => {
      if (isPositioned) {
        handlePlaced?.();
      }
    }, [isPositioned, handlePlaced]);
    const arrowX = middlewareData.arrow?.x;
    const arrowY = middlewareData.arrow?.y;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const [contentZIndex, setContentZIndex] = React78.useState();
    useLayoutEffect2(() => {
      if (content)
        setContentZIndex(window.getComputedStyle(content).zIndex);
    }, [content]);
    return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
      "div",
      {
        ref: refs.setFloating,
        "data-radix-popper-content-wrapper": "",
        style: {
          ...floatingStyles,
          transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)",
          // keep off the page when measuring
          minWidth: "max-content",
          zIndex: contentZIndex,
          ["--radix-popper-transform-origin"]: [
            middlewareData.transformOrigin?.x,
            middlewareData.transformOrigin?.y
          ].join(" "),
          // hide the content if using the hide middleware and should be hidden
          // set visibility to hidden and disable pointer events so the UI behaves
          // as if the PopperContent isn't there at all
          ...middlewareData.hide?.referenceHidden && {
            visibility: "hidden",
            pointerEvents: "none"
          }
        },
        dir: props.dir,
        children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
          PopperContentProvider3,
          {
            scope: __scopePopper,
            placedSide,
            onArrowChange: setArrow,
            arrowX,
            arrowY,
            shouldHideArrow: cannotCenterArrow,
            children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
              Primitive7.div,
              {
                "data-side": placedSide,
                "data-align": placedAlign,
                ...contentProps,
                ref: composedRefs,
                style: {
                  ...contentProps.style,
                  // if the PopperContent hasn't been placed yet (not all measurements done)
                  // we prevent animations so that users's animation don't kick in too early referring wrong sides
                  animation: !isPositioned ? "none" : void 0
                }
              }
            )
          }
        )
      }
    );
  }
);
PopperContent3.displayName = CONTENT_NAME7;
var ARROW_NAME6 = "PopperArrow";
var OPPOSITE_SIDE3 = {
  top: "bottom",
  right: "left",
  bottom: "top",
  left: "right"
};
var PopperArrow4 = React78.forwardRef(function PopperArrow23(props, forwardedRef) {
  const { __scopePopper, ...arrowProps } = props;
  const contentContext = useContentContext3(ARROW_NAME6, __scopePopper);
  const baseSide = OPPOSITE_SIDE3[contentContext.placedSide];
  return (
    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
    // doesn't report size as we'd expect on SVG elements.
    // it reports their bounding box which is effectively the largest path inside the SVG.
    /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
      "span",
      {
        ref: contentContext.onArrowChange,
        style: {
          position: "absolute",
          left: contentContext.arrowX,
          top: contentContext.arrowY,
          [baseSide]: 0,
          transformOrigin: {
            top: "",
            right: "0 0",
            bottom: "center 0",
            left: "100% 0"
          }[contentContext.placedSide],
          transform: {
            top: "translateY(100%)",
            right: "translateY(50%) rotate(90deg) translateX(-50%)",
            bottom: `rotate(180deg)`,
            left: "translateY(50%) rotate(-90deg) translateX(50%)"
          }[contentContext.placedSide],
          visibility: contentContext.shouldHideArrow ? "hidden" : void 0
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
          Root7,
          {
            ...arrowProps,
            ref: forwardedRef,
            style: {
              ...arrowProps.style,
              // ensures the element can be measured correctly (mostly for if SVG)
              display: "block"
            }
          }
        )
      }
    )
  );
});
PopperArrow4.displayName = ARROW_NAME6;
function isNotNull3(value) {
  return value !== null;
}
var transformOrigin3 = (options) => ({
  name: "transformOrigin",
  options,
  fn(data) {
    const { placement, rects, middlewareData } = data;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const isArrowHidden = cannotCenterArrow;
    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement3(placement);
    const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign];
    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;
    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;
    let x2 = "";
    let y2 = "";
    if (placedSide === "bottom") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${-arrowHeight}px`;
    } else if (placedSide === "top") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${rects.floating.height + arrowHeight}px`;
    } else if (placedSide === "right") {
      x2 = `${-arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    } else if (placedSide === "left") {
      x2 = `${rects.floating.width + arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    }
    return { data: { x: x2, y: y2 } };
  }
});
function getSideAndAlignFromPlacement3(placement) {
  const [side, align = "center"] = placement.split("-");
  return [side, align];
}
var Root25 = Popper3;
var Anchor4 = PopperAnchor3;
var Content4 = PopperContent3;
var Arrow6 = PopperArrow4;

// node_modules/@radix-ui/react-popover/node_modules/@radix-ui/react-portal/dist/index.mjs
var React79 = __toESM(require_react(), 1);
var import_react_dom6 = __toESM(require_react_dom(), 1);
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
"use client";
var PORTAL_NAME6 = "Portal";
var Portal5 = React79.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = React79.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? import_react_dom6.default.createPortal(/* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Primitive7.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal5.displayName = PORTAL_NAME6;

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/Combination.js
var React82 = __toESM(require_react());

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/UI.js
var React80 = __toESM(require_react());

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/medium.js
var effectCar2 = createSidecarMedium();

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/UI.js
var nothing2 = function() {
  return;
};
var RemoveScroll2 = React80.forwardRef(function(props, parentRef) {
  var ref = React80.useRef(null);
  var _a5 = React80.useState({
    onScrollCapture: nothing2,
    onWheelCapture: nothing2,
    onTouchMoveCapture: nothing2
  }), callbacks = _a5[0], setCallbacks = _a5[1];
  var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest5(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]);
  var SideCar2 = sideCar;
  var containerRef = useMergeRefs([ref, parentRef]);
  var containerProps = __assign5(__assign5({}, rest), callbacks);
  return React80.createElement(
    React80.Fragment,
    null,
    enabled && React80.createElement(SideCar2, { sideCar: effectCar2, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode }),
    forwardProps ? React80.cloneElement(React80.Children.only(children), __assign5(__assign5({}, containerProps), { ref: containerRef })) : React80.createElement(Container, __assign5({}, containerProps, { className, ref: containerRef }), children)
  );
});
RemoveScroll2.defaultProps = {
  enabled: true,
  removeScrollBar: true,
  inert: false
};
RemoveScroll2.classNames = {
  fullWidth: fullWidthClassName,
  zeroRight: zeroRightClassName
};

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var React81 = __toESM(require_react());

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js
var passiveSupported2 = false;
if (typeof window !== "undefined") {
  try {
    options = Object.defineProperty({}, "passive", {
      get: function() {
        passiveSupported2 = true;
        return true;
      }
    });
    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (err) {
    passiveSupported2 = false;
  }
}
var options;
var nonPassive2 = passiveSupported2 ? { passive: false } : false;

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/handleScroll.js
var alwaysContainsScroll2 = function(node) {
  return node.tagName === "TEXTAREA";
};
var elementCanBeScrolled2 = function(node, overflow) {
  if (!(node instanceof Element)) {
    return false;
  }
  var styles2 = window.getComputedStyle(node);
  return (
    // not-not-scrollable
    styles2[overflow] !== "hidden" && // contains scroll inside self
    !(styles2.overflowY === styles2.overflowX && !alwaysContainsScroll2(node) && styles2[overflow] === "visible")
  );
};
var elementCouldBeVScrolled2 = function(node) {
  return elementCanBeScrolled2(node, "overflowY");
};
var elementCouldBeHScrolled2 = function(node) {
  return elementCanBeScrolled2(node, "overflowX");
};
var locationCouldBeScrolled2 = function(axis, node) {
  var ownerDocument = node.ownerDocument;
  var current = node;
  do {
    if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) {
      current = current.host;
    }
    var isScrollable = elementCouldBeScrolled2(axis, current);
    if (isScrollable) {
      var _a5 = getScrollVariables2(axis, current), scrollHeight = _a5[1], clientHeight = _a5[2];
      if (scrollHeight > clientHeight) {
        return true;
      }
    }
    current = current.parentNode;
  } while (current && current !== ownerDocument.body);
  return false;
};
var getVScrollVariables2 = function(_a5) {
  var scrollTop = _a5.scrollTop, scrollHeight = _a5.scrollHeight, clientHeight = _a5.clientHeight;
  return [
    scrollTop,
    scrollHeight,
    clientHeight
  ];
};
var getHScrollVariables2 = function(_a5) {
  var scrollLeft = _a5.scrollLeft, scrollWidth = _a5.scrollWidth, clientWidth = _a5.clientWidth;
  return [
    scrollLeft,
    scrollWidth,
    clientWidth
  ];
};
var elementCouldBeScrolled2 = function(axis, node) {
  return axis === "v" ? elementCouldBeVScrolled2(node) : elementCouldBeHScrolled2(node);
};
var getScrollVariables2 = function(axis, node) {
  return axis === "v" ? getVScrollVariables2(node) : getHScrollVariables2(node);
};
var getDirectionFactor2 = function(axis, direction) {
  return axis === "h" && direction === "rtl" ? -1 : 1;
};
var handleScroll2 = function(axis, endTarget, event, sourceDelta, noOverscroll) {
  var directionFactor = getDirectionFactor2(axis, window.getComputedStyle(endTarget).direction);
  var delta = directionFactor * sourceDelta;
  var target = event.target;
  var targetInLock = endTarget.contains(target);
  var shouldCancelScroll = false;
  var isDeltaPositive = delta > 0;
  var availableScroll = 0;
  var availableScrollTop = 0;
  do {
    var _a5 = getScrollVariables2(axis, target), position = _a5[0], scroll_1 = _a5[1], capacity = _a5[2];
    var elementScroll = scroll_1 - capacity - directionFactor * position;
    if (position || elementScroll) {
      if (elementCouldBeScrolled2(axis, target)) {
        availableScroll += elementScroll;
        availableScrollTop += position;
      }
    }
    if (target instanceof ShadowRoot) {
      target = target.host;
    } else {
      target = target.parentNode;
    }
  } while (
    // portaled content
    !targetInLock && target !== document.body || // self content
    targetInLock && (endTarget.contains(target) || endTarget === target)
  );
  if (isDeltaPositive && (noOverscroll && Math.abs(availableScroll) < 1 || !noOverscroll && delta > availableScroll)) {
    shouldCancelScroll = true;
  } else if (!isDeltaPositive && (noOverscroll && Math.abs(availableScrollTop) < 1 || !noOverscroll && -delta > availableScrollTop)) {
    shouldCancelScroll = true;
  }
  return shouldCancelScroll;
};

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var getTouchXY2 = function(event) {
  return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
};
var getDeltaXY2 = function(event) {
  return [event.deltaX, event.deltaY];
};
var extractRef2 = function(ref) {
  return ref && "current" in ref ? ref.current : ref;
};
var deltaCompare2 = function(x2, y2) {
  return x2[0] === y2[0] && x2[1] === y2[1];
};
var generateStyle2 = function(id) {
  return "\n  .block-interactivity-".concat(id, " {pointer-events: none;}\n  .allow-interactivity-").concat(id, " {pointer-events: all;}\n");
};
var idCounter2 = 0;
var lockStack2 = [];
function RemoveScrollSideCar2(props) {
  var shouldPreventQueue = React81.useRef([]);
  var touchStartRef = React81.useRef([0, 0]);
  var activeAxis = React81.useRef();
  var id = React81.useState(idCounter2++)[0];
  var Style2 = React81.useState(styleSingleton)[0];
  var lastProps = React81.useRef(props);
  React81.useEffect(function() {
    lastProps.current = props;
  }, [props]);
  React81.useEffect(function() {
    if (props.inert) {
      document.body.classList.add("block-interactivity-".concat(id));
      var allow_1 = __spreadArray4([props.lockRef.current], (props.shards || []).map(extractRef2), true).filter(Boolean);
      allow_1.forEach(function(el) {
        return el.classList.add("allow-interactivity-".concat(id));
      });
      return function() {
        document.body.classList.remove("block-interactivity-".concat(id));
        allow_1.forEach(function(el) {
          return el.classList.remove("allow-interactivity-".concat(id));
        });
      };
    }
    return;
  }, [props.inert, props.lockRef.current, props.shards]);
  var shouldCancelEvent = React81.useCallback(function(event, parent) {
    if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) {
      return !lastProps.current.allowPinchZoom;
    }
    var touch = getTouchXY2(event);
    var touchStart = touchStartRef.current;
    var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0];
    var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1];
    var currentAxis;
    var target = event.target;
    var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v";
    if ("touches" in event && moveDirection === "h" && target.type === "range") {
      return false;
    }
    var canBeScrolledInMainDirection = locationCouldBeScrolled2(moveDirection, target);
    if (!canBeScrolledInMainDirection) {
      return true;
    }
    if (canBeScrolledInMainDirection) {
      currentAxis = moveDirection;
    } else {
      currentAxis = moveDirection === "v" ? "h" : "v";
      canBeScrolledInMainDirection = locationCouldBeScrolled2(moveDirection, target);
    }
    if (!canBeScrolledInMainDirection) {
      return false;
    }
    if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) {
      activeAxis.current = currentAxis;
    }
    if (!currentAxis) {
      return true;
    }
    var cancelingAxis = activeAxis.current || currentAxis;
    return handleScroll2(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true);
  }, []);
  var shouldPrevent = React81.useCallback(function(_event) {
    var event = _event;
    if (!lockStack2.length || lockStack2[lockStack2.length - 1] !== Style2) {
      return;
    }
    var delta = "deltaY" in event ? getDeltaXY2(event) : getTouchXY2(event);
    var sourceEvent = shouldPreventQueue.current.filter(function(e3) {
      return e3.name === event.type && (e3.target === event.target || event.target === e3.shadowParent) && deltaCompare2(e3.delta, delta);
    })[0];
    if (sourceEvent && sourceEvent.should) {
      if (event.cancelable) {
        event.preventDefault();
      }
      return;
    }
    if (!sourceEvent) {
      var shardNodes = (lastProps.current.shards || []).map(extractRef2).filter(Boolean).filter(function(node) {
        return node.contains(event.target);
      });
      var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
      if (shouldStop) {
        if (event.cancelable) {
          event.preventDefault();
        }
      }
    }
  }, []);
  var shouldCancel = React81.useCallback(function(name, delta, target, should) {
    var event = { name, delta, target, should, shadowParent: getOutermostShadowParent2(target) };
    shouldPreventQueue.current.push(event);
    setTimeout(function() {
      shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e3) {
        return e3 !== event;
      });
    }, 1);
  }, []);
  var scrollTouchStart = React81.useCallback(function(event) {
    touchStartRef.current = getTouchXY2(event);
    activeAxis.current = void 0;
  }, []);
  var scrollWheel = React81.useCallback(function(event) {
    shouldCancel(event.type, getDeltaXY2(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  var scrollTouchMove = React81.useCallback(function(event) {
    shouldCancel(event.type, getTouchXY2(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  React81.useEffect(function() {
    lockStack2.push(Style2);
    props.setCallbacks({
      onScrollCapture: scrollWheel,
      onWheelCapture: scrollWheel,
      onTouchMoveCapture: scrollTouchMove
    });
    document.addEventListener("wheel", shouldPrevent, nonPassive2);
    document.addEventListener("touchmove", shouldPrevent, nonPassive2);
    document.addEventListener("touchstart", scrollTouchStart, nonPassive2);
    return function() {
      lockStack2 = lockStack2.filter(function(inst) {
        return inst !== Style2;
      });
      document.removeEventListener("wheel", shouldPrevent, nonPassive2);
      document.removeEventListener("touchmove", shouldPrevent, nonPassive2);
      document.removeEventListener("touchstart", scrollTouchStart, nonPassive2);
    };
  }, []);
  var removeScrollBar = props.removeScrollBar, inert = props.inert;
  return React81.createElement(
    React81.Fragment,
    null,
    inert ? React81.createElement(Style2, { styles: generateStyle2(id) }) : null,
    removeScrollBar ? React81.createElement(RemoveScrollBar, { gapMode: props.gapMode }) : null
  );
}
function getOutermostShadowParent2(node) {
  var shadowParent = null;
  while (node !== null) {
    if (node instanceof ShadowRoot) {
      shadowParent = node.host;
      node = node.host;
    }
    node = node.parentNode;
  }
  return shadowParent;
}

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/sidecar.js
var sidecar_default2 = exportSidecar(effectCar2, RemoveScrollSideCar2);

// node_modules/@radix-ui/react-popover/node_modules/react-remove-scroll/dist/es2015/Combination.js
var ReactRemoveScroll2 = React82.forwardRef(function(props, ref) {
  return React82.createElement(RemoveScroll2, __assign5({}, props, { ref, sideCar: sidecar_default2 }));
});
ReactRemoveScroll2.classNames = RemoveScroll2.classNames;
var Combination_default2 = ReactRemoveScroll2;

// node_modules/@radix-ui/react-popover/dist/index.mjs
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
"use client";
var POPOVER_NAME = "Popover";
var [createPopoverContext, createPopoverScope] = createContextScope(POPOVER_NAME, [
  createPopperScope3
]);
var usePopperScope3 = createPopperScope3();
var [PopoverProvider, usePopoverContext] = createPopoverContext(POPOVER_NAME);
var Popover = (props) => {
  const {
    __scopePopover,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = false
  } = props;
  const popperScope = usePopperScope3(__scopePopover);
  const triggerRef = React83.useRef(null);
  const [hasCustomAnchor, setHasCustomAnchor] = React83.useState(false);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Root25, { ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
    PopoverProvider,
    {
      scope: __scopePopover,
      contentId: useId(),
      triggerRef,
      open,
      onOpenChange: setOpen,
      onOpenToggle: React83.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      hasCustomAnchor,
      onCustomAnchorAdd: React83.useCallback(() => setHasCustomAnchor(true), []),
      onCustomAnchorRemove: React83.useCallback(() => setHasCustomAnchor(false), []),
      modal,
      children
    }
  ) });
};
Popover.displayName = POPOVER_NAME;
var ANCHOR_NAME5 = "PopoverAnchor";
var PopoverAnchor = React83.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...anchorProps } = props;
    const context = usePopoverContext(ANCHOR_NAME5, __scopePopover);
    const popperScope = usePopperScope3(__scopePopover);
    const { onCustomAnchorAdd, onCustomAnchorRemove } = context;
    React83.useEffect(() => {
      onCustomAnchorAdd();
      return () => onCustomAnchorRemove();
    }, [onCustomAnchorAdd, onCustomAnchorRemove]);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Anchor4, { ...popperScope, ...anchorProps, ref: forwardedRef });
  }
);
PopoverAnchor.displayName = ANCHOR_NAME5;
var TRIGGER_NAME4 = "PopoverTrigger";
var PopoverTrigger = React83.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...triggerProps } = props;
    const context = usePopoverContext(TRIGGER_NAME4, __scopePopover);
    const popperScope = usePopperScope3(__scopePopover);
    const composedTriggerRef = useComposedRefs7(forwardedRef, context.triggerRef);
    const trigger = /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      Primitive7.button,
      {
        type: "button",
        "aria-haspopup": "dialog",
        "aria-expanded": context.open,
        "aria-controls": context.contentId,
        "data-state": getState2(context.open),
        ...triggerProps,
        ref: composedTriggerRef,
        onClick: composeEventHandlers7(props.onClick, context.onOpenToggle)
      }
    );
    return context.hasCustomAnchor ? trigger : /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Anchor4, { asChild: true, ...popperScope, children: trigger });
  }
);
PopoverTrigger.displayName = TRIGGER_NAME4;
var PORTAL_NAME7 = "PopoverPortal";
var [PortalProvider3, usePortalContext3] = createPopoverContext(PORTAL_NAME7, {
  forceMount: void 0
});
var PopoverPortal = (props) => {
  const { __scopePopover, forceMount, children, container } = props;
  const context = usePopoverContext(PORTAL_NAME7, __scopePopover);
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(PortalProvider3, { scope: __scopePopover, forceMount, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Portal5, { asChild: true, container, children }) }) });
};
PopoverPortal.displayName = PORTAL_NAME7;
var CONTENT_NAME8 = "PopoverContent";
var PopoverContent = React83.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext3(CONTENT_NAME8, props.__scopePopover);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = usePopoverContext(CONTENT_NAME8, props.__scopePopover);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(PopoverContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(PopoverContentNonModal, { ...contentProps, ref: forwardedRef }) });
  }
);
PopoverContent.displayName = CONTENT_NAME8;
var PopoverContentModal = React83.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME8, props.__scopePopover);
    const contentRef = React83.useRef(null);
    const composedRefs = useComposedRefs7(forwardedRef, contentRef);
    const isRightClickOutsideRef = React83.useRef(false);
    React83.useEffect(() => {
      const content = contentRef.current;
      if (content)
        return hideOthers(content);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Combination_default2, { as: Slot8, allowPinchZoom: true, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      PopoverContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: true,
        onCloseAutoFocus: composeEventHandlers7(props.onCloseAutoFocus, (event) => {
          event.preventDefault();
          if (!isRightClickOutsideRef.current)
            context.triggerRef.current?.focus();
        }),
        onPointerDownOutside: composeEventHandlers7(
          props.onPointerDownOutside,
          (event) => {
            const originalEvent = event.detail.originalEvent;
            const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
            const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
            isRightClickOutsideRef.current = isRightClick;
          },
          { checkForDefaultPrevented: false }
        ),
        onFocusOutside: composeEventHandlers7(
          props.onFocusOutside,
          (event) => event.preventDefault(),
          { checkForDefaultPrevented: false }
        )
      }
    ) });
  }
);
var PopoverContentNonModal = React83.forwardRef(
  (props, forwardedRef) => {
    const context = usePopoverContext(CONTENT_NAME8, props.__scopePopover);
    const hasInteractedOutsideRef = React83.useRef(false);
    const hasPointerDownOutsideRef = React83.useRef(false);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      PopoverContentImpl,
      {
        ...props,
        ref: forwardedRef,
        trapFocus: false,
        disableOutsidePointerEvents: false,
        onCloseAutoFocus: (event) => {
          props.onCloseAutoFocus?.(event);
          if (!event.defaultPrevented) {
            if (!hasInteractedOutsideRef.current)
              context.triggerRef.current?.focus();
            event.preventDefault();
          }
          hasInteractedOutsideRef.current = false;
          hasPointerDownOutsideRef.current = false;
        },
        onInteractOutside: (event) => {
          props.onInteractOutside?.(event);
          if (!event.defaultPrevented) {
            hasInteractedOutsideRef.current = true;
            if (event.detail.originalEvent.type === "pointerdown") {
              hasPointerDownOutsideRef.current = true;
            }
          }
          const target = event.target;
          const targetIsTrigger = context.triggerRef.current?.contains(target);
          if (targetIsTrigger)
            event.preventDefault();
          if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) {
            event.preventDefault();
          }
        }
      }
    );
  }
);
var PopoverContentImpl = React83.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopover,
      trapFocus,
      onOpenAutoFocus,
      onCloseAutoFocus,
      disableOutsidePointerEvents,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      ...contentProps
    } = props;
    const context = usePopoverContext(CONTENT_NAME8, __scopePopover);
    const popperScope = usePopperScope3(__scopePopover);
    useFocusGuards();
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      FocusScope2,
      {
        asChild: true,
        loop: true,
        trapped: trapFocus,
        onMountAutoFocus: onOpenAutoFocus,
        onUnmountAutoFocus: onCloseAutoFocus,
        children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
          DismissableLayer3,
          {
            asChild: true,
            disableOutsidePointerEvents,
            onInteractOutside,
            onEscapeKeyDown,
            onPointerDownOutside,
            onFocusOutside,
            onDismiss: () => context.onOpenChange(false),
            children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
              Content4,
              {
                "data-state": getState2(context.open),
                role: "dialog",
                id: context.contentId,
                ...popperScope,
                ...contentProps,
                ref: forwardedRef,
                style: {
                  ...contentProps.style,
                  // re-namespace exposed content custom properties
                  ...{
                    "--radix-popover-content-transform-origin": "var(--radix-popper-transform-origin)",
                    "--radix-popover-content-available-width": "var(--radix-popper-available-width)",
                    "--radix-popover-content-available-height": "var(--radix-popper-available-height)",
                    "--radix-popover-trigger-width": "var(--radix-popper-anchor-width)",
                    "--radix-popover-trigger-height": "var(--radix-popper-anchor-height)"
                  }
                }
              }
            )
          }
        )
      }
    );
  }
);
var CLOSE_NAME = "PopoverClose";
var PopoverClose = React83.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...closeProps } = props;
    const context = usePopoverContext(CLOSE_NAME, __scopePopover);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      Primitive7.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers7(props.onClick, () => context.onOpenChange(false))
      }
    );
  }
);
PopoverClose.displayName = CLOSE_NAME;
var ARROW_NAME7 = "PopoverArrow";
var PopoverArrow = React83.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopover, ...arrowProps } = props;
    const popperScope = usePopperScope3(__scopePopover);
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Arrow6, { ...popperScope, ...arrowProps, ref: forwardedRef });
  }
);
PopoverArrow.displayName = ARROW_NAME7;
function getState2(open) {
  return open ? "open" : "closed";
}
var Root26 = Popover;
var Trigger3 = PopoverTrigger;
var Portal6 = PopoverPortal;
var Content24 = PopoverContent;

// src/components/ui/popover.tsx
var Popover2 = Root26;
var PopoverTrigger2 = Trigger3;
var PopoverContent2 = React84.forwardRef(({ className, align = "center", sideOffset = 4, container, ...props }, ref) => /* @__PURE__ */ React84.createElement(Portal6, { container: container ?? activeDocument.body }, /* @__PURE__ */ React84.createElement(
  Content24,
  {
    ref,
    align,
    sideOffset,
    className: cn(
      "z-popover w-72 rounded-md border border-border bg-primary p-4 text-normal  shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    ),
    ...props
  }
)));
PopoverContent2.displayName = Content24.displayName;

// src/context.ts
var React85 = __toESM(require_react());
var AppContext = React85.createContext(void 0);
var EventTargetContext = React85.createContext(void 0);

// src/hooks/useActiveFile.ts
var import_react17 = __toESM(require_react());
function useActiveFile() {
  const [activeFile, setActiveFile] = (0, import_react17.useState)(null);
  const eventTarget = (0, import_react17.useContext)(EventTargetContext);
  (0, import_react17.useEffect)(() => {
    const handleActiveLeafChange = () => {
      const activeFile2 = app.workspace.getActiveFile();
      setActiveFile(activeFile2);
    };
    eventTarget?.addEventListener(EVENT_NAMES.ACTIVE_LEAF_CHANGE, handleActiveLeafChange);
    return () => {
      eventTarget?.removeEventListener(EVENT_NAMES.ACTIVE_LEAF_CHANGE, handleActiveLeafChange);
    };
  }, [eventTarget]);
  return activeFile;
}

// src/noteUtils.ts
var import_obsidian34 = require("obsidian");
function getLinkedNotes(file, limit2 = 20) {
  const fileCache = app.metadataCache.getFileCache(file);
  const linkedNotes = [];
  if (fileCache?.links) {
    for (const link of fileCache.links) {
      const resolvedFile = app.metadataCache.getFirstLinkpathDest(link.link, file.path);
      if (resolvedFile) {
        linkedNotes.push(resolvedFile);
        if (linkedNotes.length >= limit2) {
          break;
        }
      }
    }
  }
  if (fileCache?.embeds && linkedNotes.length < limit2) {
    for (const embed of fileCache.embeds) {
      const resolvedFile = app.metadataCache.getFirstLinkpathDest(embed.link, file.path);
      if (resolvedFile) {
        linkedNotes.push(resolvedFile);
        if (linkedNotes.length >= limit2) {
          break;
        }
      }
    }
  }
  return [...new Set(linkedNotes)];
}
function getBacklinkedNotes(file, limit2 = 20) {
  const backlinkedNotes = [];
  const backlinks = app.metadataCache.getBacklinksForFile(file);
  if (backlinks?.data) {
    for (const [path] of backlinks.data) {
      const file2 = app.vault.getAbstractFileByPath(path);
      if (file2 instanceof import_obsidian34.TFile) {
        backlinkedNotes.push(file2);
        if (backlinkedNotes.length >= limit2) {
          break;
        }
      }
    }
  }
  return backlinkedNotes;
}

// src/search/findRelevantNotes.ts
var import_obsidian35 = require("obsidian");
var MIN_SIMILARITY_SCORE = 0.4;
var MAX_K = 20;
var ORIGINAL_WEIGHT = 0.7;
var LINKS_WEIGHT = 0.3;
async function getNoteEmbeddings(notePath, db) {
  const debug4 = getSettings().debug;
  const hits = await DBOperations.getDocsByPath(db, notePath);
  if (!hits) {
    if (debug4) {
      console.log("No hits found for note:", notePath);
    }
    return [];
  }
  const embeddings = [];
  for (const hit of hits) {
    if (!hit?.document?.embedding) {
      if (debug4) {
        console.log("No embedding found for note:", notePath);
      }
      continue;
    }
    embeddings.push(hit.document.embedding);
  }
  return embeddings;
}
function getAverageEmbedding(noteEmbeddings) {
  if (noteEmbeddings.length === 0) {
    return [];
  }
  const embeddingLength = noteEmbeddings[0].length;
  const averageEmbedding = Array(embeddingLength).fill(0);
  noteEmbeddings.forEach((embedding) => {
    embedding.forEach((value, index2) => {
      averageEmbedding[index2] += value / embeddingLength;
    });
  });
  return averageEmbedding;
}
function getHighestScoreHits(hits, currentFilePath) {
  const hitMap = /* @__PURE__ */ new Map();
  for (const hit of hits) {
    const matchingScore = hitMap.get(hit.document.path);
    if (matchingScore) {
      if (hit.score > matchingScore) {
        hitMap.set(hit.document.path, hit.score);
      }
    } else {
      hitMap.set(hit.document.path, hit.score);
    }
  }
  hitMap.delete(currentFilePath);
  return hitMap;
}
async function calculateSimilarityScore({
  db,
  filePath
}) {
  const debug4 = getSettings().debug;
  const currentNoteEmbeddings = await getNoteEmbeddings(filePath, db);
  const averageEmbedding = getAverageEmbedding(currentNoteEmbeddings);
  if (averageEmbedding.length === 0) {
    if (debug4) {
      console.log("No embeddings found for note:", filePath);
    }
    return /* @__PURE__ */ new Map();
  }
  const hits = await DBOperations.getDocsByEmbedding(db, averageEmbedding, {
    limit: MAX_K,
    similarity: MIN_SIMILARITY_SCORE
  });
  return getHighestScoreHits(hits, filePath);
}
function getNoteLinks(file) {
  const resultMap = /* @__PURE__ */ new Map();
  const linkedNotes = getLinkedNotes(file);
  const linkedNotePaths = linkedNotes.map((note) => note.path);
  for (const notePath of linkedNotePaths) {
    resultMap.set(notePath, { links: true, backlinks: false });
  }
  const backlinkedNotes = getBacklinkedNotes(file);
  const backlinkedNotePaths = backlinkedNotes.map((note) => note.path);
  for (const notePath of backlinkedNotePaths) {
    if (resultMap.has(notePath)) {
      resultMap.set(notePath, { links: true, backlinks: true });
    } else {
      resultMap.set(notePath, { links: false, backlinks: true });
    }
  }
  return resultMap;
}
function mergeScoreMaps(similarityScoreMap, noteLinks) {
  const mergedMap = /* @__PURE__ */ new Map();
  const totalWeight = ORIGINAL_WEIGHT + LINKS_WEIGHT;
  for (const [key, value] of similarityScoreMap) {
    mergedMap.set(key, value * ORIGINAL_WEIGHT / totalWeight);
  }
  for (const [key, value] of noteLinks) {
    let score = 0;
    if (value.links && value.backlinks) {
      score = LINKS_WEIGHT;
    } else if (value.links) {
      score = LINKS_WEIGHT * 0.8;
    } else if (value.backlinks) {
      score = LINKS_WEIGHT * 0.8;
    }
    mergedMap.set(key, (mergedMap.get(key) ?? 0) + score);
  }
  return mergedMap;
}
async function findRelevantNotes({
  db,
  filePath
}) {
  const file = app.vault.getAbstractFileByPath(filePath);
  if (!(file instanceof import_obsidian35.TFile)) {
    return [];
  }
  const similarityScoreMap = await calculateSimilarityScore({ db, filePath });
  const noteLinks = getNoteLinks(file);
  const mergedScoreMap = mergeScoreMaps(similarityScoreMap, noteLinks);
  const sortedHits = Array.from(mergedScoreMap.entries()).sort((a3, b3) => {
    const aPath = a3[0];
    const bPath = b3[0];
    const aCategory = getSimilarityCategory(similarityScoreMap.get(aPath) ?? 0);
    const bCategory = getSimilarityCategory(similarityScoreMap.get(bPath) ?? 0);
    if (aCategory !== bCategory) {
      return bCategory - aCategory;
    }
    return b3[1] - a3[1];
  });
  return sortedHits.map(([path, score]) => {
    const file2 = app.vault.getAbstractFileByPath(path);
    if (!(file2 instanceof import_obsidian35.TFile)) {
      return null;
    }
    return {
      document: {
        path,
        title: file2.basename
      },
      metadata: {
        score,
        similarityScore: similarityScoreMap.get(path),
        hasOutgoingLinks: noteLinks.get(path)?.links ?? false,
        hasBacklinks: noteLinks.get(path)?.backlinks ?? false
      }
    };
  }).filter((entry) => entry !== null);
}
function getSimilarityCategory(score) {
  if (score > 0.7)
    return 3;
  if (score > 0.55)
    return 2;
  return 1;
}

// src/components/chat-components/RelevantNotes.tsx
var import_obsidian36 = require("obsidian");
var import_react18 = __toESM(require_react());
function useRelevantNotes(refresher) {
  const [relevantNotes, setRelevantNotes] = (0, import_react18.useState)([]);
  const activeFile = useActiveFile();
  (0, import_react18.useEffect)(() => {
    async function fetchNotes() {
      if (!activeFile?.path)
        return;
      const db = await VectorStoreManager.getInstance().getDb();
      const notes = await findRelevantNotes({ db, filePath: activeFile.path });
      setRelevantNotes(notes);
    }
    fetchNotes();
  }, [activeFile?.path, refresher]);
  return relevantNotes;
}
function useHasIndex(notePath, refresher) {
  const [hasIndex, setHasIndex] = (0, import_react18.useState)(true);
  (0, import_react18.useEffect)(() => {
    if (!notePath)
      return;
    async function fetchHasIndex() {
      const hasIndex2 = await VectorStoreManager.getInstance().hasIndex(notePath);
      setHasIndex(hasIndex2);
    }
    fetchHasIndex();
  }, [notePath, refresher]);
  return hasIndex;
}
var ExplainerBadge = (0, import_react18.forwardRef)(
  ({ children, ...props }, ref) => {
    return /* @__PURE__ */ import_react18.default.createElement("div", { ref, ...props, className: "flex gap-2" }, /* @__PURE__ */ import_react18.default.createElement(
      Badge,
      {
        variant: "secondary",
        className: "text-muted font-normal whitespace-nowrap cursor-default"
      },
      children
    ));
  }
);
ExplainerBadge.displayName = "ExplainerBadge";
function inSameFolder(path1, path2) {
  const folder1 = path1.split("/").slice(0, -1).join("/");
  const folder2 = path2.split("/").slice(0, -1).join("/");
  return folder1 === folder2;
}
function SimilarityBadge({ score }) {
  const category = getSimilarityCategory(score);
  let text = "\u{1F534} Low Similarity";
  if (category === 2)
    text = "\u{1F7E0} Medium Similarity";
  if (category === 3)
    text = "\u{1F7E2} High Similarity";
  return /* @__PURE__ */ import_react18.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react18.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(ExplainerBadge, null, text)), /* @__PURE__ */ import_react18.default.createElement(TooltipContent2, { side: "right" }, "Similarity Score: ", Math.round(score * 100).toFixed(0), "%"));
}
function Metadata({ note }) {
  return /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-1" }, note.metadata.similarityScore != null && /* @__PURE__ */ import_react18.default.createElement(SimilarityBadge, { score: note.metadata.similarityScore }), note.metadata.hasOutgoingLinks && /* @__PURE__ */ import_react18.default.createElement(ExplainerBadge, null, "Outgoing Links"), note.metadata.hasBacklinks && /* @__PURE__ */ import_react18.default.createElement(ExplainerBadge, null, "Backlinks"));
}
function RelevantNote({
  showPath = false,
  note,
  onAddToChat,
  onNavigateToNote
}) {
  return /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-2 p-2 justify-between rounded-md border border-border border-solid" }, /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex flex-col gap-2 flex-1 overflow-hidden" }, /* @__PURE__ */ import_react18.default.createElement(
    "a",
    {
      onClick: onNavigateToNote,
      className: "text-sm text-normal font-bold text-ellipsis overflow-hidden whitespace-nowrap w-full"
    },
    note.document.title
  ), showPath && /* @__PURE__ */ import_react18.default.createElement("span", { className: "text-xs text-faint text-ellipsis overflow-hidden whitespace-nowrap w-full" }, note.document.path), /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-1" }, /* @__PURE__ */ import_react18.default.createElement(Metadata, { note }))), /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ import_react18.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react18.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(Button, { variant: "ghost2", size: "icon", onClick: onAddToChat }, /* @__PURE__ */ import_react18.default.createElement(CirclePlus, { className: "size-4" }))), /* @__PURE__ */ import_react18.default.createElement(TooltipContent2, null, "Add to Chat"))));
}
function RelevantNotePopover({
  note,
  onAddToChat,
  onNavigateToNote,
  children
}) {
  return /* @__PURE__ */ import_react18.default.createElement(Popover2, { key: note.document.path }, /* @__PURE__ */ import_react18.default.createElement(PopoverTrigger2, { asChild: true }, children), /* @__PURE__ */ import_react18.default.createElement(PopoverContent2, { className: "flex flex-col gap-2 overflow-hidden w-fit min-w-72 max-w-96" }, /* @__PURE__ */ import_react18.default.createElement("span", { className: "text-sm text-normal" }, note.document.title), /* @__PURE__ */ import_react18.default.createElement("span", { className: "text-xs text-muted" }, note.document.path), /* @__PURE__ */ import_react18.default.createElement(Metadata, { note }), /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ import_react18.default.createElement(
    "button",
    {
      onClick: onAddToChat,
      className: "!bg-transparent inline-flex items-center gap-2 border border-border border-solid !shadow-none hover:!bg-interactive-hover"
    },
    "Add to Chat ",
    /* @__PURE__ */ import_react18.default.createElement(CirclePlus, { className: "size-4" })
  ), /* @__PURE__ */ import_react18.default.createElement(
    "button",
    {
      onClick: onNavigateToNote,
      className: "!bg-transparent inline-flex items-center gap-2 border border-border border-solid !shadow-none hover:!bg-interactive-hover"
    },
    "Navigate to Note ",
    /* @__PURE__ */ import_react18.default.createElement(ArrowRight, { className: "size-4" })
  ))));
}
var RelevantNotes = (0, import_react18.memo)(
  ({
    className,
    onInsertToChat,
    defaultOpen = false
  }) => {
    const [refresher, setRefresher] = (0, import_react18.useState)(0);
    const [isOpen, setIsOpen] = (0, import_react18.useState)(defaultOpen);
    const relevantNotes = useRelevantNotes(refresher);
    const activeFile = useActiveFile();
    const hasIndex = useHasIndex(activeFile?.path ?? "", refresher);
    const navigateToNote = (notePath) => {
      const file = app.vault.getAbstractFileByPath(notePath);
      if (file instanceof import_obsidian36.TFile) {
        app.workspace.getLeaf(false).openFile(file);
      }
    };
    const addToChat = (prompt) => {
      onInsertToChat(`[[${prompt}]]`);
    };
    const refreshIndex = async () => {
      if (activeFile) {
        await VectorStoreManager.getInstance().reindexFile(activeFile);
        new import_obsidian36.Notice(`Reindexed ${activeFile.name}`);
        setRefresher(refresher + 1);
      }
    };
    return /* @__PURE__ */ import_react18.default.createElement(
      "div",
      {
        className: cn(
          "@container w-full border border-transparent border-b-border border-solid pb-2",
          className
        )
      },
      /* @__PURE__ */ import_react18.default.createElement(Collapsible2, { open: isOpen, onOpenChange: setIsOpen }, /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex justify-between items-center pl-1 pb-2" }, /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex gap-2 items-center flex-1" }, /* @__PURE__ */ import_react18.default.createElement("span", { className: "font-semibold text-normal" }, "Relevant Notes"), /* @__PURE__ */ import_react18.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react18.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(Info, { className: "size-4 text-muted" })), /* @__PURE__ */ import_react18.default.createElement(TooltipContent2, { side: "bottom", className: "w-64" }, "Relevance is a combination of semantic similarity and links.")), !hasIndex && /* @__PURE__ */ import_react18.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react18.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(TriangleAlert, { className: "size-4 text-warning" })), /* @__PURE__ */ import_react18.default.createElement(TooltipContent2, { side: "bottom" }, "Note has not been indexed"))), /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex items-center" }, /* @__PURE__ */ import_react18.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react18.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(Button, { variant: "ghost2", size: "icon", onClick: refreshIndex }, /* @__PURE__ */ import_react18.default.createElement(RefreshCcw, { className: "size-4" }))), /* @__PURE__ */ import_react18.default.createElement(TooltipContent2, { side: "bottom" }, "Reindex Current Note")), relevantNotes.length > 0 && /* @__PURE__ */ import_react18.default.createElement(CollapsibleTrigger2, { asChild: true }, /* @__PURE__ */ import_react18.default.createElement(Button, { variant: "ghost2", size: "icon" }, isOpen ? /* @__PURE__ */ import_react18.default.createElement(ChevronUp, { className: "size-5" }) : /* @__PURE__ */ import_react18.default.createElement(ChevronDown, { className: "size-5" }))))), relevantNotes.length === 0 && /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex flex-wrap gap-x-2 gap-y-1 max-h-12 overflow-y-hidden px-1" }, /* @__PURE__ */ import_react18.default.createElement("span", { className: "text-xs text-muted" }, "No relevant notes found")), !isOpen && relevantNotes.length > 0 && /* @__PURE__ */ import_react18.default.createElement("div", { className: "flex flex-wrap gap-x-2 gap-y-1 max-h-6 overflow-y-hidden px-1" }, relevantNotes.map((note) => /* @__PURE__ */ import_react18.default.createElement(
        RelevantNotePopover,
        {
          key: note.document.path,
          note,
          onAddToChat: () => addToChat(note.document.title),
          onNavigateToNote: () => navigateToNote(note.document.path)
        },
        /* @__PURE__ */ import_react18.default.createElement(
          Badge,
          {
            variant: "outline",
            key: note.document.path,
            className: "text-xs max-w-40 text-muted hover:cursor-pointer hover:bg-interactive-hover"
          },
          /* @__PURE__ */ import_react18.default.createElement("span", { className: "text-ellipsis overflow-hidden whitespace-nowrap" }, note.document.title)
        )
      ))), /* @__PURE__ */ import_react18.default.createElement(CollapsibleContent2, null, /* @__PURE__ */ import_react18.default.createElement("div", { className: "px-1 py-2 max-h-screen overflow-y-auto flex flex-col gap-2 @2xl:grid @2xl:grid-cols-2 @4xl:grid-cols-3" }, relevantNotes.map((note) => /* @__PURE__ */ import_react18.default.createElement(
        RelevantNote,
        {
          showPath: !inSameFolder(activeFile?.path ?? "", note.document.path),
          note,
          key: note.document.path,
          onAddToChat: () => addToChat(note.document.title),
          onNavigateToNote: () => navigateToNote(note.document.path)
        }
      )))))
    );
  }
);
RelevantNotes.displayName = "RelevantNotes";

// src/components/ui/card.tsx
var React87 = __toESM(require_react());
var Card = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement(
    "div",
    {
      ref,
      className: cn("rounded-xl border border-border bg-primary text-normal shadow", className),
      ...props
    }
  )
);
Card.displayName = "Card";
var CardHeader = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement("div", { ref, className: cn("flex flex-col space-y-1.5 p-6", className), ...props })
);
CardHeader.displayName = "CardHeader";
var CardTitle = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement(
    "div",
    {
      ref,
      className: cn("font-semibold leading-none tracking-tight", className),
      ...props
    }
  )
);
CardTitle.displayName = "CardTitle";
var CardDescription = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement("div", { ref, className: cn("text-sm text-muted", className), ...props })
);
CardDescription.displayName = "CardDescription";
var CardContent = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement("div", { ref, className: cn("p-6 pt-0", className), ...props })
);
CardContent.displayName = "CardContent";
var CardFooter = React87.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React87.createElement("div", { ref, className: cn("flex items-center p-6 pt-0", className), ...props })
);
CardFooter.displayName = "CardFooter";

// src/components/chat-components/SuggestedPrompts.tsx
var import_react19 = __toESM(require_react());
var SUGGESTED_PROMPTS = {
  activeNote: {
    title: "Active Note Insights",
    prompts: [
      `Provide three follow-up questions worded as if I'm asking you based on {activeNote}?`,
      `What key questions does {activeNote} answer?`,
      `Give me a quick recap of {activeNote} in two sentences.`
    ]
  },
  quoteNote: {
    title: "Note Link Chat",
    prompts: [
      `Based on [[<note>]], what improvements should we focus on next?`,
      `Summarize the key points from [[<note>]].`,
      `Summarize the recent updates from [[<note>]].`,
      `Roast my writing in [[<note>]] and give concrete actionable feedback`
    ]
  },
  fun: {
    title: "Test LLM",
    prompts: [
      `9.11 and 9.8, which is bigger?`,
      `What's the longest river in the world?`,
      `If a lead ball and a feather are dropped simultaneously from the same height, which will reach the ground first?`
    ]
  },
  qaVault: {
    title: "Vault Q&A",
    prompts: [
      `What insights can I gather about <topic> from my notes?`,
      `Explain <concept> based on my stored notes.`,
      `Highlight important details on <topic> from my notes.`,
      `Based on my notes on <topic>, what is the question that I should be asking, but am not?`
    ]
  },
  copilotPlus: {
    title: "Copilot Plus",
    prompts: [
      `Give me a recap of last week @vault`,
      `What are the key takeaways from my notes on <topic> @vault`,
      `Summarize <url> in under 10 bullet points`,
      `@youtube <video_url>`,
      `@web what are most recent updates in the AI industry`,
      `What are the key insights from this paper <arxiv_url>`,
      `What new methods are proposed in this paper [[<note_with_embedded_pdf>]]`
    ]
  }
};
var PROMPT_KEYS = {
  ["llm_chain" /* LLM_CHAIN */]: ["activeNote", "quoteNote", "fun"],
  ["vault_qa" /* VAULT_QA_CHAIN */]: ["qaVault", "qaVault", "quoteNote"],
  ["copilot_plus" /* COPILOT_PLUS_CHAIN */]: ["copilotPlus", "copilotPlus", "copilotPlus"]
};
function getRandomPrompt(chainType = "llm_chain" /* LLM_CHAIN */) {
  const keys = PROMPT_KEYS[chainType] || PROMPT_KEYS["llm_chain" /* LLM_CHAIN */];
  const shuffledPrompts = {};
  return keys.map((key) => {
    if (!shuffledPrompts[key]) {
      shuffledPrompts[key] = [...SUGGESTED_PROMPTS[key].prompts].sort(() => Math.random() - 0.5);
    }
    return {
      title: SUGGESTED_PROMPTS[key].title,
      text: shuffledPrompts[key].pop() || SUGGESTED_PROMPTS[key].prompts[0]
    };
  });
}
var SuggestedPrompts = ({ onClick }) => {
  const [chainType] = useChainType();
  const prompts = (0, import_react19.useMemo)(() => getRandomPrompt(chainType), [chainType]);
  const settings = useSettingsValue();
  const indexVaultToVectorStore = settings.indexVaultToVectorStore;
  return /* @__PURE__ */ import_react19.default.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ import_react19.default.createElement(Card, { className: "w-full bg-transparent" }, /* @__PURE__ */ import_react19.default.createElement(CardHeader, { className: "px-2" }, /* @__PURE__ */ import_react19.default.createElement(CardTitle, null, "Suggested Prompts")), /* @__PURE__ */ import_react19.default.createElement(CardContent, { className: "p-2 pt-0" }, /* @__PURE__ */ import_react19.default.createElement("div", { className: "flex flex-col gap-2" }, prompts.map((prompt, i3) => /* @__PURE__ */ import_react19.default.createElement(
    "div",
    {
      key: i3,
      className: "flex gap-2 p-2 justify-between text-sm rounded-md border border-border border-solid"
    },
    /* @__PURE__ */ import_react19.default.createElement("div", { className: "flex flex-col gap-1" }, /* @__PURE__ */ import_react19.default.createElement("div", { className: "text-muted" }, prompt.title), /* @__PURE__ */ import_react19.default.createElement("div", null, prompt.text)),
    /* @__PURE__ */ import_react19.default.createElement("div", { className: "flex items-start h-full" }, /* @__PURE__ */ import_react19.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react19.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react19.default.createElement(
      Button,
      {
        variant: "ghost2",
        size: "fit",
        className: "text-muted",
        onClick: () => onClick(prompt.text)
      },
      /* @__PURE__ */ import_react19.default.createElement(CirclePlus, { className: "size-4" })
    )), /* @__PURE__ */ import_react19.default.createElement(TooltipContent2, null, "Add to Chat")))
  ))))), chainType === "vault_qa" /* VAULT_QA_CHAIN */ && /* @__PURE__ */ import_react19.default.createElement("div", { className: "text-sm border border-border border-solid p-2 rounded-md" }, "Please note that this is a retrieval-based QA. Questions should contain keywords and concepts that exist literally in your vault"), chainType === "vault_qa" /* VAULT_QA_CHAIN */ && indexVaultToVectorStore === "NEVER" /* NEVER */ && /* @__PURE__ */ import_react19.default.createElement("div", { className: "text-sm border border-border border-solid p-2 rounded-md" }, /* @__PURE__ */ import_react19.default.createElement("div", null, /* @__PURE__ */ import_react19.default.createElement(TriangleAlert, { className: "size-4" }), " Your auto-index strategy is set to ", /* @__PURE__ */ import_react19.default.createElement("b", null, "NEVER"), ". Before proceeding, click the ", /* @__PURE__ */ import_react19.default.createElement("span", { className: "text-accent" }, "Refresh Index"), " button below or run the", " ", /* @__PURE__ */ import_react19.default.createElement("span", { className: "text-accent" }, "Copilot command: Index (refresh) vault for QA"), " to update the index.")));
};

// src/components/chat-components/ChatMessages.tsx
var import_react20 = __toESM(require_react());
var ChatMessages = (0, import_react20.memo)(
  ({
    chatHistory,
    currentAiMessage,
    loading,
    loadingMessage,
    app: app2,
    onRegenerate,
    onEdit,
    onDelete,
    onInsertToChat,
    onReplaceChat
  }) => {
    const [loadingDots, setLoadingDots] = (0, import_react20.useState)("");
    const settings = useSettingsValue();
    const scrollToBottom = () => {
      const chatMessagesContainer = document.querySelector("[data-testid='chat-messages']");
      if (chatMessagesContainer) {
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
      }
    };
    (0, import_react20.useEffect)(() => {
      if (!loading) {
        scrollToBottom();
      }
    }, [loading]);
    (0, import_react20.useEffect)(() => {
      let intervalId;
      if (loading) {
        intervalId = setInterval(() => {
          setLoadingDots((dots) => dots.length < 6 ? dots + "." : "");
        }, 200);
      } else {
        setLoadingDots("");
      }
      return () => clearInterval(intervalId);
    }, [loading]);
    if (!chatHistory.filter((message) => message.isVisible).length && !currentAiMessage) {
      return /* @__PURE__ */ import_react20.default.createElement("div", { className: "flex flex-col gap-2 overflow-y-auto w-full h-full" }, settings.showRelevantNotes && /* @__PURE__ */ import_react20.default.createElement(
        RelevantNotes,
        {
          onInsertToChat,
          defaultOpen: true,
          key: "relevant-notes-before-chat"
        }
      ), settings.showSuggestedPrompts && /* @__PURE__ */ import_react20.default.createElement(SuggestedPrompts, { onClick: onReplaceChat }));
    }
    const getLoadingMessage = () => {
      return loadingMessage ? `${loadingMessage} ${loadingDots}` : loadingDots;
    };
    return /* @__PURE__ */ import_react20.default.createElement("div", { className: "flex flex-col flex-1 h-full overflow-hidden" }, settings.showRelevantNotes && /* @__PURE__ */ import_react20.default.createElement(
      RelevantNotes,
      {
        className: "mb-4",
        onInsertToChat,
        defaultOpen: false,
        key: "relevant-notes-in-chat"
      }
    ), /* @__PURE__ */ import_react20.default.createElement(
      "div",
      {
        "data-testid": "chat-messages",
        className: "flex flex-col items-start justify-start flex-1 overflow-y-auto w-full break-words text-[calc(var(--font-text-size)_-_2px)] box-border scroll-smooth mt-auto select-text"
      },
      chatHistory.map(
        (message, index2) => message.isVisible && /* @__PURE__ */ import_react20.default.createElement(
          ChatSingleMessage_default,
          {
            key: index2,
            message,
            app: app2,
            isStreaming: false,
            onRegenerate: () => onRegenerate(index2),
            onEdit: (newMessage) => onEdit(index2, newMessage),
            onDelete: () => onDelete(index2)
          }
        )
      ),
      (currentAiMessage || loading) && /* @__PURE__ */ import_react20.default.createElement(
        ChatSingleMessage_default,
        {
          key: `ai_message_${currentAiMessage}`,
          message: {
            sender: "AI",
            message: currentAiMessage || getLoadingMessage(),
            isVisible: true,
            timestamp: null
          },
          app: app2,
          isStreaming: true,
          onDelete: () => {
          }
        }
      )
    ));
  }
);
ChatMessages.displayName = "ChatMessages";
var ChatMessages_default = ChatMessages;

// src/langchainStream.ts
var getAIResponse = async (userMessage, chainManager, addMessage, updateCurrentAiMessage, updateShouldAbort, options = {}) => {
  const abortController = new AbortController();
  updateShouldAbort(abortController);
  try {
    await chainManager.runChain(
      userMessage,
      abortController,
      updateCurrentAiMessage,
      addMessage,
      options
    );
  } catch (error) {
    console.error("Model request failed:", error);
    let errorMessage = "Model request failed: ";
    if (error instanceof Error) {
      errorMessage += error.message;
      if (error.cause) {
        errorMessage += ` Cause: ${error.cause}`;
      }
    } else if (typeof error === "object" && error !== null) {
      errorMessage += JSON.stringify(error);
    } else {
      errorMessage += String(error);
    }
    addMessage({
      sender: AI_SENDER,
      message: `Error: ${errorMessage}`,
      isVisible: true,
      timestamp: formatDateTime(new Date())
    });
  }
};

// src/mentions/Mention.ts
var Mention = class {
  constructor() {
    this.mentions = /* @__PURE__ */ new Map();
    this.brevilabsClient = BrevilabsClient.getInstance();
  }
  static getInstance() {
    if (!Mention.instance) {
      Mention.instance = new Mention();
    }
    return Mention.instance;
  }
  extractAllUrls(text) {
    const urlRegex = /https?:\/\/[^\s"'<>]+/g;
    return (text.match(urlRegex) || []).map((url) => url.replace(/,+$/, "")).filter((url, index2, self2) => self2.indexOf(url) === index2);
  }
  extractUrls(text) {
    const urlRegex = /https?:\/\/[^\s"'<>]+/g;
    return (text.match(urlRegex) || []).map((url) => url.replace(/,+$/, "")).filter((url, index2, self2) => self2.indexOf(url) === index2).filter((url) => !isYoutubeUrl(url));
  }
  async processUrl(url) {
    try {
      return await this.brevilabsClient.url4llm(url);
    } catch (error) {
      console.error(`Error processing URL ${url}:`, error);
      return { response: url, elapsed_time_ms: 0 };
    }
  }
  // For non-youtube URLs
  async processUrls(text) {
    const urls = this.extractUrls(text);
    let urlContext = "";
    const imageUrls = [];
    if (urls.length === 0) {
      return { urlContext: "", imageUrls: [] };
    }
    const processPromises = urls.map(async (url) => {
      if (await ImageProcessor.isImageUrl(url)) {
        imageUrls.push(url);
        return null;
      }
      if (!this.mentions.has(url)) {
        const processed = await this.processUrl(url);
        this.mentions.set(url, {
          type: "url",
          original: url,
          processed: processed.response
        });
      }
      return this.mentions.get(url);
    });
    const processedUrls = await Promise.all(processPromises);
    processedUrls.forEach((urlData) => {
      if (urlData?.processed) {
        urlContext += `

Content from ${urlData.original}:
${urlData.processed}`;
      }
    });
    return { urlContext, imageUrls };
  }
  getMentions() {
    return this.mentions;
  }
  clearMentions() {
    this.mentions.clear();
  }
};

// src/sharedState.ts
var import_react21 = __toESM(require_react());
var SharedState = class {
  constructor() {
    this.chatHistory = [];
  }
  addMessage(message) {
    this.chatHistory.push(message);
  }
  getMessages() {
    return this.chatHistory;
  }
  clearChatHistory() {
    this.chatHistory = [];
  }
};
function useSharedState(sharedState) {
  const [chatHistory, setChatHistory] = (0, import_react21.useState)(sharedState.getMessages());
  (0, import_react21.useEffect)(() => {
    setChatHistory(sharedState.getMessages());
  }, [sharedState]);
  const addMessage = (0, import_react21.useCallback)(
    (message) => {
      sharedState.addMessage(message);
      setChatHistory([...sharedState.getMessages()]);
    },
    [sharedState]
  );
  const clearMessages = (0, import_react21.useCallback)(() => {
    sharedState.clearChatHistory();
    setChatHistory([]);
  }, [sharedState]);
  return [chatHistory, addMessage, clearMessages];
}
var sharedState_default = SharedState;

// src/components/Chat.tsx
var import_obsidian37 = require("obsidian");
var import_react22 = __toESM(require_react());
var Chat4 = ({
  sharedState,
  chainManager,
  onSaveChat,
  updateUserMessageHistory,
  fileParserManager,
  plugin
}) => {
  const settings = useSettingsValue();
  const eventTarget = (0, import_react22.useContext)(EventTargetContext);
  const [chatHistory, addMessage, clearMessages] = useSharedState(sharedState);
  const [currentModelKey] = useModelKey();
  const [currentChain] = useChainType();
  const [currentAiMessage, setCurrentAiMessage] = (0, import_react22.useState)("");
  const [inputMessage, setInputMessage] = (0, import_react22.useState)("");
  const [abortController, setAbortController] = (0, import_react22.useState)(null);
  const [loading, setLoading] = (0, import_react22.useState)(false);
  const [loadingMessage, setLoadingMessage] = (0, import_react22.useState)(LOADING_MESSAGES.DEFAULT);
  const [historyIndex, setHistoryIndex] = (0, import_react22.useState)(-1);
  const [contextNotes, setContextNotes] = (0, import_react22.useState)([]);
  const [includeActiveNote, setIncludeActiveNote] = (0, import_react22.useState)(false);
  const [selectedImages, setSelectedImages] = (0, import_react22.useState)([]);
  const mention = Mention.getInstance();
  const contextProcessor = ContextProcessor.getInstance();
  const inputRef = (0, import_react22.useRef)(null);
  (0, import_react22.useEffect)(() => {
    const handleChatVisibility = () => {
      if (inputRef.current) {
        inputRef.current.focus();
      }
    };
    eventTarget?.addEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
    return () => {
      eventTarget?.removeEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
    };
  }, [eventTarget]);
  const appContext = (0, import_react22.useContext)(AppContext);
  const app2 = plugin.app || appContext;
  const processContextNotes = async (customPromptProcessor2, fileParserManager2) => {
    const activeNote = app2.workspace.getActiveFile();
    return await contextProcessor.processContextNotes(
      customPromptProcessor2,
      fileParserManager2,
      app2.vault,
      contextNotes,
      includeActiveNote,
      activeNote,
      currentChain
    );
  };
  const handleSendMessage = async ({
    toolCalls,
    urls,
    contextNotes: contextNotes2
  } = {}) => {
    if (!inputMessage && selectedImages.length === 0)
      return;
    const timestamp = formatDateTime(new Date());
    const content = [];
    if (inputMessage) {
      content.push({
        type: "text",
        text: inputMessage
      });
    }
    for (const image of selectedImages) {
      const imageData = await image.arrayBuffer();
      const base64Image = Buffer.from(imageData).toString("base64");
      content.push({
        type: "image_url",
        image_url: {
          url: `data:${image.type};base64,${base64Image}`
        }
      });
    }
    const notes = [...contextNotes2 || []];
    const activeNote = app2.workspace.getActiveFile();
    if (includeActiveNote && activeNote && !notes.some((note) => note.path === activeNote.path)) {
      notes.push(activeNote);
    }
    const userMessage = {
      message: inputMessage || "Image message",
      originalMessage: inputMessage,
      sender: USER_SENDER,
      isVisible: true,
      timestamp,
      content,
      context: {
        notes,
        urls: urls || []
      }
    };
    setInputMessage("");
    setSelectedImages([]);
    addMessage(userMessage);
    setLoading(true);
    setLoadingMessage(LOADING_MESSAGES.DEFAULT);
    const customPromptProcessor2 = CustomPromptProcessor.getInstance(app2.vault);
    let processedUserMessage = await customPromptProcessor2.processCustomPrompt(
      inputMessage || "",
      "",
      app2.workspace.getActiveFile()
    );
    const urlContextAddition = currentChain === "copilot_plus" /* COPILOT_PLUS_CHAIN */ ? await mention.processUrls(inputMessage || "") : { urlContext: "", imageUrls: [] };
    const noteContextAddition = await processContextNotes(customPromptProcessor2, fileParserManager);
    processedUserMessage = processedUserMessage + urlContextAddition.urlContext + noteContextAddition;
    let messageWithToolCalls = inputMessage;
    if (toolCalls) {
      messageWithToolCalls += " " + toolCalls.join("\n");
    }
    const promptMessageHidden = {
      message: processedUserMessage,
      originalMessage: messageWithToolCalls,
      sender: USER_SENDER,
      isVisible: false,
      timestamp,
      content,
      context: {
        notes,
        urls: currentChain === "copilot_plus" /* COPILOT_PLUS_CHAIN */ ? [...urls || [], ...urlContextAddition.imageUrls] : urls || []
      }
    };
    addMessage(promptMessageHidden);
    if (inputMessage) {
      updateUserMessageHistory(inputMessage);
      setHistoryIndex(-1);
    }
    await getAIResponse(
      promptMessageHidden,
      chainManager,
      addMessage,
      setCurrentAiMessage,
      setAbortController,
      { debug: settings.debug, updateLoadingMessage: setLoadingMessage }
    );
    setLoading(false);
    setLoadingMessage(LOADING_MESSAGES.DEFAULT);
  };
  const navigateHistory = (direction) => {
    const history = plugin.userMessageHistory;
    if (direction === "up" && historyIndex < history.length - 1) {
      setHistoryIndex(historyIndex + 1);
      return history[history.length - 1 - historyIndex - 1];
    } else if (direction === "down" && historyIndex > -1) {
      setHistoryIndex(historyIndex - 1);
      return historyIndex === 0 ? "" : history[history.length - 1 - historyIndex + 1];
    }
    return inputMessage;
  };
  const handleSaveAsNote = (0, import_react22.useCallback)(
    async (openNote = false) => {
      if (!app2) {
        console.error("App instance is not available.");
        return;
      }
      const visibleMessages = chatHistory.filter((message) => message.isVisible);
      if (visibleMessages.length === 0) {
        new import_obsidian37.Notice("No messages to save.");
        return;
      }
      const firstMessageEpoch = visibleMessages[0].timestamp?.epoch || Date.now();
      const chatContent = visibleMessages.map(
        (message) => `**${message.sender}**: ${message.message}
[Timestamp: ${message.timestamp?.display}]`
      ).join("\n\n");
      try {
        const folder = app2.vault.getAbstractFileByPath(settings.defaultSaveFolder);
        if (!folder) {
          await app2.vault.createFolder(settings.defaultSaveFolder);
        }
        const { fileName: timestampFileName } = formatDateTime(new Date(firstMessageEpoch));
        const firstUserMessage = visibleMessages.find((message) => message.sender === USER_SENDER);
        const firstTenWords = firstUserMessage ? firstUserMessage.message.split(/\s+/).slice(0, 10).join(" ").replace(/[\\/:*?"<>|]/g, "").trim() : "Untitled Chat";
        let customFileName = settings.defaultConversationNoteName || "{$date}_{$time}__{$topic}";
        customFileName = customFileName.replace("{$topic}", firstTenWords.slice(0, 100).replace(/\s+/g, "_")).replace("{$date}", timestampFileName.split("_")[0]).replace("{$time}", timestampFileName.split("_")[1]);
        const sanitizedFileName = customFileName.replace(/[\\/:*?"<>|]/g, "_");
        const noteFileName = `${settings.defaultSaveFolder}/${sanitizedFileName}.md`;
        const noteContentWithTimestamp = `---
epoch: ${firstMessageEpoch}
modelKey: ${currentModelKey}
tags:
  - ${settings.defaultConversationTag}
---

${chatContent}`;
        const existingFile = app2.vault.getAbstractFileByPath(noteFileName);
        if (existingFile instanceof import_obsidian37.TFile) {
          await app2.vault.modify(existingFile, noteContentWithTimestamp);
          new import_obsidian37.Notice(`Chat updated in existing note: ${noteFileName}`);
        } else {
          await app2.vault.create(noteFileName, noteContentWithTimestamp);
          new import_obsidian37.Notice(`Chat saved as new note: ${noteFileName}`);
        }
        if (openNote) {
          const file = app2.vault.getAbstractFileByPath(noteFileName);
          if (file instanceof import_obsidian37.TFile) {
            const leaf = app2.workspace.getLeaf();
            leaf.openFile(file);
          }
        }
      } catch (error) {
        console.error("Error saving chat as note:", err2String(error));
        new import_obsidian37.Notice("Failed to save chat as note. Check console for details.");
      }
    },
    [
      app2,
      chatHistory,
      currentModelKey,
      settings.defaultConversationTag,
      settings.defaultSaveFolder,
      settings.defaultConversationNoteName
    ]
  );
  const handleStopGenerating = (0, import_react22.useCallback)(
    (reason) => {
      if (abortController) {
        if (settings.debug) {
          console.log(`stopping generation..., reason: ${reason}`);
        }
        abortController.abort(reason);
        setLoading(false);
      }
    },
    [abortController, settings.debug]
  );
  const handleRegenerate = (0, import_react22.useCallback)(
    async (messageIndex) => {
      const lastUserMessageIndex = messageIndex - 1;
      if (lastUserMessageIndex < 0 || chatHistory[lastUserMessageIndex].sender !== USER_SENDER) {
        new import_obsidian37.Notice("Cannot regenerate the first message or a user message.");
        return;
      }
      const lastUserMessage = chatHistory[lastUserMessageIndex];
      const newChatHistory = chatHistory.slice(0, messageIndex);
      clearMessages();
      newChatHistory.forEach(addMessage);
      chainManager.memoryManager.clearChatMemory();
      for (let i3 = 0; i3 < newChatHistory.length; i3 += 2) {
        const userMsg = newChatHistory[i3];
        const aiMsg = newChatHistory[i3 + 1];
        if (userMsg && aiMsg) {
          await chainManager.memoryManager.getMemory().saveContext({ input: userMsg.message }, { output: aiMsg.message });
        }
      }
      setLoading(true);
      try {
        const regeneratedResponse = await chainManager.runChain(
          lastUserMessage,
          new AbortController(),
          setCurrentAiMessage,
          addMessage,
          { debug: settings.debug }
        );
        if (regeneratedResponse && settings.debug) {
          console.log("Message regenerated successfully");
        }
      } catch (error) {
        console.error("Error regenerating message:", error);
        new import_obsidian37.Notice("Failed to regenerate message. Please try again.");
      } finally {
        setLoading(false);
      }
    },
    [addMessage, chainManager, chatHistory, clearMessages, settings.debug]
  );
  const handleEdit = (0, import_react22.useCallback)(
    async (messageIndex, newMessage) => {
      const oldMessage = chatHistory[messageIndex].message;
      if (oldMessage === newMessage) {
        return;
      }
      const newChatHistory = [...chatHistory];
      for (let i3 = messageIndex; i3 < newChatHistory.length; i3++) {
        if (newChatHistory[i3].originalMessage === oldMessage) {
          newChatHistory[i3].message = newMessage;
          newChatHistory[i3].originalMessage = newMessage;
          newChatHistory[i3].context = { notes: [], urls: [] };
        }
      }
      clearMessages();
      newChatHistory.forEach(addMessage);
      await updateChatMemory(newChatHistory, chainManager.memoryManager);
      if (newChatHistory[messageIndex].sender === USER_SENDER && messageIndex < newChatHistory.length - 1) {
        handleRegenerate(messageIndex + 1);
      }
    },
    [addMessage, chainManager.memoryManager, chatHistory, clearMessages, handleRegenerate]
  );
  const createEffect = (eventType, promptFn) => {
    return () => {
      const debug4 = getSettings().debug;
      const handleSelection = async (event) => {
        const messageWithPrompt = await promptFn(
          event.detail.selectedText,
          event.detail.eventSubtype
        );
        const promptMessage = {
          message: messageWithPrompt,
          sender: USER_SENDER,
          isVisible: debug4,
          timestamp: formatDateTime(new Date())
        };
        if (debug4) {
          addMessage(promptMessage);
        }
        setLoading(true);
        await getAIResponse(
          promptMessage,
          chainManager,
          addMessage,
          setCurrentAiMessage,
          setAbortController,
          {
            debug: debug4,
            ignoreSystemMessage: true
          }
        );
        setLoading(false);
      };
      eventTarget?.addEventListener(eventType, handleSelection);
      return () => {
        eventTarget?.removeEventListener(eventType, handleSelection);
      };
    };
  };
  const customPromptProcessor = CustomPromptProcessor.getInstance(app2.vault);
  (0, import_react22.useEffect)(
    createEffect(COMMAND_IDS.APPLY_CUSTOM_PROMPT, async (selectedText, customPrompt) => {
      if (!customPrompt) {
        return selectedText;
      }
      return await customPromptProcessor.processCustomPrompt(
        customPrompt,
        selectedText,
        app2.workspace.getActiveFile() ?? void 0
      );
    }),
    []
  );
  (0, import_react22.useEffect)(
    createEffect(COMMAND_IDS.APPLY_ADHOC_PROMPT, async (selectedText, customPrompt) => {
      if (!customPrompt) {
        return selectedText;
      }
      return await customPromptProcessor.processCustomPrompt(
        customPrompt,
        selectedText,
        app2.workspace.getActiveFile()
      );
    }),
    []
  );
  (0, import_react22.useEffect)(() => {
    if (onSaveChat) {
      onSaveChat(handleSaveAsNote);
    }
  }, [onSaveChat, handleSaveAsNote]);
  const handleDelete = (0, import_react22.useCallback)(
    async (messageIndex) => {
      const newChatHistory = [...chatHistory];
      newChatHistory.splice(messageIndex, 1);
      clearMessages();
      newChatHistory.forEach(addMessage);
      await updateChatMemory(newChatHistory, chainManager.memoryManager);
    },
    [addMessage, chainManager.memoryManager, chatHistory, clearMessages]
  );
  const handleInsertToChat = (0, import_react22.useCallback)((prompt) => {
    setInputMessage((prev) => `${prev} ${prompt} `);
  }, []);
  const handleNewChat = (0, import_react22.useCallback)(async () => {
    handleStopGenerating("new-chat" /* NEW_CHAT */);
    if (settings.autosaveChat && chatHistory.length > 0) {
      await handleSaveAsNote(true);
    }
    clearMessages();
    chainManager.memoryManager.clearChatMemory();
    setCurrentAiMessage("");
    setContextNotes([]);
    setIncludeActiveNote(false);
  }, [
    handleStopGenerating,
    settings.autosaveChat,
    chatHistory.length,
    clearMessages,
    chainManager.memoryManager,
    handleSaveAsNote
  ]);
  return /* @__PURE__ */ import_react22.default.createElement("div", { className: "chat-container" }, /* @__PURE__ */ import_react22.default.createElement(
    ChatMessages_default,
    {
      chatHistory,
      currentAiMessage,
      loading,
      loadingMessage,
      app: app2,
      onRegenerate: handleRegenerate,
      onEdit: handleEdit,
      onDelete: handleDelete,
      onInsertToChat: handleInsertToChat,
      onReplaceChat: setInputMessage
    }
  ), /* @__PURE__ */ import_react22.default.createElement("div", { className: "bottom-container" }, /* @__PURE__ */ import_react22.default.createElement(ChatControls, { onNewChat: handleNewChat, onSaveAsNote: () => handleSaveAsNote(true) }), /* @__PURE__ */ import_react22.default.createElement(
    ChatInput_default,
    {
      ref: inputRef,
      inputMessage,
      setInputMessage,
      handleSendMessage,
      isGenerating: loading,
      onStopGenerating: () => handleStopGenerating("user-stopped" /* USER_STOPPED */),
      app: app2,
      navigateHistory,
      contextNotes,
      setContextNotes,
      includeActiveNote,
      setIncludeActiveNote,
      mention,
      selectedImages,
      onAddImage: (files) => setSelectedImages((prev) => [...prev, ...files]),
      setSelectedImages
    }
  )));
};
var Chat_default = Chat4;

// src/components/CopilotView.tsx
var import_obsidian38 = require("obsidian");
var React91 = __toESM(require_react());
var import_client5 = __toESM(require_client());
var CopilotView = class extends import_obsidian38.ItemView {
  constructor(leaf, plugin) {
    super(leaf);
    this.plugin = plugin;
    this.root = null;
    this.handleSaveAsNote = null;
    this.sharedState = plugin.sharedState;
    this.app = plugin.app;
    this.chainManager = plugin.chainManager;
    this.fileParserManager = plugin.fileParserManager;
    this.eventTarget = new EventTarget();
    this.plugin = plugin;
  }
  getViewType() {
    return CHAT_VIEWTYPE;
  }
  // Return an icon for this view
  getIcon() {
    return "message-square";
  }
  // Return a title for this view
  getTitle() {
    return "Copilot Chat";
  }
  getDisplayText() {
    return "Copilot";
  }
  async onOpen() {
    const root2 = (0, import_client5.createRoot)(this.containerEl.children[1]);
    const handleSaveAsNote = (saveFunction) => {
      this.handleSaveAsNote = saveFunction;
    };
    const updateUserMessageHistory = (newMessage) => {
      this.plugin.updateUserMessageHistory(newMessage);
    };
    root2.render(
      /* @__PURE__ */ React91.createElement(AppContext.Provider, { value: this.app }, /* @__PURE__ */ React91.createElement(EventTargetContext.Provider, { value: this.eventTarget }, /* @__PURE__ */ React91.createElement(React91.StrictMode, null, /* @__PURE__ */ React91.createElement(Provider2, { delayDuration: 0 }, /* @__PURE__ */ React91.createElement(
        Chat_default,
        {
          sharedState: this.sharedState,
          chainManager: this.chainManager,
          updateUserMessageHistory,
          fileParserManager: this.fileParserManager,
          plugin: this.plugin,
          onSaveChat: handleSaveAsNote
        }
      )))))
    );
  }
  async saveChat() {
    if (this.handleSaveAsNote) {
      await this.handleSaveAsNote();
    }
  }
  async onClose() {
    if (this.root) {
      this.root.unmount();
    }
  }
  updateView() {
    this.onOpen();
  }
};

// src/components/modals/LoadChatHistoryModal.tsx
var import_obsidian39 = require("obsidian");
var LoadChatHistoryModal = class extends import_obsidian39.FuzzySuggestModal {
  constructor(app2, chatFiles, onChooseFile) {
    super(app2);
    this.chatFiles = chatFiles;
    this.onChooseFile = onChooseFile;
  }
  getItems() {
    return this.chatFiles.sort((a3, b3) => {
      const getEpoch = (file) => {
        const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
        return frontmatter && frontmatter.epoch ? frontmatter.epoch : file.stat.ctime;
      };
      const epochA = getEpoch(a3);
      const epochB = getEpoch(b3);
      return epochB - epochA;
    });
  }
  getItemText(file) {
    const title = file.basename.replace(/\{\$date}|\d{8}/g, "").replace(/\{\$time}|\d{6}/g, "").replace(/[@_]/g, " ").replace(/\s+/g, " ").trim();
    let formattedDateTime;
    const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
    if (frontmatter && frontmatter.epoch) {
      formattedDateTime = formatDateTime(new Date(frontmatter.epoch));
    } else {
      formattedDateTime = formatDateTime(new Date(file.stat.ctime));
    }
    return `${title} - ${formattedDateTime.display}`;
  }
  onChooseItem(file, evt) {
    this.onChooseFile(file);
  }
};

// src/contextMenu.ts
function registerContextMenu(menu, editor, plugin) {
  CONTEXT_MENU_COMMANDS.filter((commandId) => isCommandEnabled(commandId)).forEach((commandId) => {
    menu.addItem((item) => {
      item.setTitle(`Copilot: ${COMMAND_NAMES[commandId]}`).onClick(async (e3) => {
        plugin.app.commands.executeCommandById(`copilot:${commandId}`);
      });
    });
  });
}

// src/settings/SettingsPage.tsx
var import_obsidian45 = require("obsidian");
var import_react40 = __toESM(require_react());
var import_client8 = __toESM(require_client());

// src/components/modals/ConfirmModal.tsx
var import_obsidian40 = require("obsidian");
var import_react23 = __toESM(require_react());
var import_client6 = __toESM(require_client());
function ConfirmModalContent({
  content,
  onConfirm,
  onCancel
}) {
  return /* @__PURE__ */ import_react23.default.createElement("div", { style: { display: "flex", flexDirection: "column", gap: "20px" } }, /* @__PURE__ */ import_react23.default.createElement("div", null, content), /* @__PURE__ */ import_react23.default.createElement("div", { style: { display: "flex", justifyContent: "flex-end", gap: "10px" } }, /* @__PURE__ */ import_react23.default.createElement("button", { onClick: onCancel }, "Cancel"), /* @__PURE__ */ import_react23.default.createElement(
    "button",
    {
      style: {
        backgroundColor: "var(--interactive-accent)",
        color: "var(--text-on-accent)",
        cursor: "pointer"
      },
      onClick: onConfirm
    },
    "Continue"
  )));
}
var ConfirmModal = class extends import_obsidian40.Modal {
  constructor(app2, onConfirm, content, title) {
    super(app2);
    this.onConfirm = onConfirm;
    this.content = content;
    this.setTitle(title);
  }
  onOpen() {
    const { contentEl } = this;
    this.root = (0, import_client6.createRoot)(contentEl);
    const handleConfirm = () => {
      this.onConfirm();
      this.close();
    };
    const handleCancel = () => {
      this.close();
    };
    this.root.render(
      /* @__PURE__ */ import_react23.default.createElement(
        ConfirmModalContent,
        {
          content: this.content,
          onConfirm: handleConfirm,
          onCancel: handleCancel
        }
      )
    );
  }
  onClose() {
    this.root.unmount();
  }
};

// src/components/modals/ResetSettingsConfirmModal.tsx
var ResetSettingsConfirmModal = class extends ConfirmModal {
  constructor(app2, onConfirm) {
    super(
      app2,
      onConfirm,
      "Resetting settings will clear all settings and restore the default values. You will lose any custom settings you have made including the API keys. Are you sure you want to continue?",
      "Reset Settings"
    );
  }
};

// src/components/ui/setting-tabs.tsx
var import_react24 = __toESM(require_react());
var TabItem = ({ tab, isSelected, onClick, isFirst, isLast }) => {
  return /* @__PURE__ */ import_react24.default.createElement(
    "div",
    {
      role: "tab",
      id: `tab-${tab.id}`,
      "aria-controls": `tabpanel-${tab.id}`,
      "aria-selected": isSelected,
      onClick,
      className: cn(
        "flex flex-row items-center",
        "h-8",
        "px-2 py-1",
        "gap-1.5",
        "cursor-pointer",
        "overflow-hidden",
        "whitespace-nowrap",
        "text-sm",
        "border border-border border-solid",
        "rounded-t-md rounded-b-[2px]",
        "bg-primary",
        "transition-all duration-300 ease-in-out",
        "hover:border-interactive-accent hover:border-b-0",
        isSelected && [
          "!bg-interactive-accent",
          "text-on-accent",
          "!px-3",
          "!max-w-full",
          "border-b-0",
          "transition-all duration-300 ease-in-out",
          "delay-200"
        ],
        "lg:max-w-32",
        "md:max-w-32"
      )
    },
    /* @__PURE__ */ import_react24.default.createElement(
      "div",
      {
        className: cn(
          "flex items-center justify-center",
          "w-4 h-4",
          "transition-transform duration-200 ease-in-out",
          isSelected ? "opacity-100 max-w-[16px] translate-x-0" : "opacity-0 max-w-0 -translate-x-4"
        )
      },
      tab.icon
    ),
    /* @__PURE__ */ import_react24.default.createElement(
      "span",
      {
        className: cn(
          "text-sm",
          "font-medium",
          "transition-all duration-200 ease-in-out",
          "overflow-hidden whitespace-nowrap",
          "opacity-100 max-w-[100px] translate-x-0"
        )
      },
      tab.label
    )
  );
};
var TabContent = ({ id, children, isSelected }) => {
  if (!isSelected)
    return null;
  return /* @__PURE__ */ import_react24.default.createElement(
    "div",
    {
      role: "tabpanel",
      id: `tabpanel-${id}`,
      "aria-labelledby": `tab-${id}`,
      className: cn(
        "pt-4",
        "transition-all duration-200 ease-in-out",
        isSelected ? "opacity-100 translate-y-0" : "opacity-0 translate-y-2"
      )
    },
    children
  );
};

// src/contexts/TabContext.tsx
var import_react25 = __toESM(require_react());
var TabContext = (0, import_react25.createContext)(void 0);
var TabProvider = ({ children }) => {
  const [selectedTab, setSelectedTab] = (0, import_react25.useState)("basic");
  const [modalContainer, setModalContainer] = (0, import_react25.useState)(null);
  const hasInitialized = (0, import_react25.useRef)(false);
  (0, import_react25.useEffect)(() => {
    if (!hasInitialized.current) {
      const modal = document.querySelector(".modal-container");
      setModalContainer(modal);
      hasInitialized.current = true;
    }
  }, []);
  return /* @__PURE__ */ import_react25.default.createElement(TabContext.Provider, { value: { selectedTab, setSelectedTab, modalContainer } }, children);
};
var useTab = () => {
  const context = (0, import_react25.useContext)(TabContext);
  if (context === void 0) {
    throw new Error("useTab must be used within a TabProvider");
  }
  return context;
};

// src/settings/v2/SettingsMainV2.tsx
var import_react39 = __toESM(require_react());

// src/settings/v2/components/AdvancedSettings.tsx
var import_react30 = __toESM(require_react());

// src/components/ui/setting-item.tsx
var import_react29 = __toESM(require_react());

// src/components/ui/input.tsx
var React95 = __toESM(require_react());
var Input = React95.forwardRef(
  ({ className, type, ...props }, ref) => {
    return /* @__PURE__ */ React95.createElement(
      "input",
      {
        type,
        className: cn(
          "!h-9 !min-w-[50px] !border border-solid !rounded-md !bg-transparent !px-3 !py-1 md:!text-base !text-sm !transition-colors",
          "focus-visible:!shadow-sm focus-visible:!outline-none focus-visible:!ring-1 focus-visible:!ring-ring",
          "placeholder:text-xs",
          // custom styles
          "flex w-full shadow-sm placeholder:text-muted disabled:cursor-not-allowed disabled:opacity-50",
          className
        ),
        ref,
        ...props
      }
    );
  }
);
Input.displayName = "Input";

// src/components/ui/password-input.tsx
var import_react26 = __toESM(require_react());
function PasswordInput({
  value,
  onChange,
  placeholder,
  disabled,
  className
}) {
  const [showPassword, setShowPassword] = (0, import_react26.useState)(false);
  const inputRef = (0, import_react26.useRef)(null);
  const isFirstLoad = (0, import_react26.useRef)(true);
  (0, import_react26.useEffect)(() => {
    const processValue = async () => {
      if (isFirstLoad.current && typeof value === "string" && value && inputRef.current) {
        try {
          const decrypted = await getDecryptedKey(value);
          inputRef.current.value = decrypted;
        } catch (error) {
          console.error("Failed to decrypt value:", error);
          inputRef.current.value = value;
        }
        isFirstLoad.current = false;
      }
    };
    processValue();
  }, [value]);
  return /* @__PURE__ */ import_react26.default.createElement("div", { className: cn("relative", className) }, /* @__PURE__ */ import_react26.default.createElement(
    Input,
    {
      ref: inputRef,
      type: showPassword ? "text" : "password",
      onChange: (e3) => onChange?.(e3.target.value),
      placeholder,
      disabled,
      className: cn("![padding-right:1.75rem] w-full")
    }
  ), /* @__PURE__ */ import_react26.default.createElement(
    "div",
    {
      onClick: () => !disabled && setShowPassword(!showPassword),
      className: cn(
        "absolute right-2 top-0 bottom-0 flex items-center justify-center",
        "cursor-pointer",
        disabled && "opacity-50 cursor-not-allowed"
      ),
      role: "button",
      "aria-label": showPassword ? "Hide password" : "Show password"
    },
    showPassword ? /* @__PURE__ */ import_react26.default.createElement(
      EyeOff,
      {
        className: cn(
          "h-3.5 w-3.5",
          "text-muted/60 hover:text-accent",
          "transition-colors duration-200"
        )
      }
    ) : /* @__PURE__ */ import_react26.default.createElement(
      Eye,
      {
        className: cn(
          "h-3.5 w-3.5",
          "text-muted/60 hover:text-accent",
          "transition-colors duration-200"
        )
      }
    )
  ));
}

// src/components/ui/textarea.tsx
var React97 = __toESM(require_react());
var Textarea = React97.forwardRef(
  ({ className, value, ...props }, ref) => {
    const textareaRef = React97.useRef(null);
    const adjustHeight = React97.useCallback(() => {
      const textarea = textareaRef.current;
      if (textarea) {
        textarea.style.height = "auto";
        const newHeight = Math.min(textarea.scrollHeight, 300);
        textarea.style.height = `${newHeight}px`;
      }
    }, []);
    React97.useLayoutEffect(() => {
      adjustHeight();
    }, [value, adjustHeight]);
    React97.useEffect(() => {
      adjustHeight();
      window.addEventListener("resize", adjustHeight);
      return () => window.removeEventListener("resize", adjustHeight);
    }, [adjustHeight]);
    const combinedRef = (node) => {
      textareaRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        ref.current = node;
      }
    };
    return /* @__PURE__ */ React97.createElement(
      "textarea",
      {
        className: cn(
          "border-solid resize-y min-w-fit overflow-auto",
          "flex min-h-[60px] max-h-[300px] w-full rounded-md border border-primary-alt bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
          className
        ),
        value,
        ref: combinedRef,
        onChange: (e3) => {
          adjustHeight();
          props.onChange?.(e3);
        },
        onInput: adjustHeight,
        onCompositionEnd: adjustHeight,
        onPaste: () => {
          setTimeout(adjustHeight, 0);
        },
        ...props
      }
    );
  }
);
Textarea.displayName = "Textarea";

// src/components/ui/dialog.tsx
var React108 = __toESM(require_react());

// node_modules/@radix-ui/react-dialog/dist/index.mjs
var React107 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers8(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React98 = __toESM(require_react(), 1);
function setRef10(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs10(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef10(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef10(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs8(...refs) {
  return React98.useCallback(composeRefs10(...refs), refs);
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var React101 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React100 = __toESM(require_react(), 1);
var ReactDOM12 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-slot/dist/index.mjs
var React99 = __toESM(require_react(), 1);
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var Slot9 = React99.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React99.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable9);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React99.Children.count(newElement) > 1)
          return React99.Children.only(null);
        return React99.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(SlotClone9, { ...slotProps, ref: forwardedRef, children: React99.isValidElement(newElement) ? React99.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(SlotClone9, { ...slotProps, ref: forwardedRef, children });
});
Slot9.displayName = "Slot";
var SlotClone9 = React99.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React99.isValidElement(children)) {
    const childrenRef = getElementRef10(children);
    return React99.cloneElement(children, {
      ...mergeProps9(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs10(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React99.Children.count(children) > 1 ? React99.Children.only(null) : null;
});
SlotClone9.displayName = "SlotClone";
var Slottable9 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(import_jsx_runtime41.Fragment, { children });
};
function isSlottable9(child) {
  return React99.isValidElement(child) && child.type === Slottable9;
}
function mergeProps9(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef10(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var NODES8 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive8 = NODES8.reduce((primitive, node) => {
  const Node3 = React100.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot9 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});
function dispatchDiscreteCustomEvent4(target, event) {
  if (target)
    ReactDOM12.flushSync(() => target.dispatchEvent(event));
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
"use client";
var DISMISSABLE_LAYER_NAME4 = "DismissableLayer";
var CONTEXT_UPDATE4 = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE4 = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE4 = "dismissableLayer.focusOutside";
var originalBodyPointerEvents4;
var DismissableLayerContext4 = React101.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer4 = React101.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = React101.useContext(DismissableLayerContext4);
    const [node, setNode] = React101.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = React101.useState({});
    const composedRefs = useComposedRefs8(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside4((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside4((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch)
        return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    React101.useEffect(() => {
      if (!node)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents4 = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate4();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents4;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    React101.useEffect(() => {
      return () => {
        if (!node)
          return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate4();
      };
    }, [node, context]);
    React101.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE4, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE4, handleUpdate);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
      Primitive8.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers8(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers8(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers8(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer4.displayName = DISMISSABLE_LAYER_NAME4;
var BRANCH_NAME4 = "DismissableLayerBranch";
var DismissableLayerBranch4 = React101.forwardRef((props, forwardedRef) => {
  const context = React101.useContext(DismissableLayerContext4);
  const ref = React101.useRef(null);
  const composedRefs = useComposedRefs8(forwardedRef, ref);
  React101.useEffect(() => {
    const node = ref.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Primitive8.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch4.displayName = BRANCH_NAME4;
function usePointerDownOutside4(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
  const isPointerInsideReactTreeRef = React101.useRef(false);
  const handleClickRef = React101.useRef(() => {
  });
  React101.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent4(
            POINTER_DOWN_OUTSIDE4,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside4(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef(onFocusOutside);
  const isFocusInsideReactTreeRef = React101.useRef(false);
  React101.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent4(FOCUS_OUTSIDE4, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate4() {
  const event = new CustomEvent(CONTEXT_UPDATE4);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent4(name, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });
  if (handler)
    target.addEventListener(name, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent4(target, event);
  } else {
    target.dispatchEvent(event);
  }
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-focus-scope/dist/index.mjs
var React102 = __toESM(require_react(), 1);
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
"use client";
var AUTOFOCUS_ON_MOUNT3 = "focusScope.autoFocusOnMount";
var AUTOFOCUS_ON_UNMOUNT3 = "focusScope.autoFocusOnUnmount";
var EVENT_OPTIONS4 = { bubbles: false, cancelable: true };
var FOCUS_SCOPE_NAME3 = "FocusScope";
var FocusScope3 = React102.forwardRef((props, forwardedRef) => {
  const {
    loop = false,
    trapped = false,
    onMountAutoFocus: onMountAutoFocusProp,
    onUnmountAutoFocus: onUnmountAutoFocusProp,
    ...scopeProps
  } = props;
  const [container, setContainer] = React102.useState(null);
  const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
  const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
  const lastFocusedElementRef = React102.useRef(null);
  const composedRefs = useComposedRefs8(forwardedRef, (node) => setContainer(node));
  const focusScope = React102.useRef({
    paused: false,
    pause() {
      this.paused = true;
    },
    resume() {
      this.paused = false;
    }
  }).current;
  React102.useEffect(() => {
    if (trapped) {
      let handleFocusIn2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const target = event.target;
        if (container.contains(target)) {
          lastFocusedElementRef.current = target;
        } else {
          focus3(lastFocusedElementRef.current, { select: true });
        }
      }, handleFocusOut2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget === null)
          return;
        if (!container.contains(relatedTarget)) {
          focus3(lastFocusedElementRef.current, { select: true });
        }
      }, handleMutations2 = function(mutations) {
        const focusedElement = document.activeElement;
        if (focusedElement !== document.body)
          return;
        for (const mutation of mutations) {
          if (mutation.removedNodes.length > 0)
            focus3(container);
        }
      };
      var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
      document.addEventListener("focusin", handleFocusIn2);
      document.addEventListener("focusout", handleFocusOut2);
      const mutationObserver = new MutationObserver(handleMutations2);
      if (container)
        mutationObserver.observe(container, { childList: true, subtree: true });
      return () => {
        document.removeEventListener("focusin", handleFocusIn2);
        document.removeEventListener("focusout", handleFocusOut2);
        mutationObserver.disconnect();
      };
    }
  }, [trapped, container, focusScope.paused]);
  React102.useEffect(() => {
    if (container) {
      focusScopesStack3.add(focusScope);
      const previouslyFocusedElement = document.activeElement;
      const hasFocusedCandidate = container.contains(previouslyFocusedElement);
      if (!hasFocusedCandidate) {
        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT3, EVENT_OPTIONS4);
        container.addEventListener(AUTOFOCUS_ON_MOUNT3, onMountAutoFocus);
        container.dispatchEvent(mountEvent);
        if (!mountEvent.defaultPrevented) {
          focusFirst5(removeLinks3(getTabbableCandidates3(container)), { select: true });
          if (document.activeElement === previouslyFocusedElement) {
            focus3(container);
          }
        }
      }
      return () => {
        container.removeEventListener(AUTOFOCUS_ON_MOUNT3, onMountAutoFocus);
        setTimeout(() => {
          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT3, EVENT_OPTIONS4);
          container.addEventListener(AUTOFOCUS_ON_UNMOUNT3, onUnmountAutoFocus);
          container.dispatchEvent(unmountEvent);
          if (!unmountEvent.defaultPrevented) {
            focus3(previouslyFocusedElement ?? document.body, { select: true });
          }
          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT3, onUnmountAutoFocus);
          focusScopesStack3.remove(focusScope);
        }, 0);
      };
    }
  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
  const handleKeyDown = React102.useCallback(
    (event) => {
      if (!loop && !trapped)
        return;
      if (focusScope.paused)
        return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container2 = event.currentTarget;
        const [first, last] = getTabbableEdges3(container2);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container2)
            event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop)
              focus3(first, { select: true });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop)
              focus3(last, { select: true });
          }
        }
      }
    },
    [loop, trapped, focusScope.paused]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Primitive8.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
});
FocusScope3.displayName = FOCUS_SCOPE_NAME3;
function focusFirst5(candidates, { select = false } = {}) {
  const previouslyFocusedElement = document.activeElement;
  for (const candidate of candidates) {
    focus3(candidate, { select });
    if (document.activeElement !== previouslyFocusedElement)
      return;
  }
}
function getTabbableEdges3(container) {
  const candidates = getTabbableCandidates3(container);
  const first = findVisible3(candidates, container);
  const last = findVisible3(candidates.reverse(), container);
  return [first, last];
}
function getTabbableCandidates3(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput)
        return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode())
    nodes.push(walker.currentNode);
  return nodes;
}
function findVisible3(elements, container) {
  for (const element of elements) {
    if (!isHidden3(element, { upTo: container }))
      return element;
  }
}
function isHidden3(node, { upTo }) {
  if (getComputedStyle(node).visibility === "hidden")
    return true;
  while (node) {
    if (upTo !== void 0 && node === upTo)
      return false;
    if (getComputedStyle(node).display === "none")
      return true;
    node = node.parentElement;
  }
  return false;
}
function isSelectableInput3(element) {
  return element instanceof HTMLInputElement && "select" in element;
}
function focus3(element, { select = false } = {}) {
  if (element && element.focus) {
    const previouslyFocusedElement = document.activeElement;
    element.focus({ preventScroll: true });
    if (element !== previouslyFocusedElement && isSelectableInput3(element) && select)
      element.select();
  }
}
var focusScopesStack3 = createFocusScopesStack3();
function createFocusScopesStack3() {
  let stack = [];
  return {
    add(focusScope) {
      const activeFocusScope = stack[0];
      if (focusScope !== activeFocusScope) {
        activeFocusScope?.pause();
      }
      stack = arrayRemove3(stack, focusScope);
      stack.unshift(focusScope);
    },
    remove(focusScope) {
      stack = arrayRemove3(stack, focusScope);
      stack[0]?.resume();
    }
  };
}
function arrayRemove3(array, item) {
  const updatedArray = [...array];
  const index2 = updatedArray.indexOf(item);
  if (index2 !== -1) {
    updatedArray.splice(index2, 1);
  }
  return updatedArray;
}
function removeLinks3(items) {
  return items.filter((item) => item.tagName !== "A");
}

// node_modules/@radix-ui/react-dialog/node_modules/@radix-ui/react-portal/dist/index.mjs
var React103 = __toESM(require_react(), 1);
var import_react_dom7 = __toESM(require_react_dom(), 1);
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
"use client";
var PORTAL_NAME8 = "Portal";
var Portal7 = React103.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = React103.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? import_react_dom7.default.createPortal(/* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Primitive8.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal7.displayName = PORTAL_NAME8;

// node_modules/react-remove-scroll/dist/es2015/Combination.js
var React106 = __toESM(require_react());

// node_modules/react-remove-scroll/dist/es2015/UI.js
var React104 = __toESM(require_react());

// node_modules/react-remove-scroll/dist/es2015/medium.js
var effectCar3 = createSidecarMedium();

// node_modules/react-remove-scroll/dist/es2015/UI.js
var nothing3 = function() {
  return;
};
var RemoveScroll3 = React104.forwardRef(function(props, parentRef) {
  var ref = React104.useRef(null);
  var _a5 = React104.useState({
    onScrollCapture: nothing3,
    onWheelCapture: nothing3,
    onTouchMoveCapture: nothing3
  }), callbacks = _a5[0], setCallbacks = _a5[1];
  var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest5(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]);
  var SideCar2 = sideCar;
  var containerRef = useMergeRefs([ref, parentRef]);
  var containerProps = __assign5(__assign5({}, rest), callbacks);
  return React104.createElement(
    React104.Fragment,
    null,
    enabled && React104.createElement(SideCar2, { sideCar: effectCar3, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode }),
    forwardProps ? React104.cloneElement(React104.Children.only(children), __assign5(__assign5({}, containerProps), { ref: containerRef })) : React104.createElement(Container, __assign5({}, containerProps, { className, ref: containerRef }), children)
  );
});
RemoveScroll3.defaultProps = {
  enabled: true,
  removeScrollBar: true,
  inert: false
};
RemoveScroll3.classNames = {
  fullWidth: fullWidthClassName,
  zeroRight: zeroRightClassName
};

// node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var React105 = __toESM(require_react());

// node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js
var passiveSupported3 = false;
if (typeof window !== "undefined") {
  try {
    options = Object.defineProperty({}, "passive", {
      get: function() {
        passiveSupported3 = true;
        return true;
      }
    });
    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (err) {
    passiveSupported3 = false;
  }
}
var options;
var nonPassive3 = passiveSupported3 ? { passive: false } : false;

// node_modules/react-remove-scroll/dist/es2015/handleScroll.js
var alwaysContainsScroll3 = function(node) {
  return node.tagName === "TEXTAREA";
};
var elementCanBeScrolled3 = function(node, overflow) {
  if (!(node instanceof Element)) {
    return false;
  }
  var styles2 = window.getComputedStyle(node);
  return (
    // not-not-scrollable
    styles2[overflow] !== "hidden" && // contains scroll inside self
    !(styles2.overflowY === styles2.overflowX && !alwaysContainsScroll3(node) && styles2[overflow] === "visible")
  );
};
var elementCouldBeVScrolled3 = function(node) {
  return elementCanBeScrolled3(node, "overflowY");
};
var elementCouldBeHScrolled3 = function(node) {
  return elementCanBeScrolled3(node, "overflowX");
};
var locationCouldBeScrolled3 = function(axis, node) {
  var ownerDocument = node.ownerDocument;
  var current = node;
  do {
    if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) {
      current = current.host;
    }
    var isScrollable = elementCouldBeScrolled3(axis, current);
    if (isScrollable) {
      var _a5 = getScrollVariables3(axis, current), scrollHeight = _a5[1], clientHeight = _a5[2];
      if (scrollHeight > clientHeight) {
        return true;
      }
    }
    current = current.parentNode;
  } while (current && current !== ownerDocument.body);
  return false;
};
var getVScrollVariables3 = function(_a5) {
  var scrollTop = _a5.scrollTop, scrollHeight = _a5.scrollHeight, clientHeight = _a5.clientHeight;
  return [
    scrollTop,
    scrollHeight,
    clientHeight
  ];
};
var getHScrollVariables3 = function(_a5) {
  var scrollLeft = _a5.scrollLeft, scrollWidth = _a5.scrollWidth, clientWidth = _a5.clientWidth;
  return [
    scrollLeft,
    scrollWidth,
    clientWidth
  ];
};
var elementCouldBeScrolled3 = function(axis, node) {
  return axis === "v" ? elementCouldBeVScrolled3(node) : elementCouldBeHScrolled3(node);
};
var getScrollVariables3 = function(axis, node) {
  return axis === "v" ? getVScrollVariables3(node) : getHScrollVariables3(node);
};
var getDirectionFactor3 = function(axis, direction) {
  return axis === "h" && direction === "rtl" ? -1 : 1;
};
var handleScroll3 = function(axis, endTarget, event, sourceDelta, noOverscroll) {
  var directionFactor = getDirectionFactor3(axis, window.getComputedStyle(endTarget).direction);
  var delta = directionFactor * sourceDelta;
  var target = event.target;
  var targetInLock = endTarget.contains(target);
  var shouldCancelScroll = false;
  var isDeltaPositive = delta > 0;
  var availableScroll = 0;
  var availableScrollTop = 0;
  do {
    var _a5 = getScrollVariables3(axis, target), position = _a5[0], scroll_1 = _a5[1], capacity = _a5[2];
    var elementScroll = scroll_1 - capacity - directionFactor * position;
    if (position || elementScroll) {
      if (elementCouldBeScrolled3(axis, target)) {
        availableScroll += elementScroll;
        availableScrollTop += position;
      }
    }
    if (target instanceof ShadowRoot) {
      target = target.host;
    } else {
      target = target.parentNode;
    }
  } while (
    // portaled content
    !targetInLock && target !== document.body || // self content
    targetInLock && (endTarget.contains(target) || endTarget === target)
  );
  if (isDeltaPositive && (noOverscroll && Math.abs(availableScroll) < 1 || !noOverscroll && delta > availableScroll)) {
    shouldCancelScroll = true;
  } else if (!isDeltaPositive && (noOverscroll && Math.abs(availableScrollTop) < 1 || !noOverscroll && -delta > availableScrollTop)) {
    shouldCancelScroll = true;
  }
  return shouldCancelScroll;
};

// node_modules/react-remove-scroll/dist/es2015/SideEffect.js
var getTouchXY3 = function(event) {
  return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
};
var getDeltaXY3 = function(event) {
  return [event.deltaX, event.deltaY];
};
var extractRef3 = function(ref) {
  return ref && "current" in ref ? ref.current : ref;
};
var deltaCompare3 = function(x2, y2) {
  return x2[0] === y2[0] && x2[1] === y2[1];
};
var generateStyle3 = function(id) {
  return "\n  .block-interactivity-".concat(id, " {pointer-events: none;}\n  .allow-interactivity-").concat(id, " {pointer-events: all;}\n");
};
var idCounter3 = 0;
var lockStack3 = [];
function RemoveScrollSideCar3(props) {
  var shouldPreventQueue = React105.useRef([]);
  var touchStartRef = React105.useRef([0, 0]);
  var activeAxis = React105.useRef();
  var id = React105.useState(idCounter3++)[0];
  var Style2 = React105.useState(styleSingleton)[0];
  var lastProps = React105.useRef(props);
  React105.useEffect(function() {
    lastProps.current = props;
  }, [props]);
  React105.useEffect(function() {
    if (props.inert) {
      document.body.classList.add("block-interactivity-".concat(id));
      var allow_1 = __spreadArray4([props.lockRef.current], (props.shards || []).map(extractRef3), true).filter(Boolean);
      allow_1.forEach(function(el) {
        return el.classList.add("allow-interactivity-".concat(id));
      });
      return function() {
        document.body.classList.remove("block-interactivity-".concat(id));
        allow_1.forEach(function(el) {
          return el.classList.remove("allow-interactivity-".concat(id));
        });
      };
    }
    return;
  }, [props.inert, props.lockRef.current, props.shards]);
  var shouldCancelEvent = React105.useCallback(function(event, parent) {
    if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) {
      return !lastProps.current.allowPinchZoom;
    }
    var touch = getTouchXY3(event);
    var touchStart = touchStartRef.current;
    var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0];
    var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1];
    var currentAxis;
    var target = event.target;
    var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v";
    if ("touches" in event && moveDirection === "h" && target.type === "range") {
      return false;
    }
    var canBeScrolledInMainDirection = locationCouldBeScrolled3(moveDirection, target);
    if (!canBeScrolledInMainDirection) {
      return true;
    }
    if (canBeScrolledInMainDirection) {
      currentAxis = moveDirection;
    } else {
      currentAxis = moveDirection === "v" ? "h" : "v";
      canBeScrolledInMainDirection = locationCouldBeScrolled3(moveDirection, target);
    }
    if (!canBeScrolledInMainDirection) {
      return false;
    }
    if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) {
      activeAxis.current = currentAxis;
    }
    if (!currentAxis) {
      return true;
    }
    var cancelingAxis = activeAxis.current || currentAxis;
    return handleScroll3(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true);
  }, []);
  var shouldPrevent = React105.useCallback(function(_event) {
    var event = _event;
    if (!lockStack3.length || lockStack3[lockStack3.length - 1] !== Style2) {
      return;
    }
    var delta = "deltaY" in event ? getDeltaXY3(event) : getTouchXY3(event);
    var sourceEvent = shouldPreventQueue.current.filter(function(e3) {
      return e3.name === event.type && (e3.target === event.target || event.target === e3.shadowParent) && deltaCompare3(e3.delta, delta);
    })[0];
    if (sourceEvent && sourceEvent.should) {
      if (event.cancelable) {
        event.preventDefault();
      }
      return;
    }
    if (!sourceEvent) {
      var shardNodes = (lastProps.current.shards || []).map(extractRef3).filter(Boolean).filter(function(node) {
        return node.contains(event.target);
      });
      var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
      if (shouldStop) {
        if (event.cancelable) {
          event.preventDefault();
        }
      }
    }
  }, []);
  var shouldCancel = React105.useCallback(function(name, delta, target, should) {
    var event = { name, delta, target, should, shadowParent: getOutermostShadowParent3(target) };
    shouldPreventQueue.current.push(event);
    setTimeout(function() {
      shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e3) {
        return e3 !== event;
      });
    }, 1);
  }, []);
  var scrollTouchStart = React105.useCallback(function(event) {
    touchStartRef.current = getTouchXY3(event);
    activeAxis.current = void 0;
  }, []);
  var scrollWheel = React105.useCallback(function(event) {
    shouldCancel(event.type, getDeltaXY3(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  var scrollTouchMove = React105.useCallback(function(event) {
    shouldCancel(event.type, getTouchXY3(event), event.target, shouldCancelEvent(event, props.lockRef.current));
  }, []);
  React105.useEffect(function() {
    lockStack3.push(Style2);
    props.setCallbacks({
      onScrollCapture: scrollWheel,
      onWheelCapture: scrollWheel,
      onTouchMoveCapture: scrollTouchMove
    });
    document.addEventListener("wheel", shouldPrevent, nonPassive3);
    document.addEventListener("touchmove", shouldPrevent, nonPassive3);
    document.addEventListener("touchstart", scrollTouchStart, nonPassive3);
    return function() {
      lockStack3 = lockStack3.filter(function(inst) {
        return inst !== Style2;
      });
      document.removeEventListener("wheel", shouldPrevent, nonPassive3);
      document.removeEventListener("touchmove", shouldPrevent, nonPassive3);
      document.removeEventListener("touchstart", scrollTouchStart, nonPassive3);
    };
  }, []);
  var removeScrollBar = props.removeScrollBar, inert = props.inert;
  return React105.createElement(
    React105.Fragment,
    null,
    inert ? React105.createElement(Style2, { styles: generateStyle3(id) }) : null,
    removeScrollBar ? React105.createElement(RemoveScrollBar, { gapMode: props.gapMode }) : null
  );
}
function getOutermostShadowParent3(node) {
  var shadowParent = null;
  while (node !== null) {
    if (node instanceof ShadowRoot) {
      shadowParent = node.host;
      node = node.host;
    }
    node = node.parentNode;
  }
  return shadowParent;
}

// node_modules/react-remove-scroll/dist/es2015/sidecar.js
var sidecar_default3 = exportSidecar(effectCar3, RemoveScrollSideCar3);

// node_modules/react-remove-scroll/dist/es2015/Combination.js
var ReactRemoveScroll3 = React106.forwardRef(function(props, ref) {
  return React106.createElement(RemoveScroll3, __assign5({}, props, { ref, sideCar: sidecar_default3 }));
});
ReactRemoveScroll3.classNames = RemoveScroll3.classNames;
var Combination_default3 = ReactRemoveScroll3;

// node_modules/@radix-ui/react-dialog/dist/index.mjs
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
"use client";
var DIALOG_NAME = "Dialog";
var [createDialogContext, createDialogScope] = createContextScope(DIALOG_NAME);
var [DialogProvider, useDialogContext] = createDialogContext(DIALOG_NAME);
var Dialog = (props) => {
  const {
    __scopeDialog,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    modal = true
  } = props;
  const triggerRef = React107.useRef(null);
  const contentRef = React107.useRef(null);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
    DialogProvider,
    {
      scope: __scopeDialog,
      triggerRef,
      contentRef,
      contentId: useId(),
      titleId: useId(),
      descriptionId: useId(),
      open,
      onOpenChange: setOpen,
      onOpenToggle: React107.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]),
      modal,
      children
    }
  );
};
Dialog.displayName = DIALOG_NAME;
var TRIGGER_NAME5 = "DialogTrigger";
var DialogTrigger = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...triggerProps } = props;
    const context = useDialogContext(TRIGGER_NAME5, __scopeDialog);
    const composedTriggerRef = useComposedRefs8(forwardedRef, context.triggerRef);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      Primitive8.button,
      {
        type: "button",
        "aria-haspopup": "dialog",
        "aria-expanded": context.open,
        "aria-controls": context.contentId,
        "data-state": getState3(context.open),
        ...triggerProps,
        ref: composedTriggerRef,
        onClick: composeEventHandlers8(props.onClick, context.onOpenToggle)
      }
    );
  }
);
DialogTrigger.displayName = TRIGGER_NAME5;
var PORTAL_NAME9 = "DialogPortal";
var [PortalProvider4, usePortalContext4] = createDialogContext(PORTAL_NAME9, {
  forceMount: void 0
});
var DialogPortal = (props) => {
  const { __scopeDialog, forceMount, children, container } = props;
  const context = useDialogContext(PORTAL_NAME9, __scopeDialog);
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(PortalProvider4, { scope: __scopeDialog, forceMount, children: React107.Children.map(children, (child) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Portal7, { asChild: true, container, children: child }) })) });
};
DialogPortal.displayName = PORTAL_NAME9;
var OVERLAY_NAME = "DialogOverlay";
var DialogOverlay = React107.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext4(OVERLAY_NAME, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...overlayProps } = props;
    const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog);
    return context.modal ? /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Presence, { present: forceMount || context.open, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(DialogOverlayImpl, { ...overlayProps, ref: forwardedRef }) }) : null;
  }
);
DialogOverlay.displayName = OVERLAY_NAME;
var DialogOverlayImpl = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...overlayProps } = props;
    const context = useDialogContext(OVERLAY_NAME, __scopeDialog);
    return (
      // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll`
      // ie. when `Overlay` and `Content` are siblings
      /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Combination_default3, { as: Slot9, allowPinchZoom: true, shards: [context.contentRef], children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
        Primitive8.div,
        {
          "data-state": getState3(context.open),
          ...overlayProps,
          ref: forwardedRef,
          style: { pointerEvents: "auto", ...overlayProps.style }
        }
      ) })
    );
  }
);
var CONTENT_NAME9 = "DialogContent";
var DialogContent = React107.forwardRef(
  (props, forwardedRef) => {
    const portalContext = usePortalContext4(CONTENT_NAME9, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = useDialogContext(CONTENT_NAME9, props.__scopeDialog);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Presence, { present: forceMount || context.open, children: context.modal ? /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(DialogContentModal, { ...contentProps, ref: forwardedRef }) : /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(DialogContentNonModal, { ...contentProps, ref: forwardedRef }) });
  }
);
DialogContent.displayName = CONTENT_NAME9;
var DialogContentModal = React107.forwardRef(
  (props, forwardedRef) => {
    const context = useDialogContext(CONTENT_NAME9, props.__scopeDialog);
    const contentRef = React107.useRef(null);
    const composedRefs = useComposedRefs8(forwardedRef, context.contentRef, contentRef);
    React107.useEffect(() => {
      const content = contentRef.current;
      if (content)
        return hideOthers(content);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      DialogContentImpl,
      {
        ...props,
        ref: composedRefs,
        trapFocus: context.open,
        disableOutsidePointerEvents: true,
        onCloseAutoFocus: composeEventHandlers8(props.onCloseAutoFocus, (event) => {
          event.preventDefault();
          context.triggerRef.current?.focus();
        }),
        onPointerDownOutside: composeEventHandlers8(props.onPointerDownOutside, (event) => {
          const originalEvent = event.detail.originalEvent;
          const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
          const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
          if (isRightClick)
            event.preventDefault();
        }),
        onFocusOutside: composeEventHandlers8(
          props.onFocusOutside,
          (event) => event.preventDefault()
        )
      }
    );
  }
);
var DialogContentNonModal = React107.forwardRef(
  (props, forwardedRef) => {
    const context = useDialogContext(CONTENT_NAME9, props.__scopeDialog);
    const hasInteractedOutsideRef = React107.useRef(false);
    const hasPointerDownOutsideRef = React107.useRef(false);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      DialogContentImpl,
      {
        ...props,
        ref: forwardedRef,
        trapFocus: false,
        disableOutsidePointerEvents: false,
        onCloseAutoFocus: (event) => {
          props.onCloseAutoFocus?.(event);
          if (!event.defaultPrevented) {
            if (!hasInteractedOutsideRef.current)
              context.triggerRef.current?.focus();
            event.preventDefault();
          }
          hasInteractedOutsideRef.current = false;
          hasPointerDownOutsideRef.current = false;
        },
        onInteractOutside: (event) => {
          props.onInteractOutside?.(event);
          if (!event.defaultPrevented) {
            hasInteractedOutsideRef.current = true;
            if (event.detail.originalEvent.type === "pointerdown") {
              hasPointerDownOutsideRef.current = true;
            }
          }
          const target = event.target;
          const targetIsTrigger = context.triggerRef.current?.contains(target);
          if (targetIsTrigger)
            event.preventDefault();
          if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) {
            event.preventDefault();
          }
        }
      }
    );
  }
);
var DialogContentImpl = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props;
    const context = useDialogContext(CONTENT_NAME9, __scopeDialog);
    const contentRef = React107.useRef(null);
    const composedRefs = useComposedRefs8(forwardedRef, contentRef);
    useFocusGuards();
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(import_jsx_runtime46.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
        FocusScope3,
        {
          asChild: true,
          loop: true,
          trapped: trapFocus,
          onMountAutoFocus: onOpenAutoFocus,
          onUnmountAutoFocus: onCloseAutoFocus,
          children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            DismissableLayer4,
            {
              role: "dialog",
              id: context.contentId,
              "aria-describedby": context.descriptionId,
              "aria-labelledby": context.titleId,
              "data-state": getState3(context.open),
              ...contentProps,
              ref: composedRefs,
              onDismiss: () => context.onOpenChange(false)
            }
          )
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(import_jsx_runtime46.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(TitleWarning, { titleId: context.titleId }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(DescriptionWarning, { contentRef, descriptionId: context.descriptionId })
      ] })
    ] });
  }
);
var TITLE_NAME = "DialogTitle";
var DialogTitle = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...titleProps } = props;
    const context = useDialogContext(TITLE_NAME, __scopeDialog);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Primitive8.h2, { id: context.titleId, ...titleProps, ref: forwardedRef });
  }
);
DialogTitle.displayName = TITLE_NAME;
var DESCRIPTION_NAME = "DialogDescription";
var DialogDescription = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...descriptionProps } = props;
    const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Primitive8.p, { id: context.descriptionId, ...descriptionProps, ref: forwardedRef });
  }
);
DialogDescription.displayName = DESCRIPTION_NAME;
var CLOSE_NAME2 = "DialogClose";
var DialogClose = React107.forwardRef(
  (props, forwardedRef) => {
    const { __scopeDialog, ...closeProps } = props;
    const context = useDialogContext(CLOSE_NAME2, __scopeDialog);
    return /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
      Primitive8.button,
      {
        type: "button",
        ...closeProps,
        ref: forwardedRef,
        onClick: composeEventHandlers8(props.onClick, () => context.onOpenChange(false))
      }
    );
  }
);
DialogClose.displayName = CLOSE_NAME2;
function getState3(open) {
  return open ? "open" : "closed";
}
var TITLE_WARNING_NAME = "DialogTitleWarning";
var [WarningProvider, useWarningContext] = createContext22(TITLE_WARNING_NAME, {
  contentName: CONTENT_NAME9,
  titleName: TITLE_NAME,
  docsSlug: "dialog"
});
var TitleWarning = ({ titleId }) => {
  const titleWarningContext = useWarningContext(TITLE_WARNING_NAME);
  const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`;
  React107.useEffect(() => {
    if (titleId) {
      const hasTitle = document.getElementById(titleId);
      if (!hasTitle)
        console.error(MESSAGE);
    }
  }, [MESSAGE, titleId]);
  return null;
};
var DESCRIPTION_WARNING_NAME = "DialogDescriptionWarning";
var DescriptionWarning = ({ contentRef, descriptionId }) => {
  const descriptionWarningContext = useWarningContext(DESCRIPTION_WARNING_NAME);
  const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`;
  React107.useEffect(() => {
    const describedById = contentRef.current?.getAttribute("aria-describedby");
    if (descriptionId && describedById) {
      const hasDescription = document.getElementById(descriptionId);
      if (!hasDescription)
        console.warn(MESSAGE);
    }
  }, [MESSAGE, contentRef, descriptionId]);
  return null;
};
var Root10 = Dialog;
var Trigger4 = DialogTrigger;
var Portal8 = DialogPortal;
var Overlay = DialogOverlay;
var Content5 = DialogContent;
var Title = DialogTitle;
var Description = DialogDescription;
var Close = DialogClose;

// src/components/ui/dialog.tsx
var Dialog2 = Root10;
var DialogTrigger2 = Trigger4;
var DialogPortal2 = Portal8;
var DialogOverlay2 = React108.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React108.createElement(
  Overlay,
  {
    ref,
    className: cn(
      "fixed inset-0 z-modal data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      "bg-overlay/50",
      // custom style
      className
    ),
    ...props
  }
));
DialogOverlay2.displayName = Overlay.displayName;
var DialogContent2 = React108.forwardRef(({ className, children, container, ...props }, ref) => /* @__PURE__ */ React108.createElement(DialogPortal2, { container }, /* @__PURE__ */ React108.createElement(DialogOverlay2, null), /* @__PURE__ */ React108.createElement(
  Content5,
  {
    ref,
    className: cn(
      "fixed left-[50%] top-[50%] z-modal grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-primary p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
      className
    ),
    ...props
  },
  children,
  /* @__PURE__ */ React108.createElement(Close, { className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-ring transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-interactive-accent data-[state=open]:text-muted" }, /* @__PURE__ */ React108.createElement(X, { className: "h-4 w-4" }), /* @__PURE__ */ React108.createElement("span", { className: "sr-only" }, "Close"))
)));
DialogContent2.displayName = Content5.displayName;
var DialogHeader = ({ className, ...props }) => /* @__PURE__ */ React108.createElement("div", { className: cn("flex flex-col space-y-1.5 text-center sm:text-left", className), ...props });
DialogHeader.displayName = "DialogHeader";
var DialogFooter = ({ className, ...props }) => /* @__PURE__ */ React108.createElement(
  "div",
  {
    className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className),
    ...props
  }
);
DialogFooter.displayName = "DialogFooter";
var DialogTitle2 = React108.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React108.createElement(
  Title,
  {
    ref,
    className: cn("text-lg font-semibold leading-none tracking-tight", className),
    ...props
  }
));
DialogTitle2.displayName = Title.displayName;
var DialogDescription2 = React108.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React108.createElement(
  Description,
  {
    ref,
    className: cn("text-sm text-muted", className),
    ...props
  }
));
DialogDescription2.displayName = Description.displayName;

// src/components/ui/setting-slider.tsx
var import_react28 = __toESM(require_react());

// src/components/ui/slider.tsx
var React114 = __toESM(require_react());

// node_modules/@radix-ui/react-slider/dist/index.mjs
var React113 = __toESM(require_react(), 1);

// node_modules/@radix-ui/number/dist/index.mjs
function clamp2(value, [min2, max2]) {
  return Math.min(max2, Math.max(min2, value));
}

// node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers9(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-use-previous/dist/index.mjs
var React109 = __toESM(require_react(), 1);
function usePrevious(value) {
  const ref = React109.useRef({ value, previous: value });
  return React109.useMemo(() => {
    if (ref.current.value !== value) {
      ref.current.previous = ref.current.value;
      ref.current.value = value;
    }
    return ref.current.previous;
  }, [value]);
}

// node_modules/@radix-ui/react-primitive/dist/index.mjs
var React110 = __toESM(require_react(), 1);
var ReactDOM14 = __toESM(require_react_dom(), 1);
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var NODES9 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive9 = NODES9.reduce((primitive, node) => {
  const Node3 = React110.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});
function dispatchDiscreteCustomEvent5(target, event) {
  if (target)
    ReactDOM14.flushSync(() => target.dispatchEvent(event));
}

// node_modules/@radix-ui/react-collection/dist/index.mjs
var import_react27 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-collection/node_modules/@radix-ui/react-context/dist/index.mjs
var React111 = __toESM(require_react(), 1);
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
function createContextScope2(scopeName, createContextScopeDeps = []) {
  let defaultContexts = [];
  function createContext32(rootComponentName, defaultContext) {
    const BaseContext = React111.createContext(defaultContext);
    const index2 = defaultContexts.length;
    defaultContexts = [...defaultContexts, defaultContext];
    function Provider5(props) {
      const { scope, children, ...context } = props;
      const Context2 = scope?.[scopeName][index2] || BaseContext;
      const value = React111.useMemo(() => context, Object.values(context));
      return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Context2.Provider, { value, children });
    }
    function useContext22(consumerName, scope) {
      const Context2 = scope?.[scopeName][index2] || BaseContext;
      const context = React111.useContext(Context2);
      if (context)
        return context;
      if (defaultContext !== void 0)
        return defaultContext;
      throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
    }
    Provider5.displayName = rootComponentName + "Provider";
    return [Provider5, useContext22];
  }
  const createScope2 = () => {
    const scopeContexts = defaultContexts.map((defaultContext) => {
      return React111.createContext(defaultContext);
    });
    return function useScope(scope) {
      const contexts = scope?.[scopeName] || scopeContexts;
      return React111.useMemo(
        () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),
        [scope, contexts]
      );
    };
  };
  createScope2.scopeName = scopeName;
  return [createContext32, composeContextScopes2(createScope2, ...createContextScopeDeps)];
}
function composeContextScopes2(...scopes) {
  const baseScope = scopes[0];
  if (scopes.length === 1)
    return baseScope;
  const createScope2 = () => {
    const scopeHooks = scopes.map((createScope22) => ({
      useScope: createScope22(),
      scopeName: createScope22.scopeName
    }));
    return function useComposedScopes(overrideScopes) {
      const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => {
        const scopeProps = useScope(overrideScopes);
        const currentScope = scopeProps[`__scope${scopeName}`];
        return { ...nextScopes2, ...currentScope };
      }, {});
      return React111.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);
    };
  };
  createScope2.scopeName = baseScope.scopeName;
  return createScope2;
}

// node_modules/@radix-ui/react-collection/dist/index.mjs
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
"use client";
function createCollection3(name) {
  const PROVIDER_NAME2 = name + "CollectionProvider";
  const [createCollectionContext, createCollectionScope5] = createContextScope2(PROVIDER_NAME2);
  const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(
    PROVIDER_NAME2,
    { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }
  );
  const CollectionProvider = (props) => {
    const { scope, children } = props;
    const ref = import_react27.default.useRef(null);
    const itemMap = import_react27.default.useRef(/* @__PURE__ */ new Map()).current;
    return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(CollectionProviderImpl, { scope, itemMap, collectionRef: ref, children });
  };
  CollectionProvider.displayName = PROVIDER_NAME2;
  const COLLECTION_SLOT_NAME = name + "CollectionSlot";
  const CollectionSlot = import_react27.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children } = props;
      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
      const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);
      return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Slot, { ref: composedRefs, children });
    }
  );
  CollectionSlot.displayName = COLLECTION_SLOT_NAME;
  const ITEM_SLOT_NAME = name + "CollectionItemSlot";
  const ITEM_DATA_ATTR = "data-radix-collection-item";
  const CollectionItemSlot = import_react27.default.forwardRef(
    (props, forwardedRef) => {
      const { scope, children, ...itemData } = props;
      const ref = import_react27.default.useRef(null);
      const composedRefs = useComposedRefs(forwardedRef, ref);
      const context = useCollectionContext(ITEM_SLOT_NAME, scope);
      import_react27.default.useEffect(() => {
        context.itemMap.set(ref, { ref, ...itemData });
        return () => void context.itemMap.delete(ref);
      });
      return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Slot, { ...{ [ITEM_DATA_ATTR]: "" }, ref: composedRefs, children });
    }
  );
  CollectionItemSlot.displayName = ITEM_SLOT_NAME;
  function useCollection5(scope) {
    const context = useCollectionContext(name + "CollectionConsumer", scope);
    const getItems = import_react27.default.useCallback(() => {
      const collectionNode = context.collectionRef.current;
      if (!collectionNode)
        return [];
      const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
      const items = Array.from(context.itemMap.values());
      const orderedItems = items.sort(
        (a3, b3) => orderedNodes.indexOf(a3.ref.current) - orderedNodes.indexOf(b3.ref.current)
      );
      return orderedItems;
    }, [context.collectionRef, context.itemMap]);
    return getItems;
  }
  return [
    { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },
    useCollection5,
    createCollectionScope5
  ];
}

// node_modules/@radix-ui/react-slider/dist/index.mjs
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
"use client";
var PAGE_KEYS = ["PageUp", "PageDown"];
var ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
var BACK_KEYS = {
  "from-left": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
  "from-right": ["Home", "PageDown", "ArrowDown", "ArrowRight"],
  "from-bottom": ["Home", "PageDown", "ArrowDown", "ArrowLeft"],
  "from-top": ["Home", "PageDown", "ArrowUp", "ArrowLeft"]
};
var SLIDER_NAME = "Slider";
var [Collection3, useCollection3, createCollectionScope3] = createCollection3(SLIDER_NAME);
var [createSliderContext, createSliderScope] = createContextScope(SLIDER_NAME, [
  createCollectionScope3
]);
var [SliderProvider, useSliderContext] = createSliderContext(SLIDER_NAME);
var Slider = React113.forwardRef(
  (props, forwardedRef) => {
    const {
      name,
      min: min2 = 0,
      max: max2 = 100,
      step = 1,
      orientation = "horizontal",
      disabled = false,
      minStepsBetweenThumbs = 0,
      defaultValue = [min2],
      value,
      onValueChange = () => {
      },
      onValueCommit = () => {
      },
      inverted = false,
      form,
      ...sliderProps
    } = props;
    const thumbRefs = React113.useRef(/* @__PURE__ */ new Set());
    const valueIndexToChangeRef = React113.useRef(0);
    const isHorizontal = orientation === "horizontal";
    const SliderOrientation = isHorizontal ? SliderHorizontal : SliderVertical;
    const [values = [], setValues] = useControllableState({
      prop: value,
      defaultProp: defaultValue,
      onChange: (value2) => {
        const thumbs = [...thumbRefs.current];
        thumbs[valueIndexToChangeRef.current]?.focus();
        onValueChange(value2);
      }
    });
    const valuesBeforeSlideStartRef = React113.useRef(values);
    function handleSlideStart(value2) {
      const closestIndex = getClosestValueIndex(values, value2);
      updateValues(value2, closestIndex);
    }
    function handleSlideMove(value2) {
      updateValues(value2, valueIndexToChangeRef.current);
    }
    function handleSlideEnd() {
      const prevValue = valuesBeforeSlideStartRef.current[valueIndexToChangeRef.current];
      const nextValue = values[valueIndexToChangeRef.current];
      const hasChanged = nextValue !== prevValue;
      if (hasChanged)
        onValueCommit(values);
    }
    function updateValues(value2, atIndex, { commit } = { commit: false }) {
      const decimalCount = getDecimalCount(step);
      const snapToStep = roundValue(Math.round((value2 - min2) / step) * step + min2, decimalCount);
      const nextValue = clamp2(snapToStep, [min2, max2]);
      setValues((prevValues = []) => {
        const nextValues = getNextSortedValues(prevValues, nextValue, atIndex);
        if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) {
          valueIndexToChangeRef.current = nextValues.indexOf(nextValue);
          const hasChanged = String(nextValues) !== String(prevValues);
          if (hasChanged && commit)
            onValueCommit(nextValues);
          return hasChanged ? nextValues : prevValues;
        } else {
          return prevValues;
        }
      });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      SliderProvider,
      {
        scope: props.__scopeSlider,
        name,
        disabled,
        min: min2,
        max: max2,
        valueIndexToChangeRef,
        thumbs: thumbRefs.current,
        values,
        orientation,
        form,
        children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Collection3.Provider, { scope: props.__scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Collection3.Slot, { scope: props.__scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          SliderOrientation,
          {
            "aria-disabled": disabled,
            "data-disabled": disabled ? "" : void 0,
            ...sliderProps,
            ref: forwardedRef,
            onPointerDown: composeEventHandlers9(sliderProps.onPointerDown, () => {
              if (!disabled)
                valuesBeforeSlideStartRef.current = values;
            }),
            min: min2,
            max: max2,
            inverted,
            onSlideStart: disabled ? void 0 : handleSlideStart,
            onSlideMove: disabled ? void 0 : handleSlideMove,
            onSlideEnd: disabled ? void 0 : handleSlideEnd,
            onHomeKeyDown: () => !disabled && updateValues(min2, 0, { commit: true }),
            onEndKeyDown: () => !disabled && updateValues(max2, values.length - 1, { commit: true }),
            onStepKeyDown: ({ event, direction: stepDirection }) => {
              if (!disabled) {
                const isPageKey = PAGE_KEYS.includes(event.key);
                const isSkipKey = isPageKey || event.shiftKey && ARROW_KEYS.includes(event.key);
                const multiplier = isSkipKey ? 10 : 1;
                const atIndex = valueIndexToChangeRef.current;
                const value2 = values[atIndex];
                const stepInDirection = step * multiplier * stepDirection;
                updateValues(value2 + stepInDirection, atIndex, { commit: true });
              }
            }
          }
        ) }) })
      }
    );
  }
);
Slider.displayName = SLIDER_NAME;
var [SliderOrientationProvider, useSliderOrientationContext] = createSliderContext(SLIDER_NAME, {
  startEdge: "left",
  endEdge: "right",
  size: "width",
  direction: 1
});
var SliderHorizontal = React113.forwardRef(
  (props, forwardedRef) => {
    const {
      min: min2,
      max: max2,
      dir,
      inverted,
      onSlideStart,
      onSlideMove,
      onSlideEnd,
      onStepKeyDown,
      ...sliderProps
    } = props;
    const [slider, setSlider] = React113.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setSlider(node));
    const rectRef = React113.useRef();
    const direction = useDirection(dir);
    const isDirectionLTR = direction === "ltr";
    const isSlidingFromLeft = isDirectionLTR && !inverted || !isDirectionLTR && inverted;
    function getValueFromPointer(pointerPosition) {
      const rect = rectRef.current || slider.getBoundingClientRect();
      const input = [0, rect.width];
      const output = isSlidingFromLeft ? [min2, max2] : [max2, min2];
      const value = linearScale(input, output);
      rectRef.current = rect;
      return value(pointerPosition - rect.left);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      SliderOrientationProvider,
      {
        scope: props.__scopeSlider,
        startEdge: isSlidingFromLeft ? "left" : "right",
        endEdge: isSlidingFromLeft ? "right" : "left",
        direction: isSlidingFromLeft ? 1 : -1,
        size: "width",
        children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          SliderImpl,
          {
            dir: direction,
            "data-orientation": "horizontal",
            ...sliderProps,
            ref: composedRefs,
            style: {
              ...sliderProps.style,
              ["--radix-slider-thumb-transform"]: "translateX(-50%)"
            },
            onSlideStart: (event) => {
              const value = getValueFromPointer(event.clientX);
              onSlideStart?.(value);
            },
            onSlideMove: (event) => {
              const value = getValueFromPointer(event.clientX);
              onSlideMove?.(value);
            },
            onSlideEnd: () => {
              rectRef.current = void 0;
              onSlideEnd?.();
            },
            onStepKeyDown: (event) => {
              const slideDirection = isSlidingFromLeft ? "from-left" : "from-right";
              const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
              onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
            }
          }
        )
      }
    );
  }
);
var SliderVertical = React113.forwardRef(
  (props, forwardedRef) => {
    const {
      min: min2,
      max: max2,
      inverted,
      onSlideStart,
      onSlideMove,
      onSlideEnd,
      onStepKeyDown,
      ...sliderProps
    } = props;
    const sliderRef = React113.useRef(null);
    const ref = useComposedRefs(forwardedRef, sliderRef);
    const rectRef = React113.useRef();
    const isSlidingFromBottom = !inverted;
    function getValueFromPointer(pointerPosition) {
      const rect = rectRef.current || sliderRef.current.getBoundingClientRect();
      const input = [0, rect.height];
      const output = isSlidingFromBottom ? [max2, min2] : [min2, max2];
      const value = linearScale(input, output);
      rectRef.current = rect;
      return value(pointerPosition - rect.top);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      SliderOrientationProvider,
      {
        scope: props.__scopeSlider,
        startEdge: isSlidingFromBottom ? "bottom" : "top",
        endEdge: isSlidingFromBottom ? "top" : "bottom",
        size: "height",
        direction: isSlidingFromBottom ? 1 : -1,
        children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          SliderImpl,
          {
            "data-orientation": "vertical",
            ...sliderProps,
            ref,
            style: {
              ...sliderProps.style,
              ["--radix-slider-thumb-transform"]: "translateY(50%)"
            },
            onSlideStart: (event) => {
              const value = getValueFromPointer(event.clientY);
              onSlideStart?.(value);
            },
            onSlideMove: (event) => {
              const value = getValueFromPointer(event.clientY);
              onSlideMove?.(value);
            },
            onSlideEnd: () => {
              rectRef.current = void 0;
              onSlideEnd?.();
            },
            onStepKeyDown: (event) => {
              const slideDirection = isSlidingFromBottom ? "from-bottom" : "from-top";
              const isBackKey = BACK_KEYS[slideDirection].includes(event.key);
              onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
            }
          }
        )
      }
    );
  }
);
var SliderImpl = React113.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSlider,
      onSlideStart,
      onSlideMove,
      onSlideEnd,
      onHomeKeyDown,
      onEndKeyDown,
      onStepKeyDown,
      ...sliderProps
    } = props;
    const context = useSliderContext(SLIDER_NAME, __scopeSlider);
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      Primitive9.span,
      {
        ...sliderProps,
        ref: forwardedRef,
        onKeyDown: composeEventHandlers9(props.onKeyDown, (event) => {
          if (event.key === "Home") {
            onHomeKeyDown(event);
            event.preventDefault();
          } else if (event.key === "End") {
            onEndKeyDown(event);
            event.preventDefault();
          } else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
            onStepKeyDown(event);
            event.preventDefault();
          }
        }),
        onPointerDown: composeEventHandlers9(props.onPointerDown, (event) => {
          const target = event.target;
          target.setPointerCapture(event.pointerId);
          event.preventDefault();
          if (context.thumbs.has(target)) {
            target.focus();
          } else {
            onSlideStart(event);
          }
        }),
        onPointerMove: composeEventHandlers9(props.onPointerMove, (event) => {
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId))
            onSlideMove(event);
        }),
        onPointerUp: composeEventHandlers9(props.onPointerUp, (event) => {
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId)) {
            target.releasePointerCapture(event.pointerId);
            onSlideEnd(event);
          }
        })
      }
    );
  }
);
var TRACK_NAME = "SliderTrack";
var SliderTrack = React113.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSlider, ...trackProps } = props;
    const context = useSliderContext(TRACK_NAME, __scopeSlider);
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      Primitive9.span,
      {
        "data-disabled": context.disabled ? "" : void 0,
        "data-orientation": context.orientation,
        ...trackProps,
        ref: forwardedRef
      }
    );
  }
);
SliderTrack.displayName = TRACK_NAME;
var RANGE_NAME = "SliderRange";
var SliderRange = React113.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSlider, ...rangeProps } = props;
    const context = useSliderContext(RANGE_NAME, __scopeSlider);
    const orientation = useSliderOrientationContext(RANGE_NAME, __scopeSlider);
    const ref = React113.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref);
    const valuesCount = context.values.length;
    const percentages = context.values.map(
      (value) => convertValueToPercentage(value, context.min, context.max)
    );
    const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0;
    const offsetEnd = 100 - Math.max(...percentages);
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
      Primitive9.span,
      {
        "data-orientation": context.orientation,
        "data-disabled": context.disabled ? "" : void 0,
        ...rangeProps,
        ref: composedRefs,
        style: {
          ...props.style,
          [orientation.startEdge]: offsetStart + "%",
          [orientation.endEdge]: offsetEnd + "%"
        }
      }
    );
  }
);
SliderRange.displayName = RANGE_NAME;
var THUMB_NAME = "SliderThumb";
var SliderThumb = React113.forwardRef(
  (props, forwardedRef) => {
    const getItems = useCollection3(props.__scopeSlider);
    const [thumb, setThumb] = React113.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setThumb(node));
    const index2 = React113.useMemo(
      () => thumb ? getItems().findIndex((item) => item.ref.current === thumb) : -1,
      [getItems, thumb]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(SliderThumbImpl, { ...props, ref: composedRefs, index: index2 });
  }
);
var SliderThumbImpl = React113.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSlider, index: index2, name, ...thumbProps } = props;
    const context = useSliderContext(THUMB_NAME, __scopeSlider);
    const orientation = useSliderOrientationContext(THUMB_NAME, __scopeSlider);
    const [thumb, setThumb] = React113.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setThumb(node));
    const isFormControl = thumb ? context.form || !!thumb.closest("form") : true;
    const size4 = useSize(thumb);
    const value = context.values[index2];
    const percent = value === void 0 ? 0 : convertValueToPercentage(value, context.min, context.max);
    const label = getLabel(index2, context.values.length);
    const orientationSize = size4?.[orientation.size];
    const thumbInBoundsOffset = orientationSize ? getThumbInBoundsOffset(orientationSize, percent, orientation.direction) : 0;
    React113.useEffect(() => {
      if (thumb) {
        context.thumbs.add(thumb);
        return () => {
          context.thumbs.delete(thumb);
        };
      }
    }, [thumb, context.thumbs]);
    return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
      "span",
      {
        style: {
          transform: "var(--radix-slider-thumb-transform)",
          position: "absolute",
          [orientation.startEdge]: `calc(${percent}% + ${thumbInBoundsOffset}px)`
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Collection3.ItemSlot, { scope: props.__scopeSlider, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            Primitive9.span,
            {
              role: "slider",
              "aria-label": props["aria-label"] || label,
              "aria-valuemin": context.min,
              "aria-valuenow": value,
              "aria-valuemax": context.max,
              "aria-orientation": context.orientation,
              "data-orientation": context.orientation,
              "data-disabled": context.disabled ? "" : void 0,
              tabIndex: context.disabled ? void 0 : 0,
              ...thumbProps,
              ref: composedRefs,
              style: value === void 0 ? { display: "none" } : props.style,
              onFocus: composeEventHandlers9(props.onFocus, () => {
                context.valueIndexToChangeRef.current = index2;
              })
            }
          ) }),
          isFormControl && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            BubbleInput,
            {
              name: name ?? (context.name ? context.name + (context.values.length > 1 ? "[]" : "") : void 0),
              form: context.form,
              value
            },
            index2
          )
        ]
      }
    );
  }
);
SliderThumb.displayName = THUMB_NAME;
var BubbleInput = (props) => {
  const { value, ...inputProps } = props;
  const ref = React113.useRef(null);
  const prevValue = usePrevious(value);
  React113.useEffect(() => {
    const input = ref.current;
    const inputProto = window.HTMLInputElement.prototype;
    const descriptor = Object.getOwnPropertyDescriptor(inputProto, "value");
    const setValue = descriptor.set;
    if (prevValue !== value && setValue) {
      const event = new Event("input", { bubbles: true });
      setValue.call(input, value);
      input.dispatchEvent(event);
    }
  }, [prevValue, value]);
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)("input", { style: { display: "none" }, ...inputProps, ref, defaultValue: value });
};
function getNextSortedValues(prevValues = [], nextValue, atIndex) {
  const nextValues = [...prevValues];
  nextValues[atIndex] = nextValue;
  return nextValues.sort((a3, b3) => a3 - b3);
}
function convertValueToPercentage(value, min2, max2) {
  const maxSteps = max2 - min2;
  const percentPerStep = 100 / maxSteps;
  const percentage = percentPerStep * (value - min2);
  return clamp2(percentage, [0, 100]);
}
function getLabel(index2, totalValues) {
  if (totalValues > 2) {
    return `Value ${index2 + 1} of ${totalValues}`;
  } else if (totalValues === 2) {
    return ["Minimum", "Maximum"][index2];
  } else {
    return void 0;
  }
}
function getClosestValueIndex(values, nextValue) {
  if (values.length === 1)
    return 0;
  const distances = values.map((value) => Math.abs(value - nextValue));
  const closestDistance = Math.min(...distances);
  return distances.indexOf(closestDistance);
}
function getThumbInBoundsOffset(width, left, direction) {
  const halfWidth = width / 2;
  const halfPercent = 50;
  const offset5 = linearScale([0, halfPercent], [0, halfWidth]);
  return (halfWidth - offset5(left) * direction) * direction;
}
function getStepsBetweenValues(values) {
  return values.slice(0, -1).map((value, index2) => values[index2 + 1] - value);
}
function hasMinStepsBetweenValues(values, minStepsBetweenValues) {
  if (minStepsBetweenValues > 0) {
    const stepsBetweenValues = getStepsBetweenValues(values);
    const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues);
    return actualMinStepsBetweenValues >= minStepsBetweenValues;
  }
  return true;
}
function linearScale(input, output) {
  return (value) => {
    if (input[0] === input[1] || output[0] === output[1])
      return output[0];
    const ratio = (output[1] - output[0]) / (input[1] - input[0]);
    return output[0] + ratio * (value - input[0]);
  };
}
function getDecimalCount(value) {
  return (String(value).split(".")[1] || "").length;
}
function roundValue(value, decimalCount) {
  const rounder = Math.pow(10, decimalCount);
  return Math.round(value * rounder) / rounder;
}
var Root11 = Slider;
var Track = SliderTrack;
var Range = SliderRange;
var Thumb = SliderThumb;

// src/components/ui/slider.tsx
var Slider2 = React114.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React114.createElement(
  Root11,
  {
    ref,
    className: cn("relative flex w-full touch-none select-none items-center", className),
    ...props
  },
  /* @__PURE__ */ React114.createElement(Track, { className: "relative h-1.5 w-full grow overflow-hidden border border-solid border-interactive-accent/30 rounded-full bg-interactive-accent/20" }, /* @__PURE__ */ React114.createElement(Range, { className: "absolute h-full bg-interactive-accent" })),
  /* @__PURE__ */ React114.createElement(Thumb, { className: "block h-4 w-4 rounded-full border bg-toggle-thumb shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" })
));
Slider2.displayName = Root11.displayName;

// src/components/ui/setting-slider.tsx
function SettingSlider({
  value: initialValue,
  onChange,
  min: min2,
  max: max2,
  step,
  disabled,
  className
}) {
  const [localValue, setLocalValue] = (0, import_react28.useState)(initialValue);
  (0, import_react28.useEffect)(() => {
    setLocalValue(initialValue);
  }, [initialValue]);
  return /* @__PURE__ */ import_react28.default.createElement("div", { className: cn("flex items-center gap-4", className) }, /* @__PURE__ */ import_react28.default.createElement(
    Slider2,
    {
      value: [localValue],
      onValueChange: ([value]) => setLocalValue(value),
      onValueCommit: ([value]) => onChange?.(value),
      min: min2,
      max: max2,
      step,
      disabled,
      className: "flex-1"
    }
  ), /* @__PURE__ */ import_react28.default.createElement("div", { className: "min-w-[40px] text-sm text-right" }, localValue));
}

// src/components/ui/setting-item.tsx
function SettingItem(props) {
  const { title, description, className, disabled } = props;
  const { modalContainer } = useTab();
  const onChange = "onChange" in props ? props.onChange : void 0;
  const debouncedOnChange = (0, import_react29.useMemo)(() => {
    if (!onChange)
      return;
    return debounce((value) => {
      onChange(value);
    }, 1e3);
  }, [onChange]);
  const renderControl = () => {
    switch (props.type) {
      case "text":
      case "number":
        return /* @__PURE__ */ import_react29.default.createElement(
          Input,
          {
            type: props.type,
            defaultValue: props.value,
            onChange: (e3) => {
              debouncedOnChange?.(e3.target.value);
            },
            placeholder: props.placeholder,
            disabled,
            className: "w-full sm:w-[200px]"
          }
        );
      case "password":
        return /* @__PURE__ */ import_react29.default.createElement(
          PasswordInput,
          {
            value: props.value,
            onChange: (value) => {
              debouncedOnChange?.(value);
            },
            placeholder: props.placeholder,
            disabled,
            className: "w-full sm:w-[200px]"
          }
        );
      case "textarea":
        return /* @__PURE__ */ import_react29.default.createElement(
          Textarea,
          {
            defaultValue: props.value,
            onChange: (e3) => {
              debouncedOnChange?.(e3.target.value);
            },
            placeholder: props.placeholder,
            rows: props.rows || 3,
            disabled,
            className: "w-full sm:w-[300px] min-h-[80px]"
          }
        );
      case "switch":
        return /* @__PURE__ */ import_react29.default.createElement(
          SettingSwitch,
          {
            checked: props.checked,
            onCheckedChange: props.onCheckedChange,
            disabled
          }
        );
      case "select":
        return /* @__PURE__ */ import_react29.default.createElement("div", { className: "relative w-full sm:w-[200px] group" }, /* @__PURE__ */ import_react29.default.createElement(
          "select",
          {
            value: props.value?.toString(),
            onChange: (e3) => props.onChange?.(e3.target.value),
            disabled,
            className: cn(
              "w-full appearance-none",
              "flex h-9 rounded-md border border-solid border-border bg-dropdown px-3 py-1 pr-8",
              "text-sm !shadow transition-colors",
              "focus:outline-none focus:ring-1 focus:ring-ring",
              "disabled:cursor-not-allowed disabled:opacity-50",
              "hover:bg-interactive-accent hover:text-on-accent"
            )
          },
          props.placeholder && /* @__PURE__ */ import_react29.default.createElement("option", { value: "", disabled: true }, props.placeholder),
          props.options.map((option) => /* @__PURE__ */ import_react29.default.createElement("option", { key: option.value, value: option.value.toString() }, option.label))
        ), /* @__PURE__ */ import_react29.default.createElement(
          "div",
          {
            className: cn(
              "pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2",
              "transition-colors group-hover:[&>svg]:text-on-accent",
              disabled && "opacity-50"
            )
          },
          /* @__PURE__ */ import_react29.default.createElement(ChevronDown, { className: "h-4 w-4" })
        ));
      case "slider":
        return /* @__PURE__ */ import_react29.default.createElement(
          SettingSlider,
          {
            value: props.value || 0,
            onChange: props.onChange,
            min: props.min,
            max: props.max,
            step: props.step,
            disabled,
            className: "w-full sm:w-[300px]"
          }
        );
      case "dialog":
        return /* @__PURE__ */ import_react29.default.createElement(Dialog2, null, /* @__PURE__ */ import_react29.default.createElement(DialogTrigger2, { asChild: true }, props.trigger), /* @__PURE__ */ import_react29.default.createElement(DialogContent2, { container: modalContainer }, (props.dialogTitle || props.dialogDescription) && /* @__PURE__ */ import_react29.default.createElement(DialogHeader, null, props.dialogTitle && /* @__PURE__ */ import_react29.default.createElement(DialogTitle2, null, props.dialogTitle), props.dialogDescription && /* @__PURE__ */ import_react29.default.createElement(DialogDescription2, null, props.dialogDescription)), props.children));
      case "custom":
        return props.children;
    }
  };
  return /* @__PURE__ */ import_react29.default.createElement(
    "div",
    {
      className: cn(
        "flex flex-col sm:flex-row items-start sm:items-center justify-between py-4 gap-4",
        "w-full",
        className
      )
    },
    /* @__PURE__ */ import_react29.default.createElement("div", { className: "space-y-1.5 w-full sm:w-[300px]" }, /* @__PURE__ */ import_react29.default.createElement("div", { className: "text-sm font-medium leading-none" }, title), description && /* @__PURE__ */ import_react29.default.createElement("div", { className: "text-xs text-muted" }, description)),
    /* @__PURE__ */ import_react29.default.createElement("div", { className: "flex-1 w-full sm:flex sm:justify-end" }, renderControl())
  );
}

// src/settings/v2/components/AdvancedSettings.tsx
var AdvancedSettings = () => {
  const settings = useSettingsValue();
  return /* @__PURE__ */ import_react30.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react30.default.createElement("section", null, /* @__PURE__ */ import_react30.default.createElement(
    SettingItem,
    {
      type: "textarea",
      title: "User System Prompt",
      description: "Customize the system prompt for all messages, may result in unexpected behavior!",
      value: settings.userSystemPrompt,
      onChange: (value) => updateSetting("userSystemPrompt", value),
      placeholder: "Enter your system prompt here..."
    }
  ), /* @__PURE__ */ import_react30.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react30.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Enable Encryption",
      description: "Enable encryption for the API keys.",
      checked: settings.enableEncryption,
      onCheckedChange: (checked) => {
        updateSetting("enableEncryption", checked);
      }
    }
  ), /* @__PURE__ */ import_react30.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Debug Mode",
      description: "Debug mode will log some debug message to the console.",
      checked: settings.debug,
      onCheckedChange: (checked) => {
        updateSetting("debug", checked);
      }
    }
  ))));
};
var AdvancedSettings_default = AdvancedSettings;

// src/components/modals/RebuildIndexConfirmModal.tsx
var RebuildIndexConfirmModal = class extends ConfirmModal {
  constructor(app2, onConfirm) {
    super(
      app2,
      onConfirm,
      "Changing this setting means you have to rebuild the index for your entire vault, do you wish to proceed?",
      "Rebuild Index"
    );
  }
};

// src/settings/v2/components/BasicSettings.tsx
var import_obsidian43 = require("obsidian");
var import_react34 = __toESM(require_react());

// src/settings/v2/components/ApiKeyDialog.tsx
var import_obsidian41 = require("obsidian");
var import_react31 = __toESM(require_react());
var ApiKeyDialog = ({
  open,
  onOpenChange,
  settings,
  updateSetting: updateSetting2,
  modalContainer
}) => {
  const [verifyingProviders, setVerifyingProviders] = (0, import_react31.useState)(/* @__PURE__ */ new Set());
  const [unverifiedKeys, setUnverifiedKeys] = (0, import_react31.useState)(/* @__PURE__ */ new Set());
  const handleOpenChange = (isOpen) => {
    if (isOpen) {
      setUnverifiedKeys(/* @__PURE__ */ new Set());
    } else {
      unverifiedKeys.forEach((provider) => {
        const settingKey = ProviderSettingsKeyMap[provider];
        updateSetting2(settingKey, "");
      });
    }
    onOpenChange(isOpen);
  };
  const excludeProviders = [
    "3rd party (openai-format)" /* OPENAI_FORMAT */,
    "ollama" /* OLLAMA */,
    "lm-studio" /* LM_STUDIO */,
    "azure openai" /* AZURE_OPENAI */,
    "copilot-plus" /* COPILOT_PLUS */,
    "copilot-plus-jina" /* COPILOT_PLUS_JINA */
  ];
  const getApiKeyByProvider = (provider) => {
    const settingKey = ProviderSettingsKeyMap[provider];
    return settings[settingKey] ?? "";
  };
  const providers = Object.entries(ProviderInfo).filter(([key]) => !excludeProviders.includes(key)).map(([provider]) => {
    const providerKey = provider;
    const apiKey = getApiKeyByProvider(providerKey);
    return {
      provider: providerKey,
      apiKey,
      isVerified: !!apiKey && !unverifiedKeys.has(providerKey)
    };
  });
  const handleApiKeyChange = (provider, value) => {
    const currentKey = getApiKeyByProvider(provider);
    if (currentKey !== value) {
      updateSetting2(ProviderSettingsKeyMap[provider], value);
      setUnverifiedKeys((prev) => new Set(prev).add(provider));
    }
  };
  const verifyApiKey = async (provider, apiKey) => {
    setVerifyingProviders((prev) => new Set(prev).add(provider));
    try {
      if (settings.debug)
        console.log(`Verifying ${provider} API key:`, apiKey);
      const defaultTestModel = getProviderInfo(provider).testModel;
      if (!defaultTestModel) {
        new import_obsidian41.Notice(
          "API key verification failed: No default test model found for the selected provider.",
          1e4
        );
        return;
      }
      const customModel = {
        name: defaultTestModel,
        provider,
        apiKey,
        enabled: true
      };
      await ChatModelManager.getInstance().ping(customModel);
      new import_obsidian41.Notice("API key verified successfully!");
      setUnverifiedKeys((prev) => {
        const next = new Set(prev);
        next.delete(provider);
        return next;
      });
    } catch (error) {
      console.error("API key verification failed:", error);
      new import_obsidian41.Notice("API key verification failed: " + err2String(error), 1e4);
    } finally {
      setVerifyingProviders((prev) => {
        const next = new Set(prev);
        next.delete(provider);
        return next;
      });
    }
  };
  return /* @__PURE__ */ import_react31.default.createElement(Dialog2, { open, onOpenChange: handleOpenChange }, /* @__PURE__ */ import_react31.default.createElement(DialogContent2, { container: modalContainer, className: "sm:max-w-[480px]" }, /* @__PURE__ */ import_react31.default.createElement(DialogHeader, null, /* @__PURE__ */ import_react31.default.createElement(DialogTitle2, null, "AI Provider Settings"), /* @__PURE__ */ import_react31.default.createElement(DialogDescription2, null, "Configure your AI providers by adding their API keys.")), /* @__PURE__ */ import_react31.default.createElement("div", { className: "space-y-6 py-4" }, /* @__PURE__ */ import_react31.default.createElement("div", { className: "space-y-4" }, providers.map((item) => /* @__PURE__ */ import_react31.default.createElement("div", { key: item.provider, className: "flex items-center gap-2" }, /* @__PURE__ */ import_react31.default.createElement("div", { className: "w-[120px] font-medium" }, /* @__PURE__ */ import_react31.default.createElement("div", { className: "truncate" }, getProviderLabel(item.provider)), getProviderInfo(item.provider).keyManagementURL && /* @__PURE__ */ import_react31.default.createElement(
    "a",
    {
      href: getProviderInfo(item.provider).keyManagementURL,
      target: "_blank",
      rel: "noopener noreferrer",
      className: "text-[10px] text-accent hover:text-accent-hover"
    },
    "Get ",
    getProviderLabel(item.provider),
    " Key"
  )), /* @__PURE__ */ import_react31.default.createElement("div", { className: "flex-1 flex items-center gap-2" }, /* @__PURE__ */ import_react31.default.createElement("div", { className: "flex-1 pr-2" }, /* @__PURE__ */ import_react31.default.createElement(
    PasswordInput,
    {
      className: "w-full",
      value: item.apiKey,
      onChange: (v5) => handleApiKeyChange(item.provider, v5),
      disabled: verifyingProviders.has(item.provider)
    }
  )), /* @__PURE__ */ import_react31.default.createElement("div", { className: "w-[72px]" }, !item.isVerified ? /* @__PURE__ */ import_react31.default.createElement(
    Button,
    {
      onClick: () => verifyApiKey(item.provider, item.apiKey),
      disabled: !item.apiKey || verifyingProviders.size > 0,
      variant: "outline",
      size: "sm",
      className: "w-full whitespace-nowrap"
    },
    verifyingProviders.has(item.provider) ? /* @__PURE__ */ import_react31.default.createElement(import_react31.default.Fragment, null, /* @__PURE__ */ import_react31.default.createElement(LoaderCircle, { className: "mr-2 h-4 w-4 animate-spin" }), "Verify") : "Verify"
  ) : /* @__PURE__ */ import_react31.default.createElement("span", { className: "text-success text-sm flex items-center justify-center h-9" }, "Verified")))))))));
};
var ApiKeyDialog_default = ApiKeyDialog;

// src/components/modals/CopilotPlusWelcomeModal.tsx
var import_react32 = __toESM(require_react());
var import_obsidian42 = require("obsidian");
var import_client7 = __toESM(require_client());
function CopilotPlusWelcomeModalContent({
  onConfirm,
  onCancel
}) {
  const settings = getSettings();
  return /* @__PURE__ */ import_react32.default.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ import_react32.default.createElement("div", null, /* @__PURE__ */ import_react32.default.createElement("p", null, "Thanks for purchasing ", /* @__PURE__ */ import_react32.default.createElement("b", null, "Copilot Plus"), "! You have unlocked the full power of Copilot, featuring chat context, PDF and image support, exclusive chat and embedding models, and much more!"), /* @__PURE__ */ import_react32.default.createElement("p", null, "Would you like to apply the Copilot Plus settings now? You can always change this later in Settings."), /* @__PURE__ */ import_react32.default.createElement("ul", { className: "pl-4" }, /* @__PURE__ */ import_react32.default.createElement("li", null, "Default mode: ", /* @__PURE__ */ import_react32.default.createElement("b", { className: "text-accent" }, "Copilot Plus")), /* @__PURE__ */ import_react32.default.createElement("li", null, "Chat model: ", /* @__PURE__ */ import_react32.default.createElement("b", { className: "text-accent" }, DEFAULT_COPILOT_PLUS_CHAT_MODEL)), /* @__PURE__ */ import_react32.default.createElement("li", null, /* @__PURE__ */ import_react32.default.createElement("div", null, "Embedding model: ", /* @__PURE__ */ import_react32.default.createElement("b", { className: "text-accent" }, DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL)), settings.embeddingModelKey !== DEFAULT_COPILOT_PLUS_EMBEDDING_MODEL_KEY && /* @__PURE__ */ import_react32.default.createElement("div", { className: "text-sm text-warning flex items-center gap-1" }, /* @__PURE__ */ import_react32.default.createElement(TriangleAlert, { className: "size-4" }), " It will rebuild your embeddings for the entire vault")))), /* @__PURE__ */ import_react32.default.createElement("div", { className: "flex gap-2 justify-end w-full" }, /* @__PURE__ */ import_react32.default.createElement(Button, { variant: "ghost", onClick: onCancel }, "Apply Later"), /* @__PURE__ */ import_react32.default.createElement(Button, { variant: "default", onClick: onConfirm }, "Apply Now")));
}
var CopilotPlusWelcomeModal = class extends import_obsidian42.Modal {
  constructor(app2) {
    super(app2);
    this.setTitle("Welcome to Copilot Plus \u{1F680}");
  }
  onOpen() {
    const { contentEl } = this;
    this.root = (0, import_client7.createRoot)(contentEl);
    const handleConfirm = () => {
      applyPlusSettings();
      this.close();
    };
    const handleCancel = () => {
      this.close();
    };
    this.root.render(
      /* @__PURE__ */ import_react32.default.createElement(CopilotPlusWelcomeModalContent, { onConfirm: handleConfirm, onCancel: handleCancel })
    );
  }
  onClose() {
    this.root.unmount();
  }
};

// src/settings/v2/components/PlusSettings.tsx
var import_react33 = __toESM(require_react());
function PlusSettings() {
  const settings = useSettingsValue();
  const [error, setError] = (0, import_react33.useState)(null);
  const [isChecking, setIsChecking] = (0, import_react33.useState)(false);
  const isPlusUser = useIsPlusUser();
  const [localLicenseKey, setLocalLicenseKey] = (0, import_react33.useState)(settings.plusLicenseKey);
  (0, import_react33.useEffect)(() => {
    setLocalLicenseKey(settings.plusLicenseKey);
  }, [settings.plusLicenseKey]);
  return /* @__PURE__ */ import_react33.default.createElement("section", { className: "flex flex-col gap-4 bg-secondary p-4 rounded-lg" }, /* @__PURE__ */ import_react33.default.createElement("div", { className: "text-xl font-bold flex items-center gap-2 justify-between" }, /* @__PURE__ */ import_react33.default.createElement("span", null, "Copilot Plus (beta)"), isPlusUser && /* @__PURE__ */ import_react33.default.createElement(Badge, { variant: "outline", className: "text-success" }, "Active")), /* @__PURE__ */ import_react33.default.createElement("div", { className: "text-sm text-muted flex flex-col gap-2" }, /* @__PURE__ */ import_react33.default.createElement("div", null, "Copilot Plus takes your Obsidian experience to the next level with cutting-edge AI capabilities. This premium tier unlocks advanced features, including chat context, PDF and image support, web search integration, exclusive chat and embedding models, and much more."), /* @__PURE__ */ import_react33.default.createElement("div", null, "Currently in beta, Copilot Plus is evolving fast, with new features and improvements rolling out regularly. Join now to secure the lowest price and get early access!")), /* @__PURE__ */ import_react33.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react33.default.createElement(
    PasswordInput,
    {
      className: "w-full",
      placeholder: "Enter your license key",
      value: localLicenseKey,
      onChange: (value) => {
        setLocalLicenseKey(value);
      }
    }
  ), /* @__PURE__ */ import_react33.default.createElement(
    Button,
    {
      disabled: isChecking,
      onClick: async () => {
        updateSetting("plusLicenseKey", localLicenseKey);
        setIsChecking(true);
        const result = await checkIsPlusUser();
        setIsChecking(false);
        if (!result) {
          setError("Invalid license key");
        } else {
          setError(null);
          new CopilotPlusWelcomeModal(app).open();
        }
      },
      className: "min-w-20"
    },
    isChecking ? /* @__PURE__ */ import_react33.default.createElement(LoaderCircle, { className: "h-4 w-4 animate-spin" }) : "Apply"
  ), /* @__PURE__ */ import_react33.default.createElement(Button, { variant: "default", onClick: () => navigateToPlusPage(PLUS_UTM_MEDIUMS.SETTINGS) }, "Join Now ", /* @__PURE__ */ import_react33.default.createElement(ExternalLink, { className: "size-4" }))), /* @__PURE__ */ import_react33.default.createElement("div", { className: "text-error" }, error));
}

// src/settings/v2/components/BasicSettings.tsx
var ChainType2Label = {
  ["llm_chain" /* LLM_CHAIN */]: "Chat",
  ["vault_qa" /* VAULT_QA_CHAIN */]: "Vault QA (Basic)",
  ["copilot_plus" /* COPILOT_PLUS_CHAIN */]: "Copilot Plus (beta)"
};
var BasicSettings = ({ indexVaultToVectorStore }) => {
  const { modalContainer } = useTab();
  const settings = useSettingsValue();
  const [isApiKeyDialogOpen, setIsApiKeyDialogOpen] = (0, import_react34.useState)(false);
  const [isChecking, setIsChecking] = (0, import_react34.useState)(false);
  const [conversationNoteName, setConversationNoteName] = (0, import_react34.useState)(
    settings.defaultConversationNoteName || "{$date}_{$time}__{$topic}"
  );
  const handleSetDefaultEmbeddingModel = async (modelKey) => {
    if (modelKey !== settings.embeddingModelKey) {
      new RebuildIndexConfirmModal(app, async () => {
        updateSetting("embeddingModelKey", modelKey);
        await indexVaultToVectorStore(true);
      }).open();
    }
  };
  const applyCustomNoteFormat = () => {
    setIsChecking(true);
    try {
      const format = conversationNoteName || "{$date}_{$time}__{$topic}";
      const requiredVars = ["{$date}", "{$time}", "{$topic}"];
      const missingVars = requiredVars.filter((v5) => !format.includes(v5));
      if (missingVars.length > 0) {
        new import_obsidian43.Notice(`Error: Missing required variables: ${missingVars.join(", ")}`, 4e3);
        return;
      }
      const illegalChars = /[\\/:*?"<>|]/;
      const formatWithoutVars = format.replace(/\{\$date}/g, "").replace(/\{\$time}/g, "").replace(/\{\$topic}/g, "");
      if (illegalChars.test(formatWithoutVars)) {
        new import_obsidian43.Notice(`Error: Format contains illegal characters (\\/:*?"<>|)`, 4e3);
        return;
      }
      const { fileName: timestampFileName } = formatDateTime(new Date());
      const firstTenWords = "test topic name";
      const customFileName = format.replace("{$topic}", firstTenWords.slice(0, 100).replace(/\s+/g, "_")).replace("{$date}", timestampFileName.split("_")[0]).replace("{$time}", timestampFileName.split("_")[1]);
      updateSetting("defaultConversationNoteName", format);
      setConversationNoteName(format);
      new import_obsidian43.Notice(`Format applied successfully! Example: ${customFileName}`, 4e3);
    } catch (error) {
      new import_obsidian43.Notice(`Error applying format: ${error.message}`, 4e3);
    } finally {
      setIsChecking(false);
    }
  };
  return /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react34.default.createElement(PlusSettings, null), /* @__PURE__ */ import_react34.default.createElement("section", null, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-xl font-bold mb-3" }, "General"), /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "custom",
      title: "API Keys",
      description: /* @__PURE__ */ import_react34.default.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ import_react34.default.createElement("span", { className: "leading-none" }, "Configure API keys for different AI providers"), /* @__PURE__ */ import_react34.default.createElement(TooltipProvider2, { delayDuration: 0 }, /* @__PURE__ */ import_react34.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react34.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react34.default.createElement(CircleHelp, { className: "size-4" })), /* @__PURE__ */ import_react34.default.createElement(TooltipContent2, { className: "max-w-96 flex flex-col gap-2 py-4" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-sm font-medium text-accent" }, "API key required for chat and QA features"), /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-xs text-muted" }, "To enable chat and QA functionality, please provide an API key from your selected provider.")))))
    },
    /* @__PURE__ */ import_react34.default.createElement(
      Button,
      {
        onClick: () => setIsApiKeyDialogOpen(true),
        variant: "outline",
        className: "flex items-center gap-2 w-full sm:w-auto justify-center sm:justify-start"
      },
      "Set Keys",
      /* @__PURE__ */ import_react34.default.createElement(Key, { className: "h-4 w-4" })
    )
  ), /* @__PURE__ */ import_react34.default.createElement(
    ApiKeyDialog_default,
    {
      open: isApiKeyDialogOpen,
      onOpenChange: setIsApiKeyDialogOpen,
      settings,
      updateSetting,
      modalContainer
    }
  )), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Default Chat Model",
      description: "Select the Chat model to use",
      value: settings.defaultModelKey,
      onChange: (value) => {
        updateSetting("defaultModelKey", value);
      },
      options: settings.activeModels.filter((m3) => m3.enabled).map((model) => ({
        label: `${model.name} (${getProviderLabel(model.provider)})`,
        value: getModelKeyFromModel(model)
      })),
      placeholder: "Model"
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Embedding Model",
      description: /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ import_react34.default.createElement("span", { className: "leading-none font-medium text-accent" }, "Core Feature: Powers Semantic Search & QA"), /* @__PURE__ */ import_react34.default.createElement(TooltipProvider2, { delayDuration: 0 }, /* @__PURE__ */ import_react34.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react34.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react34.default.createElement(CircleHelp, { className: "size-4" })), /* @__PURE__ */ import_react34.default.createElement(TooltipContent2, { className: "max-w-96 flex flex-col gap-2" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-sm text-muted pt-2" }, "This model converts text into vector representations, essential for semantic search and QA functionality. Changing the embedding model will:"), /* @__PURE__ */ import_react34.default.createElement("ul", { className: "text-sm text-muted pl-4" }, /* @__PURE__ */ import_react34.default.createElement("li", null, "Require rebuilding your vault's vector index"), /* @__PURE__ */ import_react34.default.createElement("li", null, "Affect semantic search quality"), /* @__PURE__ */ import_react34.default.createElement("li", null, "Impact QA feature performance"))))))),
      value: settings.embeddingModelKey,
      onChange: handleSetDefaultEmbeddingModel,
      options: settings.activeEmbeddingModels.map((model) => ({
        label: `${model.name} (${getProviderLabel(model.provider)})`,
        value: getModelKeyFromModel(model)
      })),
      placeholder: "Model"
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Default Mode",
      description: /* @__PURE__ */ import_react34.default.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ import_react34.default.createElement("span", { className: "leading-none" }, "Select the default chat mode"), /* @__PURE__ */ import_react34.default.createElement(TooltipProvider2, { delayDuration: 0 }, /* @__PURE__ */ import_react34.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react34.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react34.default.createElement(CircleHelp, { className: "size-4" })), /* @__PURE__ */ import_react34.default.createElement(TooltipContent2, { className: "max-w-96 flex flex-col gap-2" }, /* @__PURE__ */ import_react34.default.createElement("ul", { className: "text-sm text-muted pl-4" }, /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "Chat:"), " Regular chat mode for general conversations and tasks. ", /* @__PURE__ */ import_react34.default.createElement("i", null, "Free to use with your own API key.")), /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "Vault QA (Basic):"), " Ask questions about your vault content with semantic search. ", /* @__PURE__ */ import_react34.default.createElement("i", null, "Free to use with your own API key.")), /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "Copilot Plus:"), " Covers all features of the 2 free modes, plus advanced paid features including chat context menu, advanced search, AI agents, and more. Check out", " ", /* @__PURE__ */ import_react34.default.createElement(
        "a",
        {
          href: createPlusPageUrl(PLUS_UTM_MEDIUMS.MODE_SELECT_TOOLTIP),
          target: "_blank",
          rel: "noopener noreferrer",
          className: "text-accent hover:text-accent-hover"
        },
        "obsidiancopilot.com"
      ), " ", "for more details.")))))),
      value: settings.defaultChainType,
      onChange: (value) => updateSetting("defaultChainType", value),
      options: Object.entries(ChainType2Label).map(([key, value]) => ({
        label: value,
        value: key
      }))
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Open Plugin In",
      description: "Choose where to open the plugin",
      value: settings.defaultOpenArea,
      onChange: (value) => updateSetting("defaultOpenArea", value),
      options: [
        { label: "Sidebar View", value: "view" /* VIEW */ },
        { label: "Editor", value: "editor" /* EDITOR */ }
      ]
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "text",
      title: "Default Conversation Folder Name",
      description: "The default folder name where chat conversations will be saved. Default is 'copilot-conversations'",
      value: settings.defaultSaveFolder,
      onChange: (value) => updateSetting("defaultSaveFolder", value),
      placeholder: "copilot-conversations"
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "text",
      title: "Custom Prompts Folder Name",
      description: "The default folder name where custom prompts will be saved. Default is 'copilot-custom-prompts'",
      value: settings.customPromptsFolder,
      onChange: (value) => updateSetting("customPromptsFolder", value),
      placeholder: "copilot-custom-prompts"
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "text",
      title: "Default Conversation Tag",
      description: "The default tag to be used when saving a conversation. Default is 'ai-conversations'",
      value: settings.defaultConversationTag,
      onChange: (value) => updateSetting("defaultConversationTag", value),
      placeholder: "ai-conversations"
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "custom",
      title: "Conversation Filename Template",
      description: /* @__PURE__ */ import_react34.default.createElement("div", { className: "flex items-start gap-1.5 " }, /* @__PURE__ */ import_react34.default.createElement("span", { className: "leading-none" }, "Customize the format of saved conversation note names."), /* @__PURE__ */ import_react34.default.createElement(TooltipProvider2, { delayDuration: 0 }, /* @__PURE__ */ import_react34.default.createElement(Tooltip2, null, /* @__PURE__ */ import_react34.default.createElement(TooltipTrigger2, { asChild: true }, /* @__PURE__ */ import_react34.default.createElement(CircleHelp, { className: "size-4" })), /* @__PURE__ */ import_react34.default.createElement(TooltipContent2, { className: "max-w-96 flex flex-col gap-2 py-4" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-sm font-medium text-accent" }, "Note: All the following variables must be included in the template."), /* @__PURE__ */ import_react34.default.createElement("div", null, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-sm font-medium text-muted" }, "Available variables:"), /* @__PURE__ */ import_react34.default.createElement("ul", { className: "text-sm text-muted pl-4" }, /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "{$date}"), ": Date in YYYYMMDD format"), /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "{$time}"), ": Time in HHMMSS format"), /* @__PURE__ */ import_react34.default.createElement("li", null, /* @__PURE__ */ import_react34.default.createElement("strong", null, "{$topic}"), ": Chat conversation topic")), /* @__PURE__ */ import_react34.default.createElement("i", { className: "text-sm text-muted mt-2" }, "Example: ", "{$date}_{$time}__{$topic}", " \u2192 20250114_153232__polish_this_article_[[Readme]]"))))))
    },
    /* @__PURE__ */ import_react34.default.createElement("div", { className: "flex items-center gap-1.5 w-[320px]" }, /* @__PURE__ */ import_react34.default.createElement(
      Input,
      {
        type: "text",
        className: `transition-all duration-200 flex-grow min-w-[80px] ${isChecking ? "w-[80px]" : "w-[120px]"}`,
        placeholder: "{$date}_{$time}__{$topic}",
        value: conversationNoteName,
        onChange: (e3) => setConversationNoteName(e3.target.value),
        disabled: isChecking
      }
    ), /* @__PURE__ */ import_react34.default.createElement(
      Button,
      {
        onClick: () => applyCustomNoteFormat(),
        disabled: isChecking,
        variant: "outline",
        size: "sm"
      },
      isChecking ? /* @__PURE__ */ import_react34.default.createElement(import_react34.default.Fragment, null, /* @__PURE__ */ import_react34.default.createElement(LoaderCircle, { className: "mr-2 h-4 w-4 animate-spin" }), "Apply") : "Apply"
    ))
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Autosave Chat",
      description: "Automatically save the chat when starting a new one or when the plugin reloads",
      checked: settings.autosaveChat,
      onCheckedChange: (checked) => updateSetting("autosaveChat", checked)
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Suggested Prompts",
      description: "Show suggested prompts in the chat view",
      checked: settings.showSuggestedPrompts,
      onCheckedChange: (checked) => updateSetting("showSuggestedPrompts", checked)
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Relevant Notes",
      description: "Show relevant notes in the chat view",
      checked: settings.showRelevantNotes,
      onCheckedChange: (checked) => updateSetting("showRelevantNotes", checked)
    }
  ), /* @__PURE__ */ import_react34.default.createElement(
    SettingItem,
    {
      type: "dialog",
      title: "Command Settings",
      description: "Enable or disable builtin Copilot commands",
      dialogTitle: "Command Settings",
      dialogDescription: "Enable or disable chat commands",
      trigger: /* @__PURE__ */ import_react34.default.createElement(Button, { variant: "outline" }, "Manage Commands")
    },
    /* @__PURE__ */ import_react34.default.createElement("div", { className: "h-[50vh] sm:h-[400px] overflow-y-auto px-1 py-2" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-4" }, DISABLEABLE_COMMANDS.map((command) => /* @__PURE__ */ import_react34.default.createElement(
      "div",
      {
        key: command,
        className: "flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 py-2 sm:py-0.5"
      },
      /* @__PURE__ */ import_react34.default.createElement("div", { className: "space-y-0.5 flex-1" }, /* @__PURE__ */ import_react34.default.createElement("div", { className: "text-sm font-medium" }, COMMAND_NAMES[command])),
      /* @__PURE__ */ import_react34.default.createElement(
        SettingSwitch,
        {
          checked: isCommandEnabled(command),
          onCheckedChange: (checked) => {
            const newEnabledCommands = {
              ...settings.enabledCommands,
              [command]: {
                enabled: checked
              }
            };
            updateSetting("enabledCommands", newEnabledCommands);
          }
        }
      )
    ))))
  ))));
};
var BasicSettings_default = BasicSettings;

// src/settings/v2/components/ModelSettings.tsx
var import_react37 = __toESM(require_react());

// src/settings/v2/components/ModelAddDialog.tsx
var import_react35 = __toESM(require_react());
var import_obsidian44 = require("obsidian");

// src/components/ui/label.tsx
var React123 = __toESM(require_react());

// node_modules/@radix-ui/react-label/dist/index.mjs
var React122 = __toESM(require_react(), 1);
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
"use client";
var NAME5 = "Label";
var Label3 = React122.forwardRef((props, forwardedRef) => {
  return /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
    Primitive9.label,
    {
      ...props,
      ref: forwardedRef,
      onMouseDown: (event) => {
        const target = event.target;
        if (target.closest("button, input, select, textarea"))
          return;
        props.onMouseDown?.(event);
        if (!event.defaultPrevented && event.detail > 1)
          event.preventDefault();
      }
    }
  );
});
Label3.displayName = NAME5;
var Root12 = Label3;

// src/components/ui/label.tsx
var labelVariants = cva(
  "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
);
var Label4 = React123.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React123.createElement(Root12, { ref, className: cn(labelVariants(), className), ...props }));
Label4.displayName = Root12.displayName;

// src/components/ui/select.tsx
var React132 = __toESM(require_react());

// node_modules/@radix-ui/react-select/dist/index.mjs
var React131 = __toESM(require_react(), 1);
var ReactDOM16 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs
var React124 = __toESM(require_react(), 1);
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
"use client";
var DISMISSABLE_LAYER_NAME5 = "DismissableLayer";
var CONTEXT_UPDATE5 = "dismissableLayer.update";
var POINTER_DOWN_OUTSIDE5 = "dismissableLayer.pointerDownOutside";
var FOCUS_OUTSIDE5 = "dismissableLayer.focusOutside";
var originalBodyPointerEvents5;
var DismissableLayerContext5 = React124.createContext({
  layers: /* @__PURE__ */ new Set(),
  layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
  branches: /* @__PURE__ */ new Set()
});
var DismissableLayer5 = React124.forwardRef(
  (props, forwardedRef) => {
    const {
      disableOutsidePointerEvents = false,
      onEscapeKeyDown,
      onPointerDownOutside,
      onFocusOutside,
      onInteractOutside,
      onDismiss,
      ...layerProps
    } = props;
    const context = React124.useContext(DismissableLayerContext5);
    const [node, setNode] = React124.useState(null);
    const ownerDocument = node?.ownerDocument ?? globalThis?.document;
    const [, force] = React124.useState({});
    const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2));
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node ? layers.indexOf(node) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = usePointerDownOutside5((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target));
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    const focusOutside = useFocusOutside5((event) => {
      const target = event.target;
      const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target));
      if (isFocusInBranch)
        return;
      onFocusOutside?.(event);
      onInteractOutside?.(event);
      if (!event.defaultPrevented)
        onDismiss?.();
    }, ownerDocument);
    useEscapeKeydown((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown?.(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    React124.useEffect(() => {
      if (!node)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          originalBodyPointerEvents5 = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node);
      }
      context.layers.add(node);
      dispatchUpdate5();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) {
          ownerDocument.body.style.pointerEvents = originalBodyPointerEvents5;
        }
      };
    }, [node, ownerDocument, disableOutsidePointerEvents, context]);
    React124.useEffect(() => {
      return () => {
        if (!node)
          return;
        context.layers.delete(node);
        context.layersWithOutsidePointerEventsDisabled.delete(node);
        dispatchUpdate5();
      };
    }, [node, context]);
    React124.useEffect(() => {
      const handleUpdate = () => force({});
      document.addEventListener(CONTEXT_UPDATE5, handleUpdate);
      return () => document.removeEventListener(CONTEXT_UPDATE5, handleUpdate);
    }, []);
    return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
      Primitive9.div,
      {
        ...layerProps,
        ref: composedRefs,
        style: {
          pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
          ...props.style
        },
        onFocusCapture: composeEventHandlers9(props.onFocusCapture, focusOutside.onFocusCapture),
        onBlurCapture: composeEventHandlers9(props.onBlurCapture, focusOutside.onBlurCapture),
        onPointerDownCapture: composeEventHandlers9(
          props.onPointerDownCapture,
          pointerDownOutside.onPointerDownCapture
        )
      }
    );
  }
);
DismissableLayer5.displayName = DISMISSABLE_LAYER_NAME5;
var BRANCH_NAME5 = "DismissableLayerBranch";
var DismissableLayerBranch5 = React124.forwardRef((props, forwardedRef) => {
  const context = React124.useContext(DismissableLayerContext5);
  const ref = React124.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, ref);
  React124.useEffect(() => {
    const node = ref.current;
    if (node) {
      context.branches.add(node);
      return () => {
        context.branches.delete(node);
      };
    }
  }, [context.branches]);
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Primitive9.div, { ...props, ref: composedRefs });
});
DismissableLayerBranch5.displayName = BRANCH_NAME5;
function usePointerDownOutside5(onPointerDownOutside, ownerDocument = globalThis?.document) {
  const handlePointerDownOutside = useCallbackRef(onPointerDownOutside);
  const isPointerInsideReactTreeRef = React124.useRef(false);
  const handleClickRef = React124.useRef(() => {
  });
  React124.useEffect(() => {
    const handlePointerDown = (event) => {
      if (event.target && !isPointerInsideReactTreeRef.current) {
        let handleAndDispatchPointerDownOutsideEvent2 = function() {
          handleAndDispatchCustomEvent5(
            POINTER_DOWN_OUTSIDE5,
            handlePointerDownOutside,
            eventDetail,
            { discrete: true }
          );
        };
        var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2;
        const eventDetail = { originalEvent: event };
        if (event.pointerType === "touch") {
          ownerDocument.removeEventListener("click", handleClickRef.current);
          handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
          ownerDocument.addEventListener("click", handleClickRef.current, { once: true });
        } else {
          handleAndDispatchPointerDownOutsideEvent2();
        }
      } else {
        ownerDocument.removeEventListener("click", handleClickRef.current);
      }
      isPointerInsideReactTreeRef.current = false;
    };
    const timerId = window.setTimeout(() => {
      ownerDocument.addEventListener("pointerdown", handlePointerDown);
    }, 0);
    return () => {
      window.clearTimeout(timerId);
      ownerDocument.removeEventListener("pointerdown", handlePointerDown);
      ownerDocument.removeEventListener("click", handleClickRef.current);
    };
  }, [ownerDocument, handlePointerDownOutside]);
  return {
    // ensures we check React component tree (not just DOM tree)
    onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
  };
}
function useFocusOutside5(onFocusOutside, ownerDocument = globalThis?.document) {
  const handleFocusOutside = useCallbackRef(onFocusOutside);
  const isFocusInsideReactTreeRef = React124.useRef(false);
  React124.useEffect(() => {
    const handleFocus = (event) => {
      if (event.target && !isFocusInsideReactTreeRef.current) {
        const eventDetail = { originalEvent: event };
        handleAndDispatchCustomEvent5(FOCUS_OUTSIDE5, handleFocusOutside, eventDetail, {
          discrete: false
        });
      }
    };
    ownerDocument.addEventListener("focusin", handleFocus);
    return () => ownerDocument.removeEventListener("focusin", handleFocus);
  }, [ownerDocument, handleFocusOutside]);
  return {
    onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
    onBlurCapture: () => isFocusInsideReactTreeRef.current = false
  };
}
function dispatchUpdate5() {
  const event = new CustomEvent(CONTEXT_UPDATE5);
  document.dispatchEvent(event);
}
function handleAndDispatchCustomEvent5(name, handler, detail, { discrete }) {
  const target = detail.originalEvent.target;
  const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail });
  if (handler)
    target.addEventListener(name, handler, { once: true });
  if (discrete) {
    dispatchDiscreteCustomEvent5(target, event);
  } else {
    target.dispatchEvent(event);
  }
}

// node_modules/@radix-ui/react-focus-scope/dist/index.mjs
var React125 = __toESM(require_react(), 1);
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
"use client";
var AUTOFOCUS_ON_MOUNT4 = "focusScope.autoFocusOnMount";
var AUTOFOCUS_ON_UNMOUNT4 = "focusScope.autoFocusOnUnmount";
var EVENT_OPTIONS5 = { bubbles: false, cancelable: true };
var FOCUS_SCOPE_NAME4 = "FocusScope";
var FocusScope4 = React125.forwardRef((props, forwardedRef) => {
  const {
    loop = false,
    trapped = false,
    onMountAutoFocus: onMountAutoFocusProp,
    onUnmountAutoFocus: onUnmountAutoFocusProp,
    ...scopeProps
  } = props;
  const [container, setContainer] = React125.useState(null);
  const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp);
  const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp);
  const lastFocusedElementRef = React125.useRef(null);
  const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node));
  const focusScope = React125.useRef({
    paused: false,
    pause() {
      this.paused = true;
    },
    resume() {
      this.paused = false;
    }
  }).current;
  React125.useEffect(() => {
    if (trapped) {
      let handleFocusIn2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const target = event.target;
        if (container.contains(target)) {
          lastFocusedElementRef.current = target;
        } else {
          focus4(lastFocusedElementRef.current, { select: true });
        }
      }, handleFocusOut2 = function(event) {
        if (focusScope.paused || !container)
          return;
        const relatedTarget = event.relatedTarget;
        if (relatedTarget === null)
          return;
        if (!container.contains(relatedTarget)) {
          focus4(lastFocusedElementRef.current, { select: true });
        }
      }, handleMutations2 = function(mutations) {
        const focusedElement = document.activeElement;
        if (focusedElement !== document.body)
          return;
        for (const mutation of mutations) {
          if (mutation.removedNodes.length > 0)
            focus4(container);
        }
      };
      var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2;
      document.addEventListener("focusin", handleFocusIn2);
      document.addEventListener("focusout", handleFocusOut2);
      const mutationObserver = new MutationObserver(handleMutations2);
      if (container)
        mutationObserver.observe(container, { childList: true, subtree: true });
      return () => {
        document.removeEventListener("focusin", handleFocusIn2);
        document.removeEventListener("focusout", handleFocusOut2);
        mutationObserver.disconnect();
      };
    }
  }, [trapped, container, focusScope.paused]);
  React125.useEffect(() => {
    if (container) {
      focusScopesStack4.add(focusScope);
      const previouslyFocusedElement = document.activeElement;
      const hasFocusedCandidate = container.contains(previouslyFocusedElement);
      if (!hasFocusedCandidate) {
        const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT4, EVENT_OPTIONS5);
        container.addEventListener(AUTOFOCUS_ON_MOUNT4, onMountAutoFocus);
        container.dispatchEvent(mountEvent);
        if (!mountEvent.defaultPrevented) {
          focusFirst6(removeLinks4(getTabbableCandidates4(container)), { select: true });
          if (document.activeElement === previouslyFocusedElement) {
            focus4(container);
          }
        }
      }
      return () => {
        container.removeEventListener(AUTOFOCUS_ON_MOUNT4, onMountAutoFocus);
        setTimeout(() => {
          const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT4, EVENT_OPTIONS5);
          container.addEventListener(AUTOFOCUS_ON_UNMOUNT4, onUnmountAutoFocus);
          container.dispatchEvent(unmountEvent);
          if (!unmountEvent.defaultPrevented) {
            focus4(previouslyFocusedElement ?? document.body, { select: true });
          }
          container.removeEventListener(AUTOFOCUS_ON_UNMOUNT4, onUnmountAutoFocus);
          focusScopesStack4.remove(focusScope);
        }, 0);
      };
    }
  }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]);
  const handleKeyDown = React125.useCallback(
    (event) => {
      if (!loop && !trapped)
        return;
      if (focusScope.paused)
        return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container2 = event.currentTarget;
        const [first, last] = getTabbableEdges4(container2);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container2)
            event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop)
              focus4(first, { select: true });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop)
              focus4(last, { select: true });
          }
        }
      }
    },
    [loop, trapped, focusScope.paused]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Primitive9.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown });
});
FocusScope4.displayName = FOCUS_SCOPE_NAME4;
function focusFirst6(candidates, { select = false } = {}) {
  const previouslyFocusedElement = document.activeElement;
  for (const candidate of candidates) {
    focus4(candidate, { select });
    if (document.activeElement !== previouslyFocusedElement)
      return;
  }
}
function getTabbableEdges4(container) {
  const candidates = getTabbableCandidates4(container);
  const first = findVisible4(candidates, container);
  const last = findVisible4(candidates.reverse(), container);
  return [first, last];
}
function getTabbableCandidates4(container) {
  const nodes = [];
  const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
    acceptNode: (node) => {
      const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
      if (node.disabled || node.hidden || isHiddenInput)
        return NodeFilter.FILTER_SKIP;
      return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  while (walker.nextNode())
    nodes.push(walker.currentNode);
  return nodes;
}
function findVisible4(elements, container) {
  for (const element of elements) {
    if (!isHidden4(element, { upTo: container }))
      return element;
  }
}
function isHidden4(node, { upTo }) {
  if (getComputedStyle(node).visibility === "hidden")
    return true;
  while (node) {
    if (upTo !== void 0 && node === upTo)
      return false;
    if (getComputedStyle(node).display === "none")
      return true;
    node = node.parentElement;
  }
  return false;
}
function isSelectableInput4(element) {
  return element instanceof HTMLInputElement && "select" in element;
}
function focus4(element, { select = false } = {}) {
  if (element && element.focus) {
    const previouslyFocusedElement = document.activeElement;
    element.focus({ preventScroll: true });
    if (element !== previouslyFocusedElement && isSelectableInput4(element) && select)
      element.select();
  }
}
var focusScopesStack4 = createFocusScopesStack4();
function createFocusScopesStack4() {
  let stack = [];
  return {
    add(focusScope) {
      const activeFocusScope = stack[0];
      if (focusScope !== activeFocusScope) {
        activeFocusScope?.pause();
      }
      stack = arrayRemove4(stack, focusScope);
      stack.unshift(focusScope);
    },
    remove(focusScope) {
      stack = arrayRemove4(stack, focusScope);
      stack[0]?.resume();
    }
  };
}
function arrayRemove4(array, item) {
  const updatedArray = [...array];
  const index2 = updatedArray.indexOf(item);
  if (index2 !== -1) {
    updatedArray.splice(index2, 1);
  }
  return updatedArray;
}
function removeLinks4(items) {
  return items.filter((item) => item.tagName !== "A");
}

// node_modules/@radix-ui/react-popper/dist/index.mjs
var React128 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-arrow/dist/index.mjs
var React126 = __toESM(require_react(), 1);
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var NAME6 = "Arrow";
var Arrow7 = React126.forwardRef((props, forwardedRef) => {
  const { children, width = 10, height = 5, ...arrowProps } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(
    Primitive9.svg,
    {
      ...arrowProps,
      ref: forwardedRef,
      width,
      height,
      viewBox: "0 0 30 10",
      preserveAspectRatio: "none",
      children: props.asChild ? children : /* @__PURE__ */ (0, import_jsx_runtime54.jsx)("polygon", { points: "0,0 30,0 15,10" })
    }
  );
});
Arrow7.displayName = NAME6;
var Root13 = Arrow7;

// node_modules/@radix-ui/react-popper/node_modules/@radix-ui/react-context/dist/index.mjs
var React127 = __toESM(require_react(), 1);
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
function createContextScope3(scopeName, createContextScopeDeps = []) {
  let defaultContexts = [];
  function createContext32(rootComponentName, defaultContext) {
    const BaseContext = React127.createContext(defaultContext);
    const index2 = defaultContexts.length;
    defaultContexts = [...defaultContexts, defaultContext];
    function Provider5(props) {
      const { scope, children, ...context } = props;
      const Context2 = scope?.[scopeName][index2] || BaseContext;
      const value = React127.useMemo(() => context, Object.values(context));
      return /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Context2.Provider, { value, children });
    }
    function useContext22(consumerName, scope) {
      const Context2 = scope?.[scopeName][index2] || BaseContext;
      const context = React127.useContext(Context2);
      if (context)
        return context;
      if (defaultContext !== void 0)
        return defaultContext;
      throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
    }
    Provider5.displayName = rootComponentName + "Provider";
    return [Provider5, useContext22];
  }
  const createScope2 = () => {
    const scopeContexts = defaultContexts.map((defaultContext) => {
      return React127.createContext(defaultContext);
    });
    return function useScope(scope) {
      const contexts = scope?.[scopeName] || scopeContexts;
      return React127.useMemo(
        () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }),
        [scope, contexts]
      );
    };
  };
  createScope2.scopeName = scopeName;
  return [createContext32, composeContextScopes3(createScope2, ...createContextScopeDeps)];
}
function composeContextScopes3(...scopes) {
  const baseScope = scopes[0];
  if (scopes.length === 1)
    return baseScope;
  const createScope2 = () => {
    const scopeHooks = scopes.map((createScope22) => ({
      useScope: createScope22(),
      scopeName: createScope22.scopeName
    }));
    return function useComposedScopes(overrideScopes) {
      const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => {
        const scopeProps = useScope(overrideScopes);
        const currentScope = scopeProps[`__scope${scopeName}`];
        return { ...nextScopes2, ...currentScope };
      }, {});
      return React127.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]);
    };
  };
  createScope2.scopeName = baseScope.scopeName;
  return createScope2;
}

// node_modules/@radix-ui/react-popper/dist/index.mjs
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
"use client";
var POPPER_NAME4 = "Popper";
var [createPopperContext4, createPopperScope4] = createContextScope3(POPPER_NAME4);
var [PopperProvider4, usePopperContext4] = createPopperContext4(POPPER_NAME4);
var Popper4 = (props) => {
  const { __scopePopper, children } = props;
  const [anchor, setAnchor] = React128.useState(null);
  return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(PopperProvider4, { scope: __scopePopper, anchor, onAnchorChange: setAnchor, children });
};
Popper4.displayName = POPPER_NAME4;
var ANCHOR_NAME6 = "PopperAnchor";
var PopperAnchor4 = React128.forwardRef(
  (props, forwardedRef) => {
    const { __scopePopper, virtualRef, ...anchorProps } = props;
    const context = usePopperContext4(ANCHOR_NAME6, __scopePopper);
    const ref = React128.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref);
    React128.useEffect(() => {
      context.onAnchorChange(virtualRef?.current || ref.current);
    });
    return virtualRef ? null : /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Primitive9.div, { ...anchorProps, ref: composedRefs });
  }
);
PopperAnchor4.displayName = ANCHOR_NAME6;
var CONTENT_NAME10 = "PopperContent";
var [PopperContentProvider4, useContentContext4] = createPopperContext4(CONTENT_NAME10);
var PopperContent4 = React128.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopePopper,
      side = "bottom",
      sideOffset = 0,
      align = "center",
      alignOffset = 0,
      arrowPadding = 0,
      avoidCollisions = true,
      collisionBoundary = [],
      collisionPadding: collisionPaddingProp = 0,
      sticky = "partial",
      hideWhenDetached = false,
      updatePositionStrategy = "optimized",
      onPlaced,
      ...contentProps
    } = props;
    const context = usePopperContext4(CONTENT_NAME10, __scopePopper);
    const [content, setContent] = React128.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
    const [arrow4, setArrow] = React128.useState(null);
    const arrowSize = useSize(arrow4);
    const arrowWidth = arrowSize?.width ?? 0;
    const arrowHeight = arrowSize?.height ?? 0;
    const desiredPlacement = side + (align !== "center" ? "-" + align : "");
    const collisionPadding = typeof collisionPaddingProp === "number" ? collisionPaddingProp : { top: 0, right: 0, bottom: 0, left: 0, ...collisionPaddingProp };
    const boundary = Array.isArray(collisionBoundary) ? collisionBoundary : [collisionBoundary];
    const hasExplicitBoundaries = boundary.length > 0;
    const detectOverflowOptions = {
      padding: collisionPadding,
      boundary: boundary.filter(isNotNull4),
      // with `strategy: 'fixed'`, this is the only way to get it to respect boundaries
      altBoundary: hasExplicitBoundaries
    };
    const { refs, floatingStyles, placement, isPositioned, middlewareData } = useFloating({
      // default to `fixed` strategy so users don't have to pick and we also avoid focus scroll issues
      strategy: "fixed",
      placement: desiredPlacement,
      whileElementsMounted: (...args) => {
        const cleanup = autoUpdate(...args, {
          animationFrame: updatePositionStrategy === "always"
        });
        return cleanup;
      },
      elements: {
        reference: context.anchor
      },
      middleware: [
        offset4({ mainAxis: sideOffset + arrowHeight, alignmentAxis: alignOffset }),
        avoidCollisions && shift3({
          mainAxis: true,
          crossAxis: false,
          limiter: sticky === "partial" ? limitShift3() : void 0,
          ...detectOverflowOptions
        }),
        avoidCollisions && flip3({ ...detectOverflowOptions }),
        size3({
          ...detectOverflowOptions,
          apply: ({ elements, rects, availableWidth, availableHeight }) => {
            const { width: anchorWidth, height: anchorHeight } = rects.reference;
            const contentStyle = elements.floating.style;
            contentStyle.setProperty("--radix-popper-available-width", `${availableWidth}px`);
            contentStyle.setProperty("--radix-popper-available-height", `${availableHeight}px`);
            contentStyle.setProperty("--radix-popper-anchor-width", `${anchorWidth}px`);
            contentStyle.setProperty("--radix-popper-anchor-height", `${anchorHeight}px`);
          }
        }),
        arrow4 && arrow3({ element: arrow4, padding: arrowPadding }),
        transformOrigin4({ arrowWidth, arrowHeight }),
        hideWhenDetached && hide3({ strategy: "referenceHidden", ...detectOverflowOptions })
      ]
    });
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement4(placement);
    const handlePlaced = useCallbackRef(onPlaced);
    useLayoutEffect2(() => {
      if (isPositioned) {
        handlePlaced?.();
      }
    }, [isPositioned, handlePlaced]);
    const arrowX = middlewareData.arrow?.x;
    const arrowY = middlewareData.arrow?.y;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const [contentZIndex, setContentZIndex] = React128.useState();
    useLayoutEffect2(() => {
      if (content)
        setContentZIndex(window.getComputedStyle(content).zIndex);
    }, [content]);
    return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
      "div",
      {
        ref: refs.setFloating,
        "data-radix-popper-content-wrapper": "",
        style: {
          ...floatingStyles,
          transform: isPositioned ? floatingStyles.transform : "translate(0, -200%)",
          // keep off the page when measuring
          minWidth: "max-content",
          zIndex: contentZIndex,
          ["--radix-popper-transform-origin"]: [
            middlewareData.transformOrigin?.x,
            middlewareData.transformOrigin?.y
          ].join(" "),
          // hide the content if using the hide middleware and should be hidden
          // set visibility to hidden and disable pointer events so the UI behaves
          // as if the PopperContent isn't there at all
          ...middlewareData.hide?.referenceHidden && {
            visibility: "hidden",
            pointerEvents: "none"
          }
        },
        dir: props.dir,
        children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
          PopperContentProvider4,
          {
            scope: __scopePopper,
            placedSide,
            onArrowChange: setArrow,
            arrowX,
            arrowY,
            shouldHideArrow: cannotCenterArrow,
            children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
              Primitive9.div,
              {
                "data-side": placedSide,
                "data-align": placedAlign,
                ...contentProps,
                ref: composedRefs,
                style: {
                  ...contentProps.style,
                  // if the PopperContent hasn't been placed yet (not all measurements done)
                  // we prevent animations so that users's animation don't kick in too early referring wrong sides
                  animation: !isPositioned ? "none" : void 0
                }
              }
            )
          }
        )
      }
    );
  }
);
PopperContent4.displayName = CONTENT_NAME10;
var ARROW_NAME8 = "PopperArrow";
var OPPOSITE_SIDE4 = {
  top: "bottom",
  right: "left",
  bottom: "top",
  left: "right"
};
var PopperArrow5 = React128.forwardRef(function PopperArrow24(props, forwardedRef) {
  const { __scopePopper, ...arrowProps } = props;
  const contentContext = useContentContext4(ARROW_NAME8, __scopePopper);
  const baseSide = OPPOSITE_SIDE4[contentContext.placedSide];
  return (
    // we have to use an extra wrapper because `ResizeObserver` (used by `useSize`)
    // doesn't report size as we'd expect on SVG elements.
    // it reports their bounding box which is effectively the largest path inside the SVG.
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
      "span",
      {
        ref: contentContext.onArrowChange,
        style: {
          position: "absolute",
          left: contentContext.arrowX,
          top: contentContext.arrowY,
          [baseSide]: 0,
          transformOrigin: {
            top: "",
            right: "0 0",
            bottom: "center 0",
            left: "100% 0"
          }[contentContext.placedSide],
          transform: {
            top: "translateY(100%)",
            right: "translateY(50%) rotate(90deg) translateX(-50%)",
            bottom: `rotate(180deg)`,
            left: "translateY(50%) rotate(-90deg) translateX(50%)"
          }[contentContext.placedSide],
          visibility: contentContext.shouldHideArrow ? "hidden" : void 0
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(
          Root13,
          {
            ...arrowProps,
            ref: forwardedRef,
            style: {
              ...arrowProps.style,
              // ensures the element can be measured correctly (mostly for if SVG)
              display: "block"
            }
          }
        )
      }
    )
  );
});
PopperArrow5.displayName = ARROW_NAME8;
function isNotNull4(value) {
  return value !== null;
}
var transformOrigin4 = (options) => ({
  name: "transformOrigin",
  options,
  fn(data) {
    const { placement, rects, middlewareData } = data;
    const cannotCenterArrow = middlewareData.arrow?.centerOffset !== 0;
    const isArrowHidden = cannotCenterArrow;
    const arrowWidth = isArrowHidden ? 0 : options.arrowWidth;
    const arrowHeight = isArrowHidden ? 0 : options.arrowHeight;
    const [placedSide, placedAlign] = getSideAndAlignFromPlacement4(placement);
    const noArrowAlign = { start: "0%", center: "50%", end: "100%" }[placedAlign];
    const arrowXCenter = (middlewareData.arrow?.x ?? 0) + arrowWidth / 2;
    const arrowYCenter = (middlewareData.arrow?.y ?? 0) + arrowHeight / 2;
    let x2 = "";
    let y2 = "";
    if (placedSide === "bottom") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${-arrowHeight}px`;
    } else if (placedSide === "top") {
      x2 = isArrowHidden ? noArrowAlign : `${arrowXCenter}px`;
      y2 = `${rects.floating.height + arrowHeight}px`;
    } else if (placedSide === "right") {
      x2 = `${-arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    } else if (placedSide === "left") {
      x2 = `${rects.floating.width + arrowHeight}px`;
      y2 = isArrowHidden ? noArrowAlign : `${arrowYCenter}px`;
    }
    return { data: { x: x2, y: y2 } };
  }
});
function getSideAndAlignFromPlacement4(placement) {
  const [side, align = "center"] = placement.split("-");
  return [side, align];
}
var Root27 = Popper4;
var Anchor5 = PopperAnchor4;
var Content6 = PopperContent4;
var Arrow8 = PopperArrow5;

// node_modules/@radix-ui/react-portal/dist/index.mjs
var React129 = __toESM(require_react(), 1);
var import_react_dom9 = __toESM(require_react_dom(), 1);
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
"use client";
var PORTAL_NAME10 = "Portal";
var Portal9 = React129.forwardRef((props, forwardedRef) => {
  const { container: containerProp, ...portalProps } = props;
  const [mounted, setMounted] = React129.useState(false);
  useLayoutEffect2(() => setMounted(true), []);
  const container = containerProp || mounted && globalThis?.document?.body;
  return container ? import_react_dom9.default.createPortal(/* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Primitive9.div, { ...portalProps, ref: forwardedRef }), container) : null;
});
Portal9.displayName = PORTAL_NAME10;

// node_modules/@radix-ui/react-select/node_modules/@radix-ui/react-visually-hidden/dist/index.mjs
var React130 = __toESM(require_react(), 1);
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var NAME7 = "VisuallyHidden";
var VisuallyHidden2 = React130.forwardRef(
  (props, forwardedRef) => {
    return /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(
      Primitive9.span,
      {
        ...props,
        ref: forwardedRef,
        style: {
          // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss
          position: "absolute",
          border: 0,
          width: 1,
          height: 1,
          padding: 0,
          margin: -1,
          overflow: "hidden",
          clip: "rect(0, 0, 0, 0)",
          whiteSpace: "nowrap",
          wordWrap: "normal",
          ...props.style
        }
      }
    );
  }
);
VisuallyHidden2.displayName = NAME7;

// node_modules/@radix-ui/react-select/dist/index.mjs
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
"use client";
var OPEN_KEYS = [" ", "Enter", "ArrowUp", "ArrowDown"];
var SELECTION_KEYS2 = [" ", "Enter"];
var SELECT_NAME = "Select";
var [Collection4, useCollection4, createCollectionScope4] = createCollection3(SELECT_NAME);
var [createSelectContext, createSelectScope] = createContextScope(SELECT_NAME, [
  createCollectionScope4,
  createPopperScope4
]);
var usePopperScope4 = createPopperScope4();
var [SelectProvider, useSelectContext] = createSelectContext(SELECT_NAME);
var [SelectNativeOptionsProvider, useSelectNativeOptionsContext] = createSelectContext(SELECT_NAME);
var Select = (props) => {
  const {
    __scopeSelect,
    children,
    open: openProp,
    defaultOpen,
    onOpenChange,
    value: valueProp,
    defaultValue,
    onValueChange,
    dir,
    name,
    autoComplete,
    disabled,
    required,
    form
  } = props;
  const popperScope = usePopperScope4(__scopeSelect);
  const [trigger, setTrigger] = React131.useState(null);
  const [valueNode, setValueNode] = React131.useState(null);
  const [valueNodeHasChildren, setValueNodeHasChildren] = React131.useState(false);
  const direction = useDirection(dir);
  const [open = false, setOpen] = useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  const [value, setValue] = useControllableState({
    prop: valueProp,
    defaultProp: defaultValue,
    onChange: onValueChange
  });
  const triggerPointerDownPosRef = React131.useRef(null);
  const isFormControl = trigger ? form || !!trigger.closest("form") : true;
  const [nativeOptionsSet, setNativeOptionsSet] = React131.useState(/* @__PURE__ */ new Set());
  const nativeSelectKey = Array.from(nativeOptionsSet).map((option) => option.props.value).join(";");
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Root27, { ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
    SelectProvider,
    {
      required,
      scope: __scopeSelect,
      trigger,
      onTriggerChange: setTrigger,
      valueNode,
      onValueNodeChange: setValueNode,
      valueNodeHasChildren,
      onValueNodeHasChildrenChange: setValueNodeHasChildren,
      contentId: useId(),
      value,
      onValueChange: setValue,
      open,
      onOpenChange: setOpen,
      dir: direction,
      triggerPointerDownPosRef,
      disabled,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Collection4.Provider, { scope: __scopeSelect, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          SelectNativeOptionsProvider,
          {
            scope: props.__scopeSelect,
            onNativeOptionAdd: React131.useCallback((option) => {
              setNativeOptionsSet((prev) => new Set(prev).add(option));
            }, []),
            onNativeOptionRemove: React131.useCallback((option) => {
              setNativeOptionsSet((prev) => {
                const optionsSet = new Set(prev);
                optionsSet.delete(option);
                return optionsSet;
              });
            }, []),
            children
          }
        ) }),
        isFormControl ? /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
          BubbleSelect,
          {
            "aria-hidden": true,
            required,
            tabIndex: -1,
            name,
            autoComplete,
            value,
            onChange: (event) => setValue(event.target.value),
            disabled,
            form,
            children: [
              value === void 0 ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("option", { value: "" }) : null,
              Array.from(nativeOptionsSet)
            ]
          },
          nativeSelectKey
        ) : null
      ]
    }
  ) });
};
Select.displayName = SELECT_NAME;
var TRIGGER_NAME6 = "SelectTrigger";
var SelectTrigger = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, disabled = false, ...triggerProps } = props;
    const popperScope = usePopperScope4(__scopeSelect);
    const context = useSelectContext(TRIGGER_NAME6, __scopeSelect);
    const isDisabled = context.disabled || disabled;
    const composedRefs = useComposedRefs(forwardedRef, context.onTriggerChange);
    const getItems = useCollection4(__scopeSelect);
    const pointerTypeRef = React131.useRef("touch");
    const [searchRef, handleTypeaheadSearch, resetTypeahead] = useTypeaheadSearch((search3) => {
      const enabledItems = getItems().filter((item) => !item.disabled);
      const currentItem = enabledItems.find((item) => item.value === context.value);
      const nextItem = findNextItem(enabledItems, search3, currentItem);
      if (nextItem !== void 0) {
        context.onValueChange(nextItem.value);
      }
    });
    const handleOpen = (pointerEvent) => {
      if (!isDisabled) {
        context.onOpenChange(true);
        resetTypeahead();
      }
      if (pointerEvent) {
        context.triggerPointerDownPosRef.current = {
          x: Math.round(pointerEvent.pageX),
          y: Math.round(pointerEvent.pageY)
        };
      }
    };
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Anchor5, { asChild: true, ...popperScope, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
      Primitive9.button,
      {
        type: "button",
        role: "combobox",
        "aria-controls": context.contentId,
        "aria-expanded": context.open,
        "aria-required": context.required,
        "aria-autocomplete": "none",
        dir: context.dir,
        "data-state": context.open ? "open" : "closed",
        disabled: isDisabled,
        "data-disabled": isDisabled ? "" : void 0,
        "data-placeholder": shouldShowPlaceholder(context.value) ? "" : void 0,
        ...triggerProps,
        ref: composedRefs,
        onClick: composeEventHandlers9(triggerProps.onClick, (event) => {
          event.currentTarget.focus();
          if (pointerTypeRef.current !== "mouse") {
            handleOpen(event);
          }
        }),
        onPointerDown: composeEventHandlers9(triggerProps.onPointerDown, (event) => {
          pointerTypeRef.current = event.pointerType;
          const target = event.target;
          if (target.hasPointerCapture(event.pointerId)) {
            target.releasePointerCapture(event.pointerId);
          }
          if (event.button === 0 && event.ctrlKey === false && event.pointerType === "mouse") {
            handleOpen(event);
            event.preventDefault();
          }
        }),
        onKeyDown: composeEventHandlers9(triggerProps.onKeyDown, (event) => {
          const isTypingAhead = searchRef.current !== "";
          const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
          if (!isModifierKey && event.key.length === 1)
            handleTypeaheadSearch(event.key);
          if (isTypingAhead && event.key === " ")
            return;
          if (OPEN_KEYS.includes(event.key)) {
            handleOpen();
            event.preventDefault();
          }
        })
      }
    ) });
  }
);
SelectTrigger.displayName = TRIGGER_NAME6;
var VALUE_NAME = "SelectValue";
var SelectValue = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, className, style, children, placeholder = "", ...valueProps } = props;
    const context = useSelectContext(VALUE_NAME, __scopeSelect);
    const { onValueNodeHasChildrenChange } = context;
    const hasChildren = children !== void 0;
    const composedRefs = useComposedRefs(forwardedRef, context.onValueNodeChange);
    useLayoutEffect2(() => {
      onValueNodeHasChildrenChange(hasChildren);
    }, [onValueNodeHasChildrenChange, hasChildren]);
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
      Primitive9.span,
      {
        ...valueProps,
        ref: composedRefs,
        style: { pointerEvents: "none" },
        children: shouldShowPlaceholder(context.value) ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(import_jsx_runtime59.Fragment, { children: placeholder }) : children
      }
    );
  }
);
SelectValue.displayName = VALUE_NAME;
var ICON_NAME = "SelectIcon";
var SelectIcon = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, children, ...iconProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.span, { "aria-hidden": true, ...iconProps, ref: forwardedRef, children: children || "\u25BC" });
  }
);
SelectIcon.displayName = ICON_NAME;
var PORTAL_NAME11 = "SelectPortal";
var SelectPortal = (props) => {
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Portal9, { asChild: true, ...props });
};
SelectPortal.displayName = PORTAL_NAME11;
var CONTENT_NAME11 = "SelectContent";
var SelectContent = React131.forwardRef(
  (props, forwardedRef) => {
    const context = useSelectContext(CONTENT_NAME11, props.__scopeSelect);
    const [fragment, setFragment] = React131.useState();
    useLayoutEffect2(() => {
      setFragment(new DocumentFragment());
    }, []);
    if (!context.open) {
      const frag = fragment;
      return frag ? ReactDOM16.createPortal(
        /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SelectContentProvider, { scope: props.__scopeSelect, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Collection4.Slot, { scope: props.__scopeSelect, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("div", { children: props.children }) }) }),
        frag
      ) : null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SelectContentImpl, { ...props, ref: forwardedRef });
  }
);
SelectContent.displayName = CONTENT_NAME11;
var CONTENT_MARGIN = 10;
var [SelectContentProvider, useSelectContentContext] = createSelectContext(CONTENT_NAME11);
var CONTENT_IMPL_NAME = "SelectContentImpl";
var SelectContentImpl = React131.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSelect,
      position = "item-aligned",
      onCloseAutoFocus,
      onEscapeKeyDown,
      onPointerDownOutside,
      //
      // PopperContent props
      side,
      sideOffset,
      align,
      alignOffset,
      arrowPadding,
      collisionBoundary,
      collisionPadding,
      sticky,
      hideWhenDetached,
      avoidCollisions,
      //
      ...contentProps
    } = props;
    const context = useSelectContext(CONTENT_NAME11, __scopeSelect);
    const [content, setContent] = React131.useState(null);
    const [viewport, setViewport] = React131.useState(null);
    const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
    const [selectedItem, setSelectedItem] = React131.useState(null);
    const [selectedItemText, setSelectedItemText] = React131.useState(
      null
    );
    const getItems = useCollection4(__scopeSelect);
    const [isPositioned, setIsPositioned] = React131.useState(false);
    const firstValidItemFoundRef = React131.useRef(false);
    React131.useEffect(() => {
      if (content)
        return hideOthers(content);
    }, [content]);
    useFocusGuards();
    const focusFirst7 = React131.useCallback(
      (candidates) => {
        const [firstItem, ...restItems] = getItems().map((item) => item.ref.current);
        const [lastItem] = restItems.slice(-1);
        const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
        for (const candidate of candidates) {
          if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)
            return;
          candidate?.scrollIntoView({ block: "nearest" });
          if (candidate === firstItem && viewport)
            viewport.scrollTop = 0;
          if (candidate === lastItem && viewport)
            viewport.scrollTop = viewport.scrollHeight;
          candidate?.focus();
          if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT)
            return;
        }
      },
      [getItems, viewport]
    );
    const focusSelectedItem = React131.useCallback(
      () => focusFirst7([selectedItem, content]),
      [focusFirst7, selectedItem, content]
    );
    React131.useEffect(() => {
      if (isPositioned) {
        focusSelectedItem();
      }
    }, [isPositioned, focusSelectedItem]);
    const { onOpenChange, triggerPointerDownPosRef } = context;
    React131.useEffect(() => {
      if (content) {
        let pointerMoveDelta = { x: 0, y: 0 };
        const handlePointerMove = (event) => {
          pointerMoveDelta = {
            x: Math.abs(Math.round(event.pageX) - (triggerPointerDownPosRef.current?.x ?? 0)),
            y: Math.abs(Math.round(event.pageY) - (triggerPointerDownPosRef.current?.y ?? 0))
          };
        };
        const handlePointerUp = (event) => {
          if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) {
            event.preventDefault();
          } else {
            if (!content.contains(event.target)) {
              onOpenChange(false);
            }
          }
          document.removeEventListener("pointermove", handlePointerMove);
          triggerPointerDownPosRef.current = null;
        };
        if (triggerPointerDownPosRef.current !== null) {
          document.addEventListener("pointermove", handlePointerMove);
          document.addEventListener("pointerup", handlePointerUp, { capture: true, once: true });
        }
        return () => {
          document.removeEventListener("pointermove", handlePointerMove);
          document.removeEventListener("pointerup", handlePointerUp, { capture: true });
        };
      }
    }, [content, onOpenChange, triggerPointerDownPosRef]);
    React131.useEffect(() => {
      const close = () => onOpenChange(false);
      window.addEventListener("blur", close);
      window.addEventListener("resize", close);
      return () => {
        window.removeEventListener("blur", close);
        window.removeEventListener("resize", close);
      };
    }, [onOpenChange]);
    const [searchRef, handleTypeaheadSearch] = useTypeaheadSearch((search3) => {
      const enabledItems = getItems().filter((item) => !item.disabled);
      const currentItem = enabledItems.find((item) => item.ref.current === document.activeElement);
      const nextItem = findNextItem(enabledItems, search3, currentItem);
      if (nextItem) {
        setTimeout(() => nextItem.ref.current.focus());
      }
    });
    const itemRefCallback = React131.useCallback(
      (node, value, disabled) => {
        const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
        const isSelectedItem = context.value !== void 0 && context.value === value;
        if (isSelectedItem || isFirstValidItem) {
          setSelectedItem(node);
          if (isFirstValidItem)
            firstValidItemFoundRef.current = true;
        }
      },
      [context.value]
    );
    const handleItemLeave = React131.useCallback(() => content?.focus(), [content]);
    const itemTextRefCallback = React131.useCallback(
      (node, value, disabled) => {
        const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
        const isSelectedItem = context.value !== void 0 && context.value === value;
        if (isSelectedItem || isFirstValidItem) {
          setSelectedItemText(node);
        }
      },
      [context.value]
    );
    const SelectPosition = position === "popper" ? SelectPopperPosition : SelectItemAlignedPosition;
    const popperContentProps = SelectPosition === SelectPopperPosition ? {
      side,
      sideOffset,
      align,
      alignOffset,
      arrowPadding,
      collisionBoundary,
      collisionPadding,
      sticky,
      hideWhenDetached,
      avoidCollisions
    } : {};
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
      SelectContentProvider,
      {
        scope: __scopeSelect,
        content,
        viewport,
        onViewportChange: setViewport,
        itemRefCallback,
        selectedItem,
        onItemLeave: handleItemLeave,
        itemTextRefCallback,
        focusSelectedItem,
        selectedItemText,
        position,
        isPositioned,
        searchRef,
        children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Combination_default3, { as: Slot, allowPinchZoom: true, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          FocusScope4,
          {
            asChild: true,
            trapped: context.open,
            onMountAutoFocus: (event) => {
              event.preventDefault();
            },
            onUnmountAutoFocus: composeEventHandlers9(onCloseAutoFocus, (event) => {
              context.trigger?.focus({ preventScroll: true });
              event.preventDefault();
            }),
            children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
              DismissableLayer5,
              {
                asChild: true,
                disableOutsidePointerEvents: true,
                onEscapeKeyDown,
                onPointerDownOutside,
                onFocusOutside: (event) => event.preventDefault(),
                onDismiss: () => context.onOpenChange(false),
                children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
                  SelectPosition,
                  {
                    role: "listbox",
                    id: context.contentId,
                    "data-state": context.open ? "open" : "closed",
                    dir: context.dir,
                    onContextMenu: (event) => event.preventDefault(),
                    ...contentProps,
                    ...popperContentProps,
                    onPlaced: () => setIsPositioned(true),
                    ref: composedRefs,
                    style: {
                      // flex layout so we can place the scroll buttons properly
                      display: "flex",
                      flexDirection: "column",
                      // reset the outline by default as the content MAY get focused
                      outline: "none",
                      ...contentProps.style
                    },
                    onKeyDown: composeEventHandlers9(contentProps.onKeyDown, (event) => {
                      const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
                      if (event.key === "Tab")
                        event.preventDefault();
                      if (!isModifierKey && event.key.length === 1)
                        handleTypeaheadSearch(event.key);
                      if (["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {
                        const items = getItems().filter((item) => !item.disabled);
                        let candidateNodes = items.map((item) => item.ref.current);
                        if (["ArrowUp", "End"].includes(event.key)) {
                          candidateNodes = candidateNodes.slice().reverse();
                        }
                        if (["ArrowUp", "ArrowDown"].includes(event.key)) {
                          const currentElement = event.target;
                          const currentIndex = candidateNodes.indexOf(currentElement);
                          candidateNodes = candidateNodes.slice(currentIndex + 1);
                        }
                        setTimeout(() => focusFirst7(candidateNodes));
                        event.preventDefault();
                      }
                    })
                  }
                )
              }
            )
          }
        ) })
      }
    );
  }
);
SelectContentImpl.displayName = CONTENT_IMPL_NAME;
var ITEM_ALIGNED_POSITION_NAME = "SelectItemAlignedPosition";
var SelectItemAlignedPosition = React131.forwardRef((props, forwardedRef) => {
  const { __scopeSelect, onPlaced, ...popperProps } = props;
  const context = useSelectContext(CONTENT_NAME11, __scopeSelect);
  const contentContext = useSelectContentContext(CONTENT_NAME11, __scopeSelect);
  const [contentWrapper, setContentWrapper] = React131.useState(null);
  const [content, setContent] = React131.useState(null);
  const composedRefs = useComposedRefs(forwardedRef, (node) => setContent(node));
  const getItems = useCollection4(__scopeSelect);
  const shouldExpandOnScrollRef = React131.useRef(false);
  const shouldRepositionRef = React131.useRef(true);
  const { viewport, selectedItem, selectedItemText, focusSelectedItem } = contentContext;
  const position = React131.useCallback(() => {
    if (context.trigger && context.valueNode && contentWrapper && content && viewport && selectedItem && selectedItemText) {
      const triggerRect = context.trigger.getBoundingClientRect();
      const contentRect = content.getBoundingClientRect();
      const valueNodeRect = context.valueNode.getBoundingClientRect();
      const itemTextRect = selectedItemText.getBoundingClientRect();
      if (context.dir !== "rtl") {
        const itemTextOffset = itemTextRect.left - contentRect.left;
        const left = valueNodeRect.left - itemTextOffset;
        const leftDelta = triggerRect.left - left;
        const minContentWidth = triggerRect.width + leftDelta;
        const contentWidth = Math.max(minContentWidth, contentRect.width);
        const rightEdge = window.innerWidth - CONTENT_MARGIN;
        const clampedLeft = clamp2(left, [
          CONTENT_MARGIN,
          // Prevents the content from going off the starting edge of the
          // viewport. It may still go off the ending edge, but this can be
          // controlled by the user since they may want to manage overflow in a
          // specific way.
          // https://github.com/radix-ui/primitives/issues/2049
          Math.max(CONTENT_MARGIN, rightEdge - contentWidth)
        ]);
        contentWrapper.style.minWidth = minContentWidth + "px";
        contentWrapper.style.left = clampedLeft + "px";
      } else {
        const itemTextOffset = contentRect.right - itemTextRect.right;
        const right = window.innerWidth - valueNodeRect.right - itemTextOffset;
        const rightDelta = window.innerWidth - triggerRect.right - right;
        const minContentWidth = triggerRect.width + rightDelta;
        const contentWidth = Math.max(minContentWidth, contentRect.width);
        const leftEdge = window.innerWidth - CONTENT_MARGIN;
        const clampedRight = clamp2(right, [
          CONTENT_MARGIN,
          Math.max(CONTENT_MARGIN, leftEdge - contentWidth)
        ]);
        contentWrapper.style.minWidth = minContentWidth + "px";
        contentWrapper.style.right = clampedRight + "px";
      }
      const items = getItems();
      const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
      const itemsHeight = viewport.scrollHeight;
      const contentStyles = window.getComputedStyle(content);
      const contentBorderTopWidth = parseInt(contentStyles.borderTopWidth, 10);
      const contentPaddingTop = parseInt(contentStyles.paddingTop, 10);
      const contentBorderBottomWidth = parseInt(contentStyles.borderBottomWidth, 10);
      const contentPaddingBottom = parseInt(contentStyles.paddingBottom, 10);
      const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth;
      const minContentHeight = Math.min(selectedItem.offsetHeight * 5, fullContentHeight);
      const viewportStyles = window.getComputedStyle(viewport);
      const viewportPaddingTop = parseInt(viewportStyles.paddingTop, 10);
      const viewportPaddingBottom = parseInt(viewportStyles.paddingBottom, 10);
      const topEdgeToTriggerMiddle = triggerRect.top + triggerRect.height / 2 - CONTENT_MARGIN;
      const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle;
      const selectedItemHalfHeight = selectedItem.offsetHeight / 2;
      const itemOffsetMiddle = selectedItem.offsetTop + selectedItemHalfHeight;
      const contentTopToItemMiddle = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle;
      const itemMiddleToContentBottom = fullContentHeight - contentTopToItemMiddle;
      const willAlignWithoutTopOverflow = contentTopToItemMiddle <= topEdgeToTriggerMiddle;
      if (willAlignWithoutTopOverflow) {
        const isLastItem = items.length > 0 && selectedItem === items[items.length - 1].ref.current;
        contentWrapper.style.bottom = "0px";
        const viewportOffsetBottom = content.clientHeight - viewport.offsetTop - viewport.offsetHeight;
        const clampedTriggerMiddleToBottomEdge = Math.max(
          triggerMiddleToBottomEdge,
          selectedItemHalfHeight + // viewport might have padding bottom, include it to avoid a scrollable viewport
          (isLastItem ? viewportPaddingBottom : 0) + viewportOffsetBottom + contentBorderBottomWidth
        );
        const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge;
        contentWrapper.style.height = height + "px";
      } else {
        const isFirstItem = items.length > 0 && selectedItem === items[0].ref.current;
        contentWrapper.style.top = "0px";
        const clampedTopEdgeToTriggerMiddle = Math.max(
          topEdgeToTriggerMiddle,
          contentBorderTopWidth + viewport.offsetTop + // viewport might have padding top, include it to avoid a scrollable viewport
          (isFirstItem ? viewportPaddingTop : 0) + selectedItemHalfHeight
        );
        const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom;
        contentWrapper.style.height = height + "px";
        viewport.scrollTop = contentTopToItemMiddle - topEdgeToTriggerMiddle + viewport.offsetTop;
      }
      contentWrapper.style.margin = `${CONTENT_MARGIN}px 0`;
      contentWrapper.style.minHeight = minContentHeight + "px";
      contentWrapper.style.maxHeight = availableHeight + "px";
      onPlaced?.();
      requestAnimationFrame(() => shouldExpandOnScrollRef.current = true);
    }
  }, [
    getItems,
    context.trigger,
    context.valueNode,
    contentWrapper,
    content,
    viewport,
    selectedItem,
    selectedItemText,
    context.dir,
    onPlaced
  ]);
  useLayoutEffect2(() => position(), [position]);
  const [contentZIndex, setContentZIndex] = React131.useState();
  useLayoutEffect2(() => {
    if (content)
      setContentZIndex(window.getComputedStyle(content).zIndex);
  }, [content]);
  const handleScrollButtonChange = React131.useCallback(
    (node) => {
      if (node && shouldRepositionRef.current === true) {
        position();
        focusSelectedItem?.();
        shouldRepositionRef.current = false;
      }
    },
    [position, focusSelectedItem]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    SelectViewportProvider,
    {
      scope: __scopeSelect,
      contentWrapper,
      shouldExpandOnScrollRef,
      onScrollButtonChange: handleScrollButtonChange,
      children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
        "div",
        {
          ref: setContentWrapper,
          style: {
            display: "flex",
            flexDirection: "column",
            position: "fixed",
            zIndex: contentZIndex
          },
          children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
            Primitive9.div,
            {
              ...popperProps,
              ref: composedRefs,
              style: {
                // When we get the height of the content, it includes borders. If we were to set
                // the height without having `boxSizing: 'border-box'` it would be too big.
                boxSizing: "border-box",
                // We need to ensure the content doesn't get taller than the wrapper
                maxHeight: "100%",
                ...popperProps.style
              }
            }
          )
        }
      )
    }
  );
});
SelectItemAlignedPosition.displayName = ITEM_ALIGNED_POSITION_NAME;
var POPPER_POSITION_NAME = "SelectPopperPosition";
var SelectPopperPosition = React131.forwardRef((props, forwardedRef) => {
  const {
    __scopeSelect,
    align = "start",
    collisionPadding = CONTENT_MARGIN,
    ...popperProps
  } = props;
  const popperScope = usePopperScope4(__scopeSelect);
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    Content6,
    {
      ...popperScope,
      ...popperProps,
      ref: forwardedRef,
      align,
      collisionPadding,
      style: {
        // Ensure border-box for floating-ui calculations
        boxSizing: "border-box",
        ...popperProps.style,
        // re-namespace exposed content custom properties
        ...{
          "--radix-select-content-transform-origin": "var(--radix-popper-transform-origin)",
          "--radix-select-content-available-width": "var(--radix-popper-available-width)",
          "--radix-select-content-available-height": "var(--radix-popper-available-height)",
          "--radix-select-trigger-width": "var(--radix-popper-anchor-width)",
          "--radix-select-trigger-height": "var(--radix-popper-anchor-height)"
        }
      }
    }
  );
});
SelectPopperPosition.displayName = POPPER_POSITION_NAME;
var [SelectViewportProvider, useSelectViewportContext] = createSelectContext(CONTENT_NAME11, {});
var VIEWPORT_NAME = "SelectViewport";
var SelectViewport = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, nonce, ...viewportProps } = props;
    const contentContext = useSelectContentContext(VIEWPORT_NAME, __scopeSelect);
    const viewportContext = useSelectViewportContext(VIEWPORT_NAME, __scopeSelect);
    const composedRefs = useComposedRefs(forwardedRef, contentContext.onViewportChange);
    const prevScrollTopRef = React131.useRef(0);
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(import_jsx_runtime59.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
        "style",
        {
          dangerouslySetInnerHTML: {
            __html: `[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}`
          },
          nonce
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Collection4.Slot, { scope: __scopeSelect, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
        Primitive9.div,
        {
          "data-radix-select-viewport": "",
          role: "presentation",
          ...viewportProps,
          ref: composedRefs,
          style: {
            // we use position: 'relative' here on the `viewport` so that when we call
            // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport
            // (independent of the scrollUpButton).
            position: "relative",
            flex: 1,
            // Viewport should only be scrollable in the vertical direction.
            // This won't work in vertical writing modes, so we'll need to
            // revisit this if/when that is supported
            // https://developer.chrome.com/blog/vertical-form-controls
            overflow: "hidden auto",
            ...viewportProps.style
          },
          onScroll: composeEventHandlers9(viewportProps.onScroll, (event) => {
            const viewport = event.currentTarget;
            const { contentWrapper, shouldExpandOnScrollRef } = viewportContext;
            if (shouldExpandOnScrollRef?.current && contentWrapper) {
              const scrolledBy = Math.abs(prevScrollTopRef.current - viewport.scrollTop);
              if (scrolledBy > 0) {
                const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
                const cssMinHeight = parseFloat(contentWrapper.style.minHeight);
                const cssHeight = parseFloat(contentWrapper.style.height);
                const prevHeight = Math.max(cssMinHeight, cssHeight);
                if (prevHeight < availableHeight) {
                  const nextHeight = prevHeight + scrolledBy;
                  const clampedNextHeight = Math.min(availableHeight, nextHeight);
                  const heightDiff = nextHeight - clampedNextHeight;
                  contentWrapper.style.height = clampedNextHeight + "px";
                  if (contentWrapper.style.bottom === "0px") {
                    viewport.scrollTop = heightDiff > 0 ? heightDiff : 0;
                    contentWrapper.style.justifyContent = "flex-end";
                  }
                }
              }
            }
            prevScrollTopRef.current = viewport.scrollTop;
          })
        }
      ) })
    ] });
  }
);
SelectViewport.displayName = VIEWPORT_NAME;
var GROUP_NAME4 = "SelectGroup";
var [SelectGroupContextProvider, useSelectGroupContext] = createSelectContext(GROUP_NAME4);
var SelectGroup = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...groupProps } = props;
    const groupId = useId();
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SelectGroupContextProvider, { scope: __scopeSelect, id: groupId, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.div, { role: "group", "aria-labelledby": groupId, ...groupProps, ref: forwardedRef }) });
  }
);
SelectGroup.displayName = GROUP_NAME4;
var LABEL_NAME3 = "SelectLabel";
var SelectLabel = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...labelProps } = props;
    const groupContext = useSelectGroupContext(LABEL_NAME3, __scopeSelect);
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.div, { id: groupContext.id, ...labelProps, ref: forwardedRef });
  }
);
SelectLabel.displayName = LABEL_NAME3;
var ITEM_NAME4 = "SelectItem";
var [SelectItemContextProvider, useSelectItemContext] = createSelectContext(ITEM_NAME4);
var SelectItem = React131.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeSelect,
      value,
      disabled = false,
      textValue: textValueProp,
      ...itemProps
    } = props;
    const context = useSelectContext(ITEM_NAME4, __scopeSelect);
    const contentContext = useSelectContentContext(ITEM_NAME4, __scopeSelect);
    const isSelected = context.value === value;
    const [textValue, setTextValue] = React131.useState(textValueProp ?? "");
    const [isFocused, setIsFocused] = React131.useState(false);
    const composedRefs = useComposedRefs(
      forwardedRef,
      (node) => contentContext.itemRefCallback?.(node, value, disabled)
    );
    const textId = useId();
    const pointerTypeRef = React131.useRef("touch");
    const handleSelect = () => {
      if (!disabled) {
        context.onValueChange(value);
        context.onOpenChange(false);
      }
    };
    if (value === "") {
      throw new Error(
        "A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder."
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
      SelectItemContextProvider,
      {
        scope: __scopeSelect,
        value,
        disabled,
        textId,
        isSelected,
        onItemTextChange: React131.useCallback((node) => {
          setTextValue((prevTextValue) => prevTextValue || (node?.textContent ?? "").trim());
        }, []),
        children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          Collection4.ItemSlot,
          {
            scope: __scopeSelect,
            value,
            disabled,
            textValue,
            children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
              Primitive9.div,
              {
                role: "option",
                "aria-labelledby": textId,
                "data-highlighted": isFocused ? "" : void 0,
                "aria-selected": isSelected && isFocused,
                "data-state": isSelected ? "checked" : "unchecked",
                "aria-disabled": disabled || void 0,
                "data-disabled": disabled ? "" : void 0,
                tabIndex: disabled ? void 0 : -1,
                ...itemProps,
                ref: composedRefs,
                onFocus: composeEventHandlers9(itemProps.onFocus, () => setIsFocused(true)),
                onBlur: composeEventHandlers9(itemProps.onBlur, () => setIsFocused(false)),
                onClick: composeEventHandlers9(itemProps.onClick, () => {
                  if (pointerTypeRef.current !== "mouse")
                    handleSelect();
                }),
                onPointerUp: composeEventHandlers9(itemProps.onPointerUp, () => {
                  if (pointerTypeRef.current === "mouse")
                    handleSelect();
                }),
                onPointerDown: composeEventHandlers9(itemProps.onPointerDown, (event) => {
                  pointerTypeRef.current = event.pointerType;
                }),
                onPointerMove: composeEventHandlers9(itemProps.onPointerMove, (event) => {
                  pointerTypeRef.current = event.pointerType;
                  if (disabled) {
                    contentContext.onItemLeave?.();
                  } else if (pointerTypeRef.current === "mouse") {
                    event.currentTarget.focus({ preventScroll: true });
                  }
                }),
                onPointerLeave: composeEventHandlers9(itemProps.onPointerLeave, (event) => {
                  if (event.currentTarget === document.activeElement) {
                    contentContext.onItemLeave?.();
                  }
                }),
                onKeyDown: composeEventHandlers9(itemProps.onKeyDown, (event) => {
                  const isTypingAhead = contentContext.searchRef?.current !== "";
                  if (isTypingAhead && event.key === " ")
                    return;
                  if (SELECTION_KEYS2.includes(event.key))
                    handleSelect();
                  if (event.key === " ")
                    event.preventDefault();
                })
              }
            )
          }
        )
      }
    );
  }
);
SelectItem.displayName = ITEM_NAME4;
var ITEM_TEXT_NAME = "SelectItemText";
var SelectItemText = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, className, style, ...itemTextProps } = props;
    const context = useSelectContext(ITEM_TEXT_NAME, __scopeSelect);
    const contentContext = useSelectContentContext(ITEM_TEXT_NAME, __scopeSelect);
    const itemContext = useSelectItemContext(ITEM_TEXT_NAME, __scopeSelect);
    const nativeOptionsContext = useSelectNativeOptionsContext(ITEM_TEXT_NAME, __scopeSelect);
    const [itemTextNode, setItemTextNode] = React131.useState(null);
    const composedRefs = useComposedRefs(
      forwardedRef,
      (node) => setItemTextNode(node),
      itemContext.onItemTextChange,
      (node) => contentContext.itemTextRefCallback?.(node, itemContext.value, itemContext.disabled)
    );
    const textContent = itemTextNode?.textContent;
    const nativeOption = React131.useMemo(
      () => /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("option", { value: itemContext.value, disabled: itemContext.disabled, children: textContent }, itemContext.value),
      [itemContext.disabled, itemContext.value, textContent]
    );
    const { onNativeOptionAdd, onNativeOptionRemove } = nativeOptionsContext;
    useLayoutEffect2(() => {
      onNativeOptionAdd(nativeOption);
      return () => onNativeOptionRemove(nativeOption);
    }, [onNativeOptionAdd, onNativeOptionRemove, nativeOption]);
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(import_jsx_runtime59.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.span, { id: itemContext.textId, ...itemTextProps, ref: composedRefs }),
      itemContext.isSelected && context.valueNode && !context.valueNodeHasChildren ? ReactDOM16.createPortal(itemTextProps.children, context.valueNode) : null
    ] });
  }
);
SelectItemText.displayName = ITEM_TEXT_NAME;
var ITEM_INDICATOR_NAME2 = "SelectItemIndicator";
var SelectItemIndicator = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...itemIndicatorProps } = props;
    const itemContext = useSelectItemContext(ITEM_INDICATOR_NAME2, __scopeSelect);
    return itemContext.isSelected ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.span, { "aria-hidden": true, ...itemIndicatorProps, ref: forwardedRef }) : null;
  }
);
SelectItemIndicator.displayName = ITEM_INDICATOR_NAME2;
var SCROLL_UP_BUTTON_NAME = "SelectScrollUpButton";
var SelectScrollUpButton = React131.forwardRef((props, forwardedRef) => {
  const contentContext = useSelectContentContext(SCROLL_UP_BUTTON_NAME, props.__scopeSelect);
  const viewportContext = useSelectViewportContext(SCROLL_UP_BUTTON_NAME, props.__scopeSelect);
  const [canScrollUp, setCanScrollUp] = React131.useState(false);
  const composedRefs = useComposedRefs(forwardedRef, viewportContext.onScrollButtonChange);
  useLayoutEffect2(() => {
    if (contentContext.viewport && contentContext.isPositioned) {
      let handleScroll22 = function() {
        const canScrollUp2 = viewport.scrollTop > 0;
        setCanScrollUp(canScrollUp2);
      };
      var handleScroll4 = handleScroll22;
      const viewport = contentContext.viewport;
      handleScroll22();
      viewport.addEventListener("scroll", handleScroll22);
      return () => viewport.removeEventListener("scroll", handleScroll22);
    }
  }, [contentContext.viewport, contentContext.isPositioned]);
  return canScrollUp ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    SelectScrollButtonImpl,
    {
      ...props,
      ref: composedRefs,
      onAutoScroll: () => {
        const { viewport, selectedItem } = contentContext;
        if (viewport && selectedItem) {
          viewport.scrollTop = viewport.scrollTop - selectedItem.offsetHeight;
        }
      }
    }
  ) : null;
});
SelectScrollUpButton.displayName = SCROLL_UP_BUTTON_NAME;
var SCROLL_DOWN_BUTTON_NAME = "SelectScrollDownButton";
var SelectScrollDownButton = React131.forwardRef((props, forwardedRef) => {
  const contentContext = useSelectContentContext(SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect);
  const viewportContext = useSelectViewportContext(SCROLL_DOWN_BUTTON_NAME, props.__scopeSelect);
  const [canScrollDown, setCanScrollDown] = React131.useState(false);
  const composedRefs = useComposedRefs(forwardedRef, viewportContext.onScrollButtonChange);
  useLayoutEffect2(() => {
    if (contentContext.viewport && contentContext.isPositioned) {
      let handleScroll22 = function() {
        const maxScroll = viewport.scrollHeight - viewport.clientHeight;
        const canScrollDown2 = Math.ceil(viewport.scrollTop) < maxScroll;
        setCanScrollDown(canScrollDown2);
      };
      var handleScroll4 = handleScroll22;
      const viewport = contentContext.viewport;
      handleScroll22();
      viewport.addEventListener("scroll", handleScroll22);
      return () => viewport.removeEventListener("scroll", handleScroll22);
    }
  }, [contentContext.viewport, contentContext.isPositioned]);
  return canScrollDown ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    SelectScrollButtonImpl,
    {
      ...props,
      ref: composedRefs,
      onAutoScroll: () => {
        const { viewport, selectedItem } = contentContext;
        if (viewport && selectedItem) {
          viewport.scrollTop = viewport.scrollTop + selectedItem.offsetHeight;
        }
      }
    }
  ) : null;
});
SelectScrollDownButton.displayName = SCROLL_DOWN_BUTTON_NAME;
var SelectScrollButtonImpl = React131.forwardRef((props, forwardedRef) => {
  const { __scopeSelect, onAutoScroll, ...scrollIndicatorProps } = props;
  const contentContext = useSelectContentContext("SelectScrollButton", __scopeSelect);
  const autoScrollTimerRef = React131.useRef(null);
  const getItems = useCollection4(__scopeSelect);
  const clearAutoScrollTimer = React131.useCallback(() => {
    if (autoScrollTimerRef.current !== null) {
      window.clearInterval(autoScrollTimerRef.current);
      autoScrollTimerRef.current = null;
    }
  }, []);
  React131.useEffect(() => {
    return () => clearAutoScrollTimer();
  }, [clearAutoScrollTimer]);
  useLayoutEffect2(() => {
    const activeItem = getItems().find((item) => item.ref.current === document.activeElement);
    activeItem?.ref.current?.scrollIntoView({ block: "nearest" });
  }, [getItems]);
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    Primitive9.div,
    {
      "aria-hidden": true,
      ...scrollIndicatorProps,
      ref: forwardedRef,
      style: { flexShrink: 0, ...scrollIndicatorProps.style },
      onPointerDown: composeEventHandlers9(scrollIndicatorProps.onPointerDown, () => {
        if (autoScrollTimerRef.current === null) {
          autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
        }
      }),
      onPointerMove: composeEventHandlers9(scrollIndicatorProps.onPointerMove, () => {
        contentContext.onItemLeave?.();
        if (autoScrollTimerRef.current === null) {
          autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
        }
      }),
      onPointerLeave: composeEventHandlers9(scrollIndicatorProps.onPointerLeave, () => {
        clearAutoScrollTimer();
      })
    }
  );
});
var SEPARATOR_NAME3 = "SelectSeparator";
var SelectSeparator = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...separatorProps } = props;
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Primitive9.div, { "aria-hidden": true, ...separatorProps, ref: forwardedRef });
  }
);
SelectSeparator.displayName = SEPARATOR_NAME3;
var ARROW_NAME9 = "SelectArrow";
var SelectArrow = React131.forwardRef(
  (props, forwardedRef) => {
    const { __scopeSelect, ...arrowProps } = props;
    const popperScope = usePopperScope4(__scopeSelect);
    const context = useSelectContext(ARROW_NAME9, __scopeSelect);
    const contentContext = useSelectContentContext(ARROW_NAME9, __scopeSelect);
    return context.open && contentContext.position === "popper" ? /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Arrow8, { ...popperScope, ...arrowProps, ref: forwardedRef }) : null;
  }
);
SelectArrow.displayName = ARROW_NAME9;
function shouldShowPlaceholder(value) {
  return value === "" || value === void 0;
}
var BubbleSelect = React131.forwardRef(
  (props, forwardedRef) => {
    const { value, ...selectProps } = props;
    const ref = React131.useRef(null);
    const composedRefs = useComposedRefs(forwardedRef, ref);
    const prevValue = usePrevious(value);
    React131.useEffect(() => {
      const select = ref.current;
      const selectProto = window.HTMLSelectElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(
        selectProto,
        "value"
      );
      const setValue = descriptor.set;
      if (prevValue !== value && setValue) {
        const event = new Event("change", { bubbles: true });
        setValue.call(select, value);
        select.dispatchEvent(event);
      }
    }, [prevValue, value]);
    return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(VisuallyHidden2, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)("select", { ...selectProps, ref: composedRefs, defaultValue: value }) });
  }
);
BubbleSelect.displayName = "BubbleSelect";
function useTypeaheadSearch(onSearchChange) {
  const handleSearchChange = useCallbackRef(onSearchChange);
  const searchRef = React131.useRef("");
  const timerRef = React131.useRef(0);
  const handleTypeaheadSearch = React131.useCallback(
    (key) => {
      const search3 = searchRef.current + key;
      handleSearchChange(search3);
      (function updateSearch(value) {
        searchRef.current = value;
        window.clearTimeout(timerRef.current);
        if (value !== "")
          timerRef.current = window.setTimeout(() => updateSearch(""), 1e3);
      })(search3);
    },
    [handleSearchChange]
  );
  const resetTypeahead = React131.useCallback(() => {
    searchRef.current = "";
    window.clearTimeout(timerRef.current);
  }, []);
  React131.useEffect(() => {
    return () => window.clearTimeout(timerRef.current);
  }, []);
  return [searchRef, handleTypeaheadSearch, resetTypeahead];
}
function findNextItem(items, search3, currentItem) {
  const isRepeated = search3.length > 1 && Array.from(search3).every((char) => char === search3[0]);
  const normalizedSearch = isRepeated ? search3[0] : search3;
  const currentItemIndex = currentItem ? items.indexOf(currentItem) : -1;
  let wrappedItems = wrapArray3(items, Math.max(currentItemIndex, 0));
  const excludeCurrentItem = normalizedSearch.length === 1;
  if (excludeCurrentItem)
    wrappedItems = wrappedItems.filter((v5) => v5 !== currentItem);
  const nextItem = wrappedItems.find(
    (item) => item.textValue.toLowerCase().startsWith(normalizedSearch.toLowerCase())
  );
  return nextItem !== currentItem ? nextItem : void 0;
}
function wrapArray3(array, startIndex) {
  return array.map((_2, index2) => array[(startIndex + index2) % array.length]);
}
var Root28 = Select;
var Trigger5 = SelectTrigger;
var Value = SelectValue;
var Icon2 = SelectIcon;
var Portal10 = SelectPortal;
var Content25 = SelectContent;
var Viewport = SelectViewport;
var Label5 = SelectLabel;
var Item3 = SelectItem;
var ItemText = SelectItemText;
var ItemIndicator3 = SelectItemIndicator;
var ScrollUpButton = SelectScrollUpButton;
var ScrollDownButton = SelectScrollDownButton;
var Separator3 = SelectSeparator;

// src/components/ui/select.tsx
var Select2 = Root28;
var SelectValue2 = Value;
var SelectTrigger2 = React132.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  Trigger5,
  {
    ref,
    className: cn(
      "border-solid !bg-dropdown !shadow-sm transition-colors",
      "focus-visible:shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
      " hover:data-[state=closed]:!bg-interactive-accent hover:data-[state=closed]:!text-on-accent",
      // custom styles
      "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-border px-3 py-1 text-sm ring-offset-ring placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
      className
    ),
    ...props
  },
  children,
  /* @__PURE__ */ React132.createElement(Icon2, { asChild: true }, /* @__PURE__ */ React132.createElement(ChevronDown, { className: "h-4 w-4" }))
));
SelectTrigger2.displayName = Trigger5.displayName;
var SelectScrollUpButton2 = React132.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  ScrollUpButton,
  {
    ref,
    className: cn("flex cursor-default items-center justify-center py-1", className),
    ...props
  },
  /* @__PURE__ */ React132.createElement(ChevronUp, { className: "h-4 w-4" })
));
SelectScrollUpButton2.displayName = ScrollUpButton.displayName;
var SelectScrollDownButton2 = React132.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  ScrollDownButton,
  {
    ref,
    className: cn("flex cursor-default items-center justify-center py-1", className),
    ...props
  },
  /* @__PURE__ */ React132.createElement(ChevronDown, { className: "h-4 w-4" })
));
SelectScrollDownButton2.displayName = ScrollDownButton.displayName;
var SelectContent2 = React132.forwardRef(({ className, children, position = "popper", container, ...props }, ref) => /* @__PURE__ */ React132.createElement(Portal10, { container }, /* @__PURE__ */ React132.createElement(
  Content25,
  {
    ref,
    className: cn(
      "relative z-modal max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-primary text-normal  shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
      className
    ),
    position,
    ...props
  },
  /* @__PURE__ */ React132.createElement(SelectScrollUpButton2, null),
  /* @__PURE__ */ React132.createElement(
    Viewport,
    {
      className: cn(
        "p-1",
        position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
      )
    },
    children
  ),
  /* @__PURE__ */ React132.createElement(SelectScrollDownButton2, null)
)));
SelectContent2.displayName = Content25.displayName;
var SelectLabel2 = React132.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  Label5,
  {
    ref,
    className: cn("px-2 py-1.5 text-sm font-semibold", className),
    ...props
  }
));
SelectLabel2.displayName = Label5.displayName;
var SelectItem2 = React132.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  Item3,
  {
    ref,
    className: cn(
      "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-interactive-accent focus:text-on-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    ),
    ...props
  },
  /* @__PURE__ */ React132.createElement("span", { className: "absolute right-2 flex h-3.5 w-3.5 items-center justify-center" }, /* @__PURE__ */ React132.createElement(ItemIndicator3, null, /* @__PURE__ */ React132.createElement(Check, { className: "h-4 w-4" }))),
  /* @__PURE__ */ React132.createElement(ItemText, null, children)
));
SelectItem2.displayName = Item3.displayName;
var SelectSeparator2 = React132.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React132.createElement(
  Separator3,
  {
    ref,
    className: cn("-mx-1 my-1 h-px bg-primary-alt", className),
    ...props
  }
));
SelectSeparator2.displayName = Separator3.displayName;

// src/components/ui/checkbox.tsx
var React137 = __toESM(require_react());

// node_modules/@radix-ui/react-checkbox/dist/index.mjs
var React136 = __toESM(require_react(), 1);

// node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
var React133 = __toESM(require_react(), 1);
function setRef11(ref, value) {
  if (typeof ref === "function") {
    return ref(value);
  } else if (ref !== null && ref !== void 0) {
    ref.current = value;
  }
}
function composeRefs11(...refs) {
  return (node) => {
    let hasCleanup = false;
    const cleanups = refs.map((ref) => {
      const cleanup = setRef11(ref, node);
      if (!hasCleanup && typeof cleanup == "function") {
        hasCleanup = true;
      }
      return cleanup;
    });
    if (hasCleanup) {
      return () => {
        for (let i3 = 0; i3 < cleanups.length; i3++) {
          const cleanup = cleanups[i3];
          if (typeof cleanup == "function") {
            cleanup();
          } else {
            setRef11(refs[i3], null);
          }
        }
      };
    }
  };
}
function useComposedRefs9(...refs) {
  return React133.useCallback(composeRefs11(...refs), refs);
}

// node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/primitive/dist/index.mjs
function composeEventHandlers10(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
  return function handleEvent(event) {
    originalEventHandler?.(event);
    if (checkForDefaultPrevented === false || !event.defaultPrevented) {
      return ourEventHandler?.(event);
    }
  };
}

// node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-primitive/dist/index.mjs
var React135 = __toESM(require_react(), 1);
var ReactDOM17 = __toESM(require_react_dom(), 1);

// node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-slot/dist/index.mjs
var React134 = __toESM(require_react(), 1);
var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
var Slot10 = React134.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  const childrenArray = React134.Children.toArray(children);
  const slottable = childrenArray.find(isSlottable10);
  if (slottable) {
    const newElement = slottable.props.children;
    const newChildren = childrenArray.map((child) => {
      if (child === slottable) {
        if (React134.Children.count(newElement) > 1)
          return React134.Children.only(null);
        return React134.isValidElement(newElement) ? newElement.props.children : null;
      } else {
        return child;
      }
    });
    return /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(SlotClone10, { ...slotProps, ref: forwardedRef, children: React134.isValidElement(newElement) ? React134.cloneElement(newElement, void 0, newChildren) : null });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(SlotClone10, { ...slotProps, ref: forwardedRef, children });
});
Slot10.displayName = "Slot";
var SlotClone10 = React134.forwardRef((props, forwardedRef) => {
  const { children, ...slotProps } = props;
  if (React134.isValidElement(children)) {
    const childrenRef = getElementRef11(children);
    return React134.cloneElement(children, {
      ...mergeProps10(slotProps, children.props),
      // @ts-ignore
      ref: forwardedRef ? composeRefs11(forwardedRef, childrenRef) : childrenRef
    });
  }
  return React134.Children.count(children) > 1 ? React134.Children.only(null) : null;
});
SlotClone10.displayName = "SlotClone";
var Slottable10 = ({ children }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(import_jsx_runtime60.Fragment, { children });
};
function isSlottable10(child) {
  return React134.isValidElement(child) && child.type === Slottable10;
}
function mergeProps10(slotProps, childProps) {
  const overrideProps = { ...childProps };
  for (const propName in childProps) {
    const slotPropValue = slotProps[propName];
    const childPropValue = childProps[propName];
    const isHandler = /^on[A-Z]/.test(propName);
    if (isHandler) {
      if (slotPropValue && childPropValue) {
        overrideProps[propName] = (...args) => {
          childPropValue(...args);
          slotPropValue(...args);
        };
      } else if (slotPropValue) {
        overrideProps[propName] = slotPropValue;
      }
    } else if (propName === "style") {
      overrideProps[propName] = { ...slotPropValue, ...childPropValue };
    } else if (propName === "className") {
      overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
    }
  }
  return { ...slotProps, ...overrideProps };
}
function getElementRef11(element) {
  let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
  let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.ref;
  }
  getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
  mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
  if (mayWarn) {
    return element.props.ref;
  }
  return element.props.ref || element.ref;
}

// node_modules/@radix-ui/react-checkbox/node_modules/@radix-ui/react-primitive/dist/index.mjs
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var NODES10 = [
  "a",
  "button",
  "div",
  "form",
  "h2",
  "h3",
  "img",
  "input",
  "label",
  "li",
  "nav",
  "ol",
  "p",
  "span",
  "svg",
  "ul"
];
var Primitive10 = NODES10.reduce((primitive, node) => {
  const Node3 = React135.forwardRef((props, forwardedRef) => {
    const { asChild, ...primitiveProps } = props;
    const Comp = asChild ? Slot10 : node;
    if (typeof window !== "undefined") {
      window[Symbol.for("radix-ui")] = true;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(Comp, { ...primitiveProps, ref: forwardedRef });
  });
  Node3.displayName = `Primitive.${node}`;
  return { ...primitive, [node]: Node3 };
}, {});

// node_modules/@radix-ui/react-checkbox/dist/index.mjs
var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
"use client";
var CHECKBOX_NAME = "Checkbox";
var [createCheckboxContext, createCheckboxScope] = createContextScope(CHECKBOX_NAME);
var [CheckboxProvider, useCheckboxContext] = createCheckboxContext(CHECKBOX_NAME);
var Checkbox = React136.forwardRef(
  (props, forwardedRef) => {
    const {
      __scopeCheckbox,
      name,
      checked: checkedProp,
      defaultChecked,
      required,
      disabled,
      value = "on",
      onCheckedChange,
      form,
      ...checkboxProps
    } = props;
    const [button, setButton] = React136.useState(null);
    const composedRefs = useComposedRefs9(forwardedRef, (node) => setButton(node));
    const hasConsumerStoppedPropagationRef = React136.useRef(false);
    const isFormControl = button ? form || !!button.closest("form") : true;
    const [checked = false, setChecked] = useControllableState({
      prop: checkedProp,
      defaultProp: defaultChecked,
      onChange: onCheckedChange
    });
    const initialCheckedStateRef = React136.useRef(checked);
    React136.useEffect(() => {
      const form2 = button?.form;
      if (form2) {
        const reset = () => setChecked(initialCheckedStateRef.current);
        form2.addEventListener("reset", reset);
        return () => form2.removeEventListener("reset", reset);
      }
    }, [button, setChecked]);
    return /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(CheckboxProvider, { scope: __scopeCheckbox, state: checked, disabled, children: [
      /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
        Primitive10.button,
        {
          type: "button",
          role: "checkbox",
          "aria-checked": isIndeterminate2(checked) ? "mixed" : checked,
          "aria-required": required,
          "data-state": getState4(checked),
          "data-disabled": disabled ? "" : void 0,
          disabled,
          value,
          ...checkboxProps,
          ref: composedRefs,
          onKeyDown: composeEventHandlers10(props.onKeyDown, (event) => {
            if (event.key === "Enter")
              event.preventDefault();
          }),
          onClick: composeEventHandlers10(props.onClick, (event) => {
            setChecked((prevChecked) => isIndeterminate2(prevChecked) ? true : !prevChecked);
            if (isFormControl) {
              hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
              if (!hasConsumerStoppedPropagationRef.current)
                event.stopPropagation();
            }
          })
        }
      ),
      isFormControl && /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
        BubbleInput2,
        {
          control: button,
          bubbles: !hasConsumerStoppedPropagationRef.current,
          name,
          value,
          checked,
          required,
          disabled,
          form,
          style: { transform: "translateX(-100%)" },
          defaultChecked: isIndeterminate2(defaultChecked) ? false : defaultChecked
        }
      )
    ] });
  }
);
Checkbox.displayName = CHECKBOX_NAME;
var INDICATOR_NAME2 = "CheckboxIndicator";
var CheckboxIndicator = React136.forwardRef(
  (props, forwardedRef) => {
    const { __scopeCheckbox, forceMount, ...indicatorProps } = props;
    const context = useCheckboxContext(INDICATOR_NAME2, __scopeCheckbox);
    return /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Presence, { present: forceMount || isIndeterminate2(context.state) || context.state === true, children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
      Primitive10.span,
      {
        "data-state": getState4(context.state),
        "data-disabled": context.disabled ? "" : void 0,
        ...indicatorProps,
        ref: forwardedRef,
        style: { pointerEvents: "none", ...props.style }
      }
    ) });
  }
);
CheckboxIndicator.displayName = INDICATOR_NAME2;
var BubbleInput2 = (props) => {
  const { control, checked, bubbles = true, defaultChecked, ...inputProps } = props;
  const ref = React136.useRef(null);
  const prevChecked = usePrevious(checked);
  const controlSize = useSize(control);
  React136.useEffect(() => {
    const input = ref.current;
    const inputProto = window.HTMLInputElement.prototype;
    const descriptor = Object.getOwnPropertyDescriptor(inputProto, "checked");
    const setChecked = descriptor.set;
    if (prevChecked !== checked && setChecked) {
      const event = new Event("click", { bubbles });
      input.indeterminate = isIndeterminate2(checked);
      setChecked.call(input, isIndeterminate2(checked) ? false : checked);
      input.dispatchEvent(event);
    }
  }, [prevChecked, checked, bubbles]);
  const defaultCheckedRef = React136.useRef(isIndeterminate2(checked) ? false : checked);
  return /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
    "input",
    {
      type: "checkbox",
      "aria-hidden": true,
      defaultChecked: defaultChecked ?? defaultCheckedRef.current,
      ...inputProps,
      tabIndex: -1,
      ref,
      style: {
        ...props.style,
        ...controlSize,
        position: "absolute",
        pointerEvents: "none",
        opacity: 0,
        margin: 0
      }
    }
  );
};
function isIndeterminate2(checked) {
  return checked === "indeterminate";
}
function getState4(checked) {
  return isIndeterminate2(checked) ? "indeterminate" : checked ? "checked" : "unchecked";
}
var Root14 = Checkbox;
var Indicator = CheckboxIndicator;

// src/components/ui/checkbox.tsx
var Checkbox2 = React137.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React137.createElement(
  Root14,
  {
    ref,
    className: cn(
      "p-0 border-solid !bg-transparent !shadow transition-colors",
      // custom styles
      "hover:!bg-interactive-accent hover:!text-on-accent data-[state=checked]:!bg-interactive-accent data-[state=checked]:!text-on-accent",
      // custom styles
      "peer h-4 w-4 shrink-0 rounded-sm border border-interactive-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-interactive-accent data-[state=checked]:text-on-accent",
      className
    ),
    ...props
  },
  /* @__PURE__ */ React137.createElement(Indicator, { className: cn("flex items-center justify-center text-current") }, /* @__PURE__ */ React137.createElement(Check, { className: "h-4 w-4" }))
));
Checkbox2.displayName = Root14.displayName;

// src/settings/v2/components/ModelAddDialog.tsx
var FormField = ({
  label,
  required = false,
  error = false,
  description,
  errorMessage = "This field is required",
  children
}) => {
  return /* @__PURE__ */ import_react35.default.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ import_react35.default.createElement(Label4, { className: error ? "text-error" : "" }, label, " ", required && /* @__PURE__ */ import_react35.default.createElement("span", { className: "text-error" }, "*")), children, error && /* @__PURE__ */ import_react35.default.createElement("p", { className: "text-xs text-error" }, errorMessage), description && /* @__PURE__ */ import_react35.default.createElement("p", { className: "text-sm text-muted" }, description));
};
var ModelAddDialog = ({
  open,
  onOpenChange,
  onAdd,
  ping,
  isEmbeddingModel = false
}) => {
  const { modalContainer } = useTab();
  const settings = getSettings();
  const defaultProvider = isEmbeddingModel ? "openai" /* OPENAI */ : "openai" /* OPENAI */;
  const [dialogElement, setDialogElement] = (0, import_react35.useState)(null);
  const [isOpen, setIsOpen] = (0, import_react35.useState)(false);
  const [isVerifying, setIsVerifying] = (0, import_react35.useState)(false);
  const [errors2, setErrors] = (0, import_react35.useState)({
    name: false,
    instanceName: false,
    deploymentName: false,
    embeddingDeploymentName: false,
    apiVersion: false
  });
  const setError = (field, value) => {
    setErrors((prev) => ({ ...prev, [field]: value }));
  };
  const clearErrors = () => {
    setErrors({
      name: false,
      instanceName: false,
      deploymentName: false,
      embeddingDeploymentName: false,
      apiVersion: false
    });
  };
  const validateFields = () => {
    let isValid2 = true;
    const newErrors = { ...errors2 };
    newErrors.name = !model.name;
    if (!model.name)
      isValid2 = false;
    if (model.provider === "azure openai" /* AZURE_OPENAI */) {
      newErrors.instanceName = !model.azureOpenAIApiInstanceName;
      newErrors.apiVersion = !model.azureOpenAIApiVersion;
      if (isEmbeddingModel) {
        newErrors.embeddingDeploymentName = !model.azureOpenAIApiEmbeddingDeploymentName;
        if (!model.azureOpenAIApiEmbeddingDeploymentName)
          isValid2 = false;
      } else {
        newErrors.deploymentName = !model.azureOpenAIApiDeploymentName;
        if (!model.azureOpenAIApiDeploymentName)
          isValid2 = false;
      }
      if (!model.azureOpenAIApiInstanceName || !model.azureOpenAIApiVersion) {
        isValid2 = false;
      }
    }
    setErrors(newErrors);
    return isValid2;
  };
  const getDefaultApiKey = (provider) => {
    return settings[ProviderSettingsKeyMap[provider]] || "";
  };
  const getInitialModel = (provider = defaultProvider) => {
    const baseModel = {
      name: "",
      provider,
      enabled: true,
      isBuiltIn: false,
      baseUrl: "",
      apiKey: getDefaultApiKey(provider),
      isEmbeddingModel
    };
    if (!isEmbeddingModel) {
      return {
        ...baseModel,
        temperature: 0.1,
        context: 1e3,
        stream: true
      };
    }
    return baseModel;
  };
  const [model, setModel] = (0, import_react35.useState)(getInitialModel());
  const [providerInfo, setProviderInfo] = (0, import_react35.useState)(
    getProviderInfo(defaultProvider)
  );
  const isFormValid = () => {
    return Boolean(model.name && model.provider);
  };
  const isButtonDisabled = () => {
    return isVerifying || !isFormValid();
  };
  const handleAdd = () => {
    if (!validateFields()) {
      new import_obsidian44.Notice("Please fill in all required fields");
      return;
    }
    onAdd(model);
    onOpenChange(false);
    setModel(getInitialModel());
    clearErrors();
  };
  const handleProviderChange = (provider) => {
    setProviderInfo(getProviderInfo(provider));
    setModel({
      ...model,
      provider,
      apiKey: getDefaultApiKey(provider),
      ...provider === "azure openai" /* AZURE_OPENAI */ ? { openAIOrgId: settings.openAIOrgId } : {},
      ...provider === "azure openai" /* AZURE_OPENAI */ ? {
        azureInstanceName: settings.azureOpenAIApiInstanceName,
        azureDeploymentName: settings.azureOpenAIApiDeploymentName,
        azureApiVersion: settings.azureOpenAIApiVersion,
        azureOpenAIApiEmbeddingDeploymentName: settings.azureOpenAIApiEmbeddingDeploymentName
      } : {}
    });
  };
  const handleOpenChange = (open2) => {
    if (!open2) {
      setModel(getInitialModel());
      clearErrors();
      setIsOpen(false);
    }
    onOpenChange(open2);
  };
  const handleVerify = async () => {
    if (!validateFields()) {
      new import_obsidian44.Notice("Please fill in all required fields");
      return;
    }
    setIsVerifying(true);
    try {
      await ping(model);
      new import_obsidian44.Notice("Model verification successful!");
    } catch (err) {
      console.error(err);
      const errStr = err2String(err);
      new import_obsidian44.Notice("Model verification failed: " + errStr);
    } finally {
      setIsVerifying(false);
    }
  };
  const renderProviderSpecificFields = () => {
    const fields = () => {
      switch (model.provider) {
        case "openai" /* OPENAI */:
          return /* @__PURE__ */ import_react35.default.createElement(
            FormField,
            {
              label: "OpenAI Organization ID",
              description: "Enter OpenAI Organization ID if applicable"
            },
            /* @__PURE__ */ import_react35.default.createElement(
              Input,
              {
                type: "text",
                placeholder: "Enter OpenAI Organization ID if applicable",
                value: model.openAIOrgId || "",
                onChange: (e3) => setModel({ ...model, openAIOrgId: e3.target.value })
              }
            )
          );
        case "azure openai" /* AZURE_OPENAI */:
          return /* @__PURE__ */ import_react35.default.createElement(import_react35.default.Fragment, null, /* @__PURE__ */ import_react35.default.createElement(
            FormField,
            {
              label: "Instance Name",
              required: true,
              error: errors2.instanceName,
              errorMessage: "Instance name is required"
            },
            /* @__PURE__ */ import_react35.default.createElement(
              Input,
              {
                type: "text",
                placeholder: "Enter Azure OpenAI API Instance Name",
                value: model.azureOpenAIApiInstanceName || "",
                onChange: (e3) => {
                  setModel({ ...model, azureOpenAIApiInstanceName: e3.target.value });
                  setError("instanceName", false);
                }
              }
            )
          ), !isEmbeddingModel ? /* @__PURE__ */ import_react35.default.createElement(
            FormField,
            {
              label: "Deployment Name",
              required: true,
              error: errors2.deploymentName,
              errorMessage: "Deployment name is required",
              description: "This is your actual model, no need to pass a model name separately."
            },
            /* @__PURE__ */ import_react35.default.createElement(
              Input,
              {
                type: "text",
                placeholder: "Enter Azure OpenAI API Deployment Name",
                value: model.azureOpenAIApiDeploymentName || "",
                onChange: (e3) => {
                  setModel({ ...model, azureOpenAIApiDeploymentName: e3.target.value });
                  setError("deploymentName", false);
                }
              }
            )
          ) : /* @__PURE__ */ import_react35.default.createElement(
            FormField,
            {
              label: "Embedding Deployment Name",
              required: true,
              error: errors2.embeddingDeploymentName,
              errorMessage: "Embedding deployment name is required"
            },
            /* @__PURE__ */ import_react35.default.createElement(
              Input,
              {
                type: "text",
                placeholder: "Enter Azure OpenAI API Embedding Deployment Name",
                value: model.azureOpenAIApiEmbeddingDeploymentName || "",
                onChange: (e3) => {
                  setModel({ ...model, azureOpenAIApiEmbeddingDeploymentName: e3.target.value });
                  setError("embeddingDeploymentName", false);
                }
              }
            )
          ), /* @__PURE__ */ import_react35.default.createElement(
            FormField,
            {
              label: "API Version",
              required: true,
              error: errors2.apiVersion,
              errorMessage: "API version is required"
            },
            /* @__PURE__ */ import_react35.default.createElement(
              Input,
              {
                type: "text",
                placeholder: "Enter Azure OpenAI API Version",
                value: model.azureOpenAIApiVersion || "",
                onChange: (e3) => {
                  setModel({ ...model, azureOpenAIApiVersion: e3.target.value });
                  setError("apiVersion", false);
                }
              }
            )
          ));
        default:
          return null;
      }
    };
    const content = fields();
    if (!content)
      return null;
    return /* @__PURE__ */ import_react35.default.createElement(
      Collapsible2,
      {
        open: isOpen,
        onOpenChange: setIsOpen,
        className: "space-y-2 border rounded-lg pt-4"
      },
      /* @__PURE__ */ import_react35.default.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ import_react35.default.createElement(Label4, null, "Additional ", getProviderLabel(model.provider), " Settings"), /* @__PURE__ */ import_react35.default.createElement(CollapsibleTrigger2, { asChild: true }, /* @__PURE__ */ import_react35.default.createElement(Button, { variant: "ghost", size: "sm", className: "w-9 p-0" }, /* @__PURE__ */ import_react35.default.createElement(ChevronDown, { className: "h-4 w-4" }), /* @__PURE__ */ import_react35.default.createElement("span", { className: "sr-only" }, "Toggle")))),
      /* @__PURE__ */ import_react35.default.createElement(CollapsibleContent2, { className: "space-y-4 max-h-[200px] overflow-y-auto pl-0.5 pr-2 pb-0.5" }, content)
    );
  };
  const getPlaceholderUrl = () => {
    if (model.provider !== "azure openai" /* AZURE_OPENAI */) {
      return providerInfo.host;
    }
    const instanceName = model.azureOpenAIApiInstanceName || "[instance]";
    const deploymentName = isEmbeddingModel ? model.azureOpenAIApiEmbeddingDeploymentName || "[deployment]" : model.azureOpenAIApiDeploymentName || "[deployment]";
    const apiVersion = model.azureOpenAIApiVersion || "[api-version]";
    const endpoint = isEmbeddingModel ? "embeddings" : "chat/completions";
    return `https://${instanceName}.openai.azure.com/openai/deployments/${deploymentName}/${endpoint}?api-version=${apiVersion}`;
  };
  return /* @__PURE__ */ import_react35.default.createElement(Dialog2, { open, onOpenChange: handleOpenChange }, /* @__PURE__ */ import_react35.default.createElement(
    DialogContent2,
    {
      className: "sm:max-w-[425px]",
      container: modalContainer,
      ref: (el) => setDialogElement(el)
    },
    /* @__PURE__ */ import_react35.default.createElement(DialogHeader, null, /* @__PURE__ */ import_react35.default.createElement(DialogTitle2, null, "Add Custom ", isEmbeddingModel ? "Embedding" : "Chat", " Model"), /* @__PURE__ */ import_react35.default.createElement(DialogDescription2, null, "Add a new model to your collection.")),
    /* @__PURE__ */ import_react35.default.createElement("div", { className: "space-y-4 py-4" }, /* @__PURE__ */ import_react35.default.createElement(
      FormField,
      {
        label: "Model Name",
        required: true,
        error: errors2.name,
        errorMessage: "Model name is required"
      },
      /* @__PURE__ */ import_react35.default.createElement(
        Input,
        {
          type: "text",
          placeholder: `Enter model name (e.g. ${isEmbeddingModel ? "text-embedding-3-small" : "gpt-4"})`,
          value: model.name,
          onChange: (e3) => {
            setModel({ ...model, name: e3.target.value });
            setError("name", false);
          }
        }
      )
    ), /* @__PURE__ */ import_react35.default.createElement(FormField, { label: "Provider" }, /* @__PURE__ */ import_react35.default.createElement(Select2, { value: model.provider, onValueChange: handleProviderChange }, /* @__PURE__ */ import_react35.default.createElement(SelectTrigger2, null, /* @__PURE__ */ import_react35.default.createElement(SelectValue2, { placeholder: "Select provider" })), /* @__PURE__ */ import_react35.default.createElement(SelectContent2, { container: dialogElement }, Object.values(
      isEmbeddingModel ? omit(EmbeddingModelProviders, ["COPILOT_PLUS", "COPILOT_PLUS_JINA"]) : ChatModelProviders
    ).map((provider) => /* @__PURE__ */ import_react35.default.createElement(SelectItem2, { key: provider, value: provider }, getProviderLabel(provider)))))), /* @__PURE__ */ import_react35.default.createElement(FormField, { label: "Base URL", description: "Leave it blank, unless you are using a proxy." }, /* @__PURE__ */ import_react35.default.createElement(
      Input,
      {
        type: "text",
        placeholder: getPlaceholderUrl() || "https://api.example.com/v1",
        value: model.baseUrl || "",
        onChange: (e3) => setModel({ ...model, baseUrl: e3.target.value })
      }
    )), /* @__PURE__ */ import_react35.default.createElement(FormField, { label: "API Key" }, /* @__PURE__ */ import_react35.default.createElement(
      PasswordInput,
      {
        placeholder: `Enter ${providerInfo.label} API Key`,
        value: model.apiKey || "",
        onChange: (value) => setModel({ ...model, apiKey: value })
      }
    ), providerInfo.keyManagementURL && /* @__PURE__ */ import_react35.default.createElement("p", { className: "text-xs text-muted" }, /* @__PURE__ */ import_react35.default.createElement("a", { href: providerInfo.keyManagementURL, target: "_blank", rel: "noopener noreferrer" }, "Get ", providerInfo.label, " API Key"))), renderProviderSpecificFields()),
    /* @__PURE__ */ import_react35.default.createElement("div", { className: "flex justify-end gap-4 items-center" }, /* @__PURE__ */ import_react35.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react35.default.createElement(
      Checkbox2,
      {
        id: "enable-cors",
        checked: model.enableCors || false,
        onCheckedChange: (checked) => setModel({ ...model, enableCors: checked })
      }
    ), /* @__PURE__ */ import_react35.default.createElement(Label4, { htmlFor: "enable-cors", className: "text-sm" }, "Enable CORS")), /* @__PURE__ */ import_react35.default.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ import_react35.default.createElement(Button, { variant: "outline", onClick: handleAdd, disabled: isButtonDisabled() }, "Add Model"), /* @__PURE__ */ import_react35.default.createElement(Button, { variant: "outline", onClick: handleVerify, disabled: isButtonDisabled() }, isVerifying ? /* @__PURE__ */ import_react35.default.createElement(import_react35.default.Fragment, null, /* @__PURE__ */ import_react35.default.createElement(LoaderCircle, { className: "mr-2 h-4 w-4 animate-spin" }), "Verify") : "Verify")))
  ));
};

// src/settings/v2/components/ModelTable.tsx
var import_react36 = __toESM(require_react());

// src/components/ui/table.tsx
var React139 = __toESM(require_react());
var Table = React139.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement("div", { className: "relative w-full overflow-auto" }, /* @__PURE__ */ React139.createElement(
    "table",
    {
      ref,
      className: cn("w-full caption-bottom text-sm border-collapse", className),
      ...props
    }
  ))
);
Table.displayName = "Table";
var TableHeader = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement("thead", { ref, className: cn("[&_tr]:border-b", className), ...props }));
TableHeader.displayName = "TableHeader";
var TableBody = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement("tbody", { ref, className: cn("[&_tr:last-child]:border-0", className), ...props }));
TableBody.displayName = "TableBody";
var TableFooter = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement(
  "tfoot",
  {
    ref,
    className: cn("border-t bg-primary-alt/50 font-medium [&>tr]:last:border-b-0", className),
    ...props
  }
));
TableFooter.displayName = "TableFooter";
var TableRow = React139.forwardRef(
  ({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement(
    "tr",
    {
      ref,
      className: cn(
        "border-b transition-colors hover:bg-primary-alt/50 data-[state=selected]:bg-primary-alt",
        className
      ),
      ...props
    }
  )
);
TableRow.displayName = "TableRow";
var TableHead = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement(
  "th",
  {
    ref,
    className: cn(
      "h-10 px-2 text-left align-middle font-medium text-muted [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    ),
    ...props
  }
));
TableHead.displayName = "TableHead";
var TableCell = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement(
  "td",
  {
    ref,
    className: cn(
      "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    ),
    ...props
  }
));
TableCell.displayName = "TableCell";
var TableCaption = React139.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ React139.createElement("caption", { ref, className: cn("mt-4 text-sm text-muted", className), ...props }));
TableCaption.displayName = "TableCaption";

// src/settings/v2/components/ModelTable.tsx
var ModelCard = ({ model, onEdit, onDelete, onUpdateModel }) => {
  const [isExpanded, setIsExpanded] = import_react36.default.useState(false);
  return /* @__PURE__ */ import_react36.default.createElement(Card, { className: "mb-2" }, /* @__PURE__ */ import_react36.default.createElement(CardHeader, { className: "p-3" }, /* @__PURE__ */ import_react36.default.createElement(
    "div",
    {
      className: "flex items-center justify-between cursor-pointer border-l-[0] border-r-[0] border-t-[0] border-b border-solid border-border pb-2",
      onClick: () => setIsExpanded(!isExpanded)
    },
    /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react36.default.createElement("div", { className: "w-3 h-3 flex items-center justify-center" }, isExpanded ? /* @__PURE__ */ import_react36.default.createElement(ChevronDown, { className: "h-3 w-3 stroke-[7]" }) : /* @__PURE__ */ import_react36.default.createElement(ChevronRight, { className: "h-3 w-3 stroke-[7]" })), /* @__PURE__ */ import_react36.default.createElement("div", null, /* @__PURE__ */ import_react36.default.createElement("div", { className: "font-medium" }, model.name), /* @__PURE__ */ import_react36.default.createElement("span", { className: "text-sm text-muted bg-secondary" }, getProviderLabel(model.provider)))),
    /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex items-center gap-2" }, onEdit && /* @__PURE__ */ import_react36.default.createElement(
      Button,
      {
        variant: "ghost",
        size: "icon",
        onClick: (e3) => {
          e3.stopPropagation();
          onEdit();
        }
      },
      /* @__PURE__ */ import_react36.default.createElement(Pencil, { className: "h-4 w-4" })
    ), onDelete && !model.core && /* @__PURE__ */ import_react36.default.createElement(
      Button,
      {
        variant: "ghost",
        size: "icon",
        onClick: (e3) => {
          e3.stopPropagation();
          onDelete();
        }
      },
      /* @__PURE__ */ import_react36.default.createElement(Trash2, { className: "h-4 w-4" })
    ))
  )), /* @__PURE__ */ import_react36.default.createElement(
    "div",
    {
      className: cn(
        "transition-all duration-300 ease-in-out",
        isExpanded ? "max-h-20 opacity-100" : "max-h-0 opacity-0 overflow-hidden"
      )
    },
    /* @__PURE__ */ import_react36.default.createElement(CardContent, { className: "p-3 pt-0" }, /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex justify-around" }, !model.isEmbeddingModel && /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react36.default.createElement("span", { className: "text-sm" }, "Enabled"), /* @__PURE__ */ import_react36.default.createElement(
      Checkbox2,
      {
        checked: model.enabled,
        onCheckedChange: (checked) => onUpdateModel({ ...model, enabled: checked })
      }
    )), /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react36.default.createElement("span", { className: "text-sm" }, "CORS"), /* @__PURE__ */ import_react36.default.createElement(
      Checkbox2,
      {
        checked: model.enableCors,
        onCheckedChange: (checked) => onUpdateModel({ ...model, enableCors: checked })
      }
    ))))
  ));
};
var ModelTable = ({
  models,
  onEdit,
  onDelete,
  onAdd,
  onUpdateModel,
  title
}) => {
  const isEmbeddingModel = models.length > 0 && models[0].isEmbeddingModel;
  return /* @__PURE__ */ import_react36.default.createElement("div", { className: "mb-4" }, /* @__PURE__ */ import_react36.default.createElement("div", { className: "hidden md:block" }, /* @__PURE__ */ import_react36.default.createElement(Table, null, /* @__PURE__ */ import_react36.default.createElement(TableHeader, null, /* @__PURE__ */ import_react36.default.createElement(TableRow, null, /* @__PURE__ */ import_react36.default.createElement(TableHead, null, "Model"), /* @__PURE__ */ import_react36.default.createElement(TableHead, null, "Provider"), !isEmbeddingModel && /* @__PURE__ */ import_react36.default.createElement(TableHead, { className: "text-center" }, "Enable"), /* @__PURE__ */ import_react36.default.createElement(TableHead, { className: "text-center" }, "CORS"), /* @__PURE__ */ import_react36.default.createElement(TableHead, { className: "w-[100px] text-center" }, "Actions"))), /* @__PURE__ */ import_react36.default.createElement(TableBody, null, models.map((model) => /* @__PURE__ */ import_react36.default.createElement(
    TableRow,
    {
      key: getModelKeyFromModel(model),
      className: "hover:bg-interactive-accent/10"
    },
    /* @__PURE__ */ import_react36.default.createElement(TableCell, null, model.name),
    /* @__PURE__ */ import_react36.default.createElement(TableCell, null, getProviderLabel(model.provider)),
    !isEmbeddingModel && /* @__PURE__ */ import_react36.default.createElement(TableCell, { className: "text-center" }, /* @__PURE__ */ import_react36.default.createElement(
      Checkbox2,
      {
        id: `${getModelKeyFromModel(model)}-enabled`,
        checked: model.enabled,
        onCheckedChange: (checked) => onUpdateModel({ ...model, enabled: checked }),
        className: "mx-auto"
      }
    )),
    /* @__PURE__ */ import_react36.default.createElement(TableCell, { className: "text-center" }, /* @__PURE__ */ import_react36.default.createElement(
      Checkbox2,
      {
        id: `${getModelKeyFromModel(model)}-enableCors`,
        checked: model.enableCors,
        onCheckedChange: (checked) => onUpdateModel({ ...model, enableCors: checked }),
        className: "mx-auto"
      }
    )),
    /* @__PURE__ */ import_react36.default.createElement(TableCell, { className: "text-center" }, /* @__PURE__ */ import_react36.default.createElement("div", { className: "flex justify-center gap-2" }, onEdit && /* @__PURE__ */ import_react36.default.createElement(
      Button,
      {
        variant: "ghost",
        size: "icon",
        onClick: () => onEdit(model),
        className: "shadow-sm hover:shadow-md transition-shadow"
      },
      /* @__PURE__ */ import_react36.default.createElement(Pencil, { className: "h-4 w-4" })
    ), !model.core && /* @__PURE__ */ import_react36.default.createElement(
      Button,
      {
        variant: "ghost",
        size: "icon",
        onClick: () => onDelete(getModelKeyFromModel(model)),
        className: "shadow-sm hover:shadow-md transition-shadow"
      },
      /* @__PURE__ */ import_react36.default.createElement(Trash2, { className: "h-4 w-4" })
    )))
  ))))), /* @__PURE__ */ import_react36.default.createElement("div", { className: "md:hidden" }, /* @__PURE__ */ import_react36.default.createElement("div", { className: "space-y-2" }, models.map((model) => /* @__PURE__ */ import_react36.default.createElement(
    ModelCard,
    {
      key: getModelKeyFromModel(model),
      model,
      onEdit: onEdit ? () => onEdit(model) : void 0,
      onDelete: () => onDelete(getModelKeyFromModel(model)),
      onUpdateModel
    }
  )))), /* @__PURE__ */ import_react36.default.createElement("div", { className: "mt-4 flex justify-end" }, /* @__PURE__ */ import_react36.default.createElement(Button, { onClick: onAdd, variant: "outline", className: "flex items-center gap-2" }, /* @__PURE__ */ import_react36.default.createElement(Plus, { className: "h-4 w-4" }), "Add Custom Model")));
};

// src/settings/v2/components/ModelSettings.tsx
var ModelSettings = () => {
  const settings = useSettingsValue();
  const [showAddDialog, setShowAddDialog] = (0, import_react37.useState)(false);
  const [showAddEmbeddingDialog, setShowAddEmbeddingDialog] = (0, import_react37.useState)(false);
  const onDeleteModel = (modelKey) => {
    const [modelName, provider] = modelKey.split("|");
    const updatedActiveModels = settings.activeModels.filter(
      (model) => !(model.name === modelName && model.provider === provider)
    );
    let newDefaultModelKey = settings.defaultModelKey;
    if (modelKey === settings.defaultModelKey) {
      const newDefaultModel = updatedActiveModels.find((model) => model.enabled);
      newDefaultModelKey = newDefaultModel ? `${newDefaultModel.name}|${newDefaultModel.provider}` : "";
    }
    setSettings({
      activeModels: updatedActiveModels,
      defaultModelKey: newDefaultModelKey
    });
  };
  const handleModelUpdate = (updatedModel) => {
    const updatedModels = settings.activeModels.map(
      (m3) => m3.name === updatedModel.name && m3.provider === updatedModel.provider ? updatedModel : m3
    );
    updateSetting("activeModels", updatedModels);
  };
  const onDeleteEmbeddingModel = (modelKey) => {
    const [modelName, provider] = modelKey.split("|");
    const updatedModels = settings.activeEmbeddingModels.filter(
      (model) => !(model.name === modelName && model.provider === provider)
    );
    updateSetting("activeEmbeddingModels", updatedModels);
  };
  const handleEmbeddingModelUpdate = (updatedModel) => {
    const updatedModels = settings.activeEmbeddingModels.map(
      (m3) => m3.name === updatedModel.name && m3.provider === updatedModel.provider ? updatedModel : m3
    );
    updateSetting("activeEmbeddingModels", updatedModels);
  };
  return /* @__PURE__ */ import_react37.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react37.default.createElement("section", null, /* @__PURE__ */ import_react37.default.createElement("div", { className: "text-xl font-bold mb-3" }, "Chat Models"), /* @__PURE__ */ import_react37.default.createElement(
    ModelTable,
    {
      models: settings.activeModels,
      onDelete: onDeleteModel,
      onAdd: () => setShowAddDialog(true),
      onUpdateModel: handleModelUpdate,
      title: "Chat Model"
    }
  ), /* @__PURE__ */ import_react37.default.createElement(
    ModelAddDialog,
    {
      open: showAddDialog,
      onOpenChange: setShowAddDialog,
      onAdd: (model) => {
        const updatedModels = [...settings.activeModels, model];
        updateSetting("activeModels", updatedModels);
      },
      ping: (model) => ChatModelManager.getInstance().ping(model)
    }
  ), /* @__PURE__ */ import_react37.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react37.default.createElement(
    SettingItem,
    {
      type: "slider",
      title: "Temperature",
      description: "Default is 0.1. Higher values will result in more creativeness, but also more mistakes. Set to 0 for no randomness.",
      value: settings.temperature,
      onChange: (value) => updateSetting("temperature", value),
      min: 0,
      max: 2,
      step: 0.05
    }
  ), /* @__PURE__ */ import_react37.default.createElement(
    SettingItem,
    {
      type: "slider",
      title: "Token limit",
      description: /* @__PURE__ */ import_react37.default.createElement(import_react37.default.Fragment, null, /* @__PURE__ */ import_react37.default.createElement("p", null, "The maximum number of ", /* @__PURE__ */ import_react37.default.createElement("em", null, "output tokens"), " to generate. Default is 1000."), /* @__PURE__ */ import_react37.default.createElement("em", null, "This number plus the length of your prompt (input tokens) must be smaller than the context window of the model.")),
      value: settings.maxTokens,
      onChange: (value) => updateSetting("maxTokens", value),
      min: 0,
      max: 16e3,
      step: 100
    }
  ), /* @__PURE__ */ import_react37.default.createElement(
    SettingItem,
    {
      type: "slider",
      title: "Conversation turns in context",
      description: "The number of previous conversation turns to include in the context. Default is 15 turns, i.e. 30 messages.",
      value: settings.contextTurns,
      onChange: (value) => updateSetting("contextTurns", value),
      min: 1,
      max: 50,
      step: 1
    }
  ))), /* @__PURE__ */ import_react37.default.createElement("section", null, /* @__PURE__ */ import_react37.default.createElement("div", { className: "text-xl font-bold mb-3" }, "Embedding Models"), /* @__PURE__ */ import_react37.default.createElement(
    ModelTable,
    {
      models: settings.activeEmbeddingModels,
      onDelete: onDeleteEmbeddingModel,
      onAdd: () => setShowAddEmbeddingDialog(true),
      onUpdateModel: handleEmbeddingModelUpdate,
      title: "Embedding Model"
    }
  ), /* @__PURE__ */ import_react37.default.createElement(
    ModelAddDialog,
    {
      open: showAddEmbeddingDialog,
      onOpenChange: setShowAddEmbeddingDialog,
      onAdd: (model) => {
        const updatedModels = [...settings.activeEmbeddingModels, model];
        updateSetting("activeEmbeddingModels", updatedModels);
      },
      isEmbeddingModel: true,
      ping: (model) => EmbeddingManager.getInstance().ping(model)
    }
  )));
};
var ModelSettings_default = ModelSettings;

// src/settings/v2/components/QASettings.tsx
var import_react38 = __toESM(require_react());
var QASettings = ({ indexVaultToVectorStore }) => {
  const { modalContainer } = useTab();
  const settings = useSettingsValue();
  const [openPopoverIds, setOpenPopoverIds] = import_react38.default.useState(/* @__PURE__ */ new Set());
  const handlePopoverOpen = (id) => {
    setOpenPopoverIds((prev) => /* @__PURE__ */ new Set([...prev, id]));
  };
  const handlePopoverClose = (id) => {
    setOpenPopoverIds((prev) => {
      const newSet = new Set(prev);
      newSet.delete(id);
      return newSet;
    });
  };
  const handlePartitionsChange = (value) => {
    const numValue = parseInt(value);
    if (numValue !== settings.numPartitions) {
      new RebuildIndexConfirmModal(app, async () => {
        updateSetting("numPartitions", numValue);
        await indexVaultToVectorStore(true);
      }).open();
    }
  };
  return /* @__PURE__ */ import_react38.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react38.default.createElement("section", null, /* @__PURE__ */ import_react38.default.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Auto-Index Strategy",
      description: /* @__PURE__ */ import_react38.default.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ import_react38.default.createElement("span", { className: "leading-none" }, "Decide when you want the vault to be indexed."), /* @__PURE__ */ import_react38.default.createElement(
        Popover2,
        {
          open: openPopoverIds.has("index-help"),
          onOpenChange: (open) => {
            if (open) {
              handlePopoverOpen("index-help");
            } else {
              handlePopoverClose("index-help");
            }
          }
        },
        /* @__PURE__ */ import_react38.default.createElement(PopoverTrigger2, { asChild: true }, /* @__PURE__ */ import_react38.default.createElement(
          CircleHelp,
          {
            className: "h-5 w-5 sm:h-4 sm:w-4 cursor-pointer text-muted hover:text-accent translate-y-[1px]",
            onMouseEnter: () => handlePopoverOpen("index-help"),
            onMouseLeave: () => handlePopoverClose("index-help")
          }
        )),
        /* @__PURE__ */ import_react38.default.createElement(
          PopoverContent2,
          {
            container: modalContainer,
            className: "w-[90vw] max-w-[400px] p-2 sm:p-3",
            side: "bottom",
            align: "center",
            sideOffset: 0,
            onMouseEnter: () => handlePopoverOpen("index-help"),
            onMouseLeave: () => handlePopoverClose("index-help")
          },
          /* @__PURE__ */ import_react38.default.createElement("div", { className: "space-y-2 sm:space-y-2.5" }, /* @__PURE__ */ import_react38.default.createElement("div", { className: "rounded bg-callout-warning/10 p-1.5 sm:p-2 ring-ring" }, /* @__PURE__ */ import_react38.default.createElement("p", { className: "text-callout-warning text-xs sm:text-sm" }, "Warning: Cost implications for large vaults with paid models")), /* @__PURE__ */ import_react38.default.createElement("div", { className: "space-y-1 sm:space-y-1.5" }, /* @__PURE__ */ import_react38.default.createElement("p", { className: "text-muted text-[11px] sm:text-xs" }, "Choose when to index your vault:"), /* @__PURE__ */ import_react38.default.createElement("ul", { className: "space-y-1 pl-2 sm:pl-3 list-disc text-[11px] sm:text-xs" }, /* @__PURE__ */ import_react38.default.createElement("li", null, /* @__PURE__ */ import_react38.default.createElement("strong", { className: "inline-block whitespace-nowrap" }, "NEVER\uFF1A"), /* @__PURE__ */ import_react38.default.createElement("span", null, "Manual indexing via command or refresh only")), /* @__PURE__ */ import_react38.default.createElement("li", null, /* @__PURE__ */ import_react38.default.createElement("strong", { className: "inline-block whitespace-nowrap" }, "ON STARTUP\uFF1A"), /* @__PURE__ */ import_react38.default.createElement("span", null, "Index updates when plugin loads or reloads")), /* @__PURE__ */ import_react38.default.createElement("li", null, /* @__PURE__ */ import_react38.default.createElement("strong", { className: "inline-block whitespace-nowrap" }, "ON MODE SWITCH\uFF1A"), /* @__PURE__ */ import_react38.default.createElement("span", null, "Updates when entering QA mode (Recommended)")))))
        )
      )),
      value: settings.indexVaultToVectorStore,
      onChange: (value) => {
        updateSetting("indexVaultToVectorStore", value);
      },
      options: VAULT_VECTOR_STORE_STRATEGIES.map((strategy) => ({
        label: strategy,
        value: strategy
      })),
      placeholder: "Strategy"
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "slider",
      title: "Max Sources",
      description: "Copilot goes through your vault to find relevant blocks and passes the top N blocks to the LLM. Default for N is 3. Increase if you want more sources included in the answer generation step.",
      min: 1,
      max: 128,
      step: 1,
      value: settings.maxSourceChunks,
      onChange: (value) => updateSetting("maxSourceChunks", value)
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "slider",
      title: "Requests per second",
      description: "Default is 10. Decrease if you are rate limited by your embedding provider.",
      min: 1,
      max: 30,
      step: 1,
      value: settings.embeddingRequestsPerSecond,
      onChange: (value) => updateSetting("embeddingRequestsPerSecond", value)
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "select",
      title: "Number of Partitions",
      description: "Number of partitions for Copilot index. Default is 1. Increase if you have issues indexing large vaults. Warning: Changes require clearing and rebuilding the index!",
      value: settings.numPartitions.toString(),
      onChange: handlePartitionsChange,
      options: [
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "12",
        "16",
        "20",
        "24",
        "28",
        "32",
        "36",
        "40"
      ].map((it) => ({
        label: it,
        value: it
      }))
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "textarea",
      title: "Exclusions",
      description: /* @__PURE__ */ import_react38.default.createElement(import_react38.default.Fragment, null, /* @__PURE__ */ import_react38.default.createElement("p", null, "Comma separated list of paths, tags, note titles or file extension will be excluded from the indexing process. e.g. folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]], *.jpg, *.excallidraw.md etc,"), /* @__PURE__ */ import_react38.default.createElement("em", null, "NOTE: Tags must be in the note properties, not the note content. Files which were previously indexed will remain in the index unless you force re-index.")),
      value: settings.qaExclusions,
      onChange: (value) => updateSetting("qaExclusions", value),
      placeholder: "folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]], *.jpg, *.excallidraw.md"
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "textarea",
      title: "Inclusions",
      description: "When specified, ONLY these paths, tags, or note titles will be indexed (comma separated). Takes precedence over exclusions. Files which were previously indexed will remain in the index unless you force re-index. Format: folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]]",
      value: settings.qaInclusions,
      onChange: (value) => updateSetting("qaInclusions", value),
      placeholder: "folder1, #tag1, [[note1]]"
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Enable Obsidian Sync for Copilot index",
      description: "If enabled, the index will be stored in the .obsidian folder and synced with Obsidian Sync by default. If disabled, it will be stored in .copilot-index folder at vault root.",
      checked: settings.enableIndexSync,
      onCheckedChange: (checked) => updateSetting("enableIndexSync", checked)
    }
  ), /* @__PURE__ */ import_react38.default.createElement(
    SettingItem,
    {
      type: "switch",
      title: "Disable index loading on mobile",
      description: "When enabled, Copilot index won't be loaded on mobile devices to save resources. Only chat mode will be available. Any existing index from desktop sync will be preserved. Uncheck to enable QA modes on mobile.",
      checked: settings.disableIndexOnMobile,
      onCheckedChange: (checked) => updateSetting("disableIndexOnMobile", checked)
    }
  ))));
};
var QASettings_default = QASettings;

// src/settings/v2/SettingsMainV2.tsx
var TAB_IDS = ["basic", "model", "QA", "advanced"];
var icons = {
  basic: /* @__PURE__ */ import_react39.default.createElement(Cog, { className: "w-5 h-5" }),
  model: /* @__PURE__ */ import_react39.default.createElement(Cpu, { className: "w-5 h-5" }),
  QA: /* @__PURE__ */ import_react39.default.createElement(Database, { className: "w-5 h-5" }),
  advanced: /* @__PURE__ */ import_react39.default.createElement(Wrench, { className: "w-5 h-5" })
};
var components = (plugin) => ({
  basic: () => /* @__PURE__ */ import_react39.default.createElement(
    BasicSettings_default,
    {
      indexVaultToVectorStore: plugin.vectorStoreManager.indexVaultToVectorStore.bind(
        plugin.vectorStoreManager
      )
    }
  ),
  model: () => /* @__PURE__ */ import_react39.default.createElement(ModelSettings_default, null),
  QA: () => /* @__PURE__ */ import_react39.default.createElement(
    QASettings_default,
    {
      indexVaultToVectorStore: plugin.vectorStoreManager.indexVaultToVectorStore.bind(
        plugin.vectorStoreManager
      )
    }
  ),
  advanced: AdvancedSettings_default
});
var tabs = TAB_IDS.map((id) => ({
  id,
  icon: icons[id],
  label: id.charAt(0).toUpperCase() + id.slice(1)
}));
var SettingsContent = ({ plugin }) => {
  const { selectedTab, setSelectedTab } = useTab();
  return /* @__PURE__ */ import_react39.default.createElement("div", { className: "flex flex-col" }, /* @__PURE__ */ import_react39.default.createElement("div", { className: "inline-flex rounded-lg" }, tabs.map((tab, index2) => /* @__PURE__ */ import_react39.default.createElement(
    TabItem,
    {
      key: tab.id,
      tab,
      isSelected: selectedTab === tab.id,
      onClick: () => setSelectedTab(tab.id),
      isFirst: index2 === 0,
      isLast: index2 === tabs.length - 1
    }
  ))), /* @__PURE__ */ import_react39.default.createElement("div", { className: "w-[100%] border border-solid" }), /* @__PURE__ */ import_react39.default.createElement("div", null, TAB_IDS.map((id) => {
    const Component2 = components(plugin)[id];
    return /* @__PURE__ */ import_react39.default.createElement(TabContent, { key: id, id, isSelected: selectedTab === id }, /* @__PURE__ */ import_react39.default.createElement(Component2, null));
  })));
};
var SettingsMainV2 = ({ plugin }) => {
  const [resetKey, setResetKey] = import_react39.default.useState(0);
  const [latestVersion, setLatestVersion] = (0, import_react39.useState)(null);
  const [updateError, setUpdateError] = (0, import_react39.useState)(null);
  (0, import_react39.useEffect)(() => {
    const checkForUpdates = async () => {
      const { version: version2, error } = await checkLatestVersion();
      if (error) {
        console.error("Version check failed:", error);
        setUpdateError(error);
      } else if (version2) {
        setLatestVersion(version2);
        setUpdateError(null);
      }
    };
    checkForUpdates();
  }, [plugin.manifest.version]);
  const handleReset = async () => {
    const modal = new ResetSettingsConfirmModal(app, async () => {
      resetSettings();
      setResetKey((prev) => prev + 1);
    });
    modal.open();
  };
  const isNewerVersionAvailable = latestVersion && isNewerVersion(latestVersion, plugin.manifest.version);
  return /* @__PURE__ */ import_react39.default.createElement(TabProvider, null, /* @__PURE__ */ import_react39.default.createElement("div", null, /* @__PURE__ */ import_react39.default.createElement("div", { className: "flex flex-col gap-2" }, /* @__PURE__ */ import_react39.default.createElement("h1", { className: "flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2" }, /* @__PURE__ */ import_react39.default.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ import_react39.default.createElement("span", null, "Copilot Settings"), /* @__PURE__ */ import_react39.default.createElement("span", { className: "text-xs text-muted" }, "v", plugin.manifest.version, updateError ? /* @__PURE__ */ import_react39.default.createElement("span", { className: "text-error", title: updateError }, " ", "(update check failed)") : latestVersion && /* @__PURE__ */ import_react39.default.createElement(import_react39.default.Fragment, null, isNewerVersionAvailable ? /* @__PURE__ */ import_react39.default.createElement("span", { className: "text-accent", title: "A new version is available" }, " ", "(latest: v", latestVersion, ")") : /* @__PURE__ */ import_react39.default.createElement("span", { className: "text-accent" }, " (up to date)")))), /* @__PURE__ */ import_react39.default.createElement("div", { className: "self-end sm:self-auto" }, /* @__PURE__ */ import_react39.default.createElement(Button, { variant: "outline", size: "sm", onClick: handleReset }, "Reset Settings")))), /* @__PURE__ */ import_react39.default.createElement(SettingsContent, { key: resetKey, plugin })));
};
var SettingsMainV2_default = SettingsMainV2;

// src/settings/SettingsPage.tsx
var CopilotSettingTab = class extends import_obsidian45.PluginSettingTab {
  constructor(app2, plugin) {
    super(app2, plugin);
    this.plugin = plugin;
  }
  async reloadPlugin() {
    try {
      const chatView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0]?.view;
      if (chatView && getSettings().autosaveChat) {
        await this.plugin.autosaveCurrentChat();
      }
      const app2 = this.plugin.app;
      await app2.plugins.disablePlugin("copilot");
      await app2.plugins.enablePlugin("copilot");
      app2.setting.openTabById("copilot").display();
      new import_obsidian45.Notice("Plugin reloaded successfully.");
    } catch (error) {
      new import_obsidian45.Notice("Failed to reload the plugin. Please reload manually.");
      console.error("Error reloading plugin:", error);
    }
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    containerEl.style.userSelect = "text";
    const div = containerEl.createDiv("div");
    const sections = (0, import_client8.createRoot)(div);
    sections.render(/* @__PURE__ */ import_react40.default.createElement(SettingsMainV2_default, { plugin: this.plugin }));
  }
};

// src/cache/pdfCache.ts
var import_crypto_js3 = __toESM(require_crypto_js());
var PDFCache = class {
  constructor() {
    this.cacheDir = ".copilot/pdf-cache";
  }
  static getInstance() {
    if (!PDFCache.instance) {
      PDFCache.instance = new PDFCache();
    }
    return PDFCache.instance;
  }
  async ensureCacheDir() {
    if (!await app.vault.adapter.exists(this.cacheDir)) {
      logInfo("Creating PDF cache directory:", this.cacheDir);
      await app.vault.adapter.mkdir(this.cacheDir);
    }
  }
  getCacheKey(file) {
    const metadata = `${file.path}:${file.stat.size}:${file.stat.mtime}`;
    const key = (0, import_crypto_js3.MD5)(metadata).toString();
    logInfo("Generated cache key for PDF:", { path: file.path, key });
    return key;
  }
  getCachePath(cacheKey) {
    return `${this.cacheDir}/${cacheKey}.json`;
  }
  async get(file) {
    try {
      const cacheKey = this.getCacheKey(file);
      const cachePath = this.getCachePath(cacheKey);
      if (await app.vault.adapter.exists(cachePath)) {
        logInfo("Cache hit for PDF:", file.path);
        const cacheContent = await app.vault.adapter.read(cachePath);
        return JSON.parse(cacheContent);
      }
      logInfo("Cache miss for PDF:", file.path);
      return null;
    } catch (error) {
      logError("Error reading from PDF cache:", error);
      return null;
    }
  }
  async set(file, response) {
    try {
      await this.ensureCacheDir();
      const cacheKey = this.getCacheKey(file);
      const cachePath = this.getCachePath(cacheKey);
      logInfo("Caching PDF response for:", file.path);
      await app.vault.adapter.write(cachePath, JSON.stringify(response));
    } catch (error) {
      logError("Error writing to PDF cache:", error);
    }
  }
  async clear() {
    try {
      if (await app.vault.adapter.exists(this.cacheDir)) {
        const files = await app.vault.adapter.list(this.cacheDir);
        logInfo("Clearing PDF cache, removing files:", files.files.length);
        for (const file of files.files) {
          await app.vault.adapter.remove(file);
        }
      }
    } catch (error) {
      logError("Error clearing PDF cache:", error);
    }
  }
};

// src/tools/FileParserManager.ts
var MarkdownParser = class {
  constructor() {
    this.supportedExtensions = ["md"];
  }
  async parseFile(file, vault) {
    return await vault.read(file);
  }
};
var PDFParser = class {
  constructor(brevilabsClient) {
    this.supportedExtensions = ["pdf"];
    this.brevilabsClient = brevilabsClient;
    this.pdfCache = PDFCache.getInstance();
  }
  async parseFile(file, vault) {
    try {
      logInfo("Parsing PDF file:", file.path);
      const cachedResponse = await this.pdfCache.get(file);
      if (cachedResponse) {
        logInfo("Using cached PDF content for:", file.path);
        return cachedResponse.response;
      }
      const binaryContent = await vault.readBinary(file);
      logInfo("Calling pdf4llm API for:", file.path);
      const pdf4llmResponse = await this.brevilabsClient.pdf4llm(binaryContent);
      await this.pdfCache.set(file, pdf4llmResponse);
      return pdf4llmResponse.response;
    } catch (error) {
      logError(`Error extracting content from PDF ${file.path}:`, error);
      return `[Error: Could not extract content from PDF ${file.basename}]`;
    }
  }
  async clearCache() {
    logInfo("Clearing PDF cache");
    await this.pdfCache.clear();
  }
};
var FileParserManager = class {
  constructor(brevilabsClient) {
    this.parsers = /* @__PURE__ */ new Map();
    this.registerParser(new MarkdownParser());
    this.registerParser(new PDFParser(brevilabsClient));
  }
  registerParser(parser) {
    for (const ext of parser.supportedExtensions) {
      this.parsers.set(ext, parser);
    }
  }
  async parseFile(file, vault) {
    const parser = this.parsers.get(file.extension);
    if (!parser) {
      throw new Error(`No parser found for file type: ${file.extension}`);
    }
    return await parser.parseFile(file, vault);
  }
  supportsExtension(extension) {
    return this.parsers.has(extension);
  }
  async clearPDFCache() {
    const pdfParser = this.parsers.get("pdf");
    if (pdfParser instanceof PDFParser) {
      await pdfParser.clearCache();
    }
  }
};

// src/main.ts
var import_obsidian46 = require("obsidian");
var CopilotPlugin = class extends import_obsidian46.Plugin {
  constructor() {
    super(...arguments);
    this.userMessageHistory = [];
    this.handleContextMenu = (menu, editor) => {
      registerContextMenu(menu, editor, this);
    };
  }
  async onload() {
    await this.loadSettings();
    this.settingsUnsubscriber = subscribeToSettingsChange(async () => {
      const settings = getSettings();
      if (settings.enableEncryption) {
        await this.saveData(await encryptAllKeys(settings));
      } else {
        await this.saveData(settings);
      }
      registerBuiltInCommands(this);
    });
    this.addSettingTab(new CopilotSettingTab(this.app, this));
    this.sharedState = new sharedState_default();
    this.vectorStoreManager = VectorStoreManager.getInstance();
    this.brevilabsClient = BrevilabsClient.getInstance();
    this.brevilabsClient.setPluginVersion(this.manifest.version);
    await checkIsPlusUser();
    this.chainManager = new ChainManager(this.app, this.vectorStoreManager);
    this.fileParserManager = new FileParserManager(this.brevilabsClient);
    this.registerView(CHAT_VIEWTYPE, (leaf) => new CopilotView(leaf, this));
    this.initActiveLeafChangeHandler();
    this.addRibbonIcon("message-square", "Open Copilot Chat", (evt) => {
      this.activateView();
    });
    registerBuiltInCommands(this);
    this.registerEvent(
      this.app.workspace.on("editor-menu", (menu, editor) => {
        const selectedText = editor.getSelection().trim();
        if (selectedText) {
          this.handleContextMenu(menu, editor);
        }
      })
    );
    this.registerEvent(
      this.app.workspace.on("active-leaf-change", (leaf) => {
        if (leaf && leaf.view instanceof import_obsidian46.MarkdownView) {
          const file = leaf.view.file;
          if (file) {
            const activeCopilotView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE).find((leaf2) => leaf2.view instanceof CopilotView)?.view;
            if (activeCopilotView) {
              const event = new CustomEvent(EVENT_NAMES.ACTIVE_LEAF_CHANGE);
              activeCopilotView.eventTarget.dispatchEvent(event);
            }
          }
        }
      })
    );
  }
  async onunload() {
    if (this.vectorStoreManager) {
      this.vectorStoreManager.onunload();
    }
    this.settingsUnsubscriber?.();
    console.log("Copilot plugin unloaded");
  }
  updateUserMessageHistory(newMessage) {
    this.userMessageHistory = [...this.userMessageHistory, newMessage];
  }
  async autosaveCurrentChat() {
    if (getSettings().autosaveChat) {
      const chatView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0]?.view;
      if (chatView && chatView.sharedState.chatHistory.length > 0) {
        await chatView.saveChat();
      }
    }
  }
  async processText(editor, eventType, eventSubtype, checkSelectedText = true) {
    const selectedText = await editor.getSelection();
    const isChatWindowActive = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE).length > 0;
    if (!isChatWindowActive) {
      await this.activateView();
    }
    setTimeout(() => {
      const activeCopilotView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE).find((leaf) => leaf.view instanceof CopilotView)?.view;
      if (activeCopilotView && (!checkSelectedText || selectedText)) {
        const event = new CustomEvent(eventType, { detail: { selectedText, eventSubtype } });
        activeCopilotView.eventTarget.dispatchEvent(event);
      }
    }, 0);
  }
  processSelection(editor, eventType, eventSubtype) {
    this.processText(editor, eventType, eventSubtype);
  }
  emitChatIsVisible() {
    const activeCopilotView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE).find((leaf) => leaf.view instanceof CopilotView)?.view;
    if (activeCopilotView) {
      const event = new CustomEvent(EVENT_NAMES.CHAT_IS_VISIBLE);
      activeCopilotView.eventTarget.dispatchEvent(event);
    }
  }
  initActiveLeafChangeHandler() {
    this.registerEvent(
      this.app.workspace.on("active-leaf-change", (leaf) => {
        if (!leaf) {
          return;
        }
        if (leaf.getViewState().type === CHAT_VIEWTYPE) {
          this.emitChatIsVisible();
        }
      })
    );
  }
  getCurrentEditorOrDummy() {
    const activeView = this.app.workspace.getActiveViewOfType(import_obsidian46.MarkdownView);
    return {
      getSelection: () => {
        const selection = activeView?.editor?.getSelection();
        if (selection)
          return selection;
        const activeFile = this.app.workspace.getActiveFile();
        return activeFile ? this.app.vault.cachedRead(activeFile) : "";
      },
      replaceSelection: activeView?.editor?.replaceSelection.bind(activeView.editor) || (() => {
      })
    };
  }
  processCustomPrompt(eventType, customPrompt) {
    const editor = this.getCurrentEditorOrDummy();
    this.processText(editor, eventType, customPrompt, false);
  }
  toggleView() {
    const leaves = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE);
    if (leaves.length > 0) {
      this.deactivateView();
    } else {
      this.activateView();
    }
  }
  async activateView() {
    const leaves = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE);
    if (leaves.length === 0) {
      if (getSettings().defaultOpenArea === "view" /* VIEW */) {
        await this.app.workspace.getRightLeaf(false).setViewState({
          type: CHAT_VIEWTYPE,
          active: true
        });
      } else {
        await this.app.workspace.getLeaf(true).setViewState({
          type: CHAT_VIEWTYPE,
          active: true
        });
      }
    } else {
      this.app.workspace.revealLeaf(leaves[0]);
    }
    this.emitChatIsVisible();
  }
  async deactivateView() {
    this.app.workspace.detachLeavesOfType(CHAT_VIEWTYPE);
  }
  async loadSettings() {
    const savedSettings = await this.loadData();
    const sanitizedSettings = sanitizeSettings(savedSettings);
    setSettings(sanitizedSettings);
  }
  mergeActiveModels(existingActiveModels, builtInModels) {
    const modelMap = /* @__PURE__ */ new Map();
    existingActiveModels.forEach((model) => {
      const key = getModelKeyFromModel(model);
      const existingModel = modelMap.get(key);
      if (existingModel) {
        modelMap.set(key, {
          ...model,
          isBuiltIn: existingModel.isBuiltIn || model.isBuiltIn
        });
      } else {
        modelMap.set(key, model);
      }
    });
    return Array.from(modelMap.values());
  }
  async loadCopilotChatHistory() {
    const chatFiles = await this.getChatHistoryFiles();
    if (chatFiles.length === 0) {
      new import_obsidian46.Notice("No chat history found.");
      return;
    }
    new LoadChatHistoryModal(this.app, chatFiles, this.loadChatHistory.bind(this)).open();
  }
  async getChatHistoryFiles() {
    const folder = this.app.vault.getAbstractFileByPath(getSettings().defaultSaveFolder);
    if (!(folder instanceof import_obsidian46.TFolder)) {
      return [];
    }
    const files = await this.app.vault.getMarkdownFiles();
    return files.filter((file) => file.path.startsWith(folder.path));
  }
  async loadChatHistory(file) {
    const content = await this.app.vault.read(file);
    const messages = parseChatContent(content);
    this.sharedState.clearChatHistory();
    messages.forEach((message) => this.sharedState.addMessage(message));
    await updateChatMemory(messages, this.chainManager.memoryManager);
    const existingView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0];
    if (!existingView) {
      this.activateView();
    } else {
      const copilotView = existingView.view;
      copilotView.updateView();
    }
  }
  async customSearchDB(query, salientTerms, textWeight) {
    const hybridRetriever = new HybridRetriever({
      minSimilarityScore: 0.3,
      maxK: 20,
      salientTerms,
      textWeight
    });
    const results = await hybridRetriever.getOramaChunks(query, salientTerms);
    return results.map((doc) => ({
      content: doc.pageContent,
      metadata: doc.metadata
    }));
  }
};
/*! Bundled license information:

@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
  (*!
   * https://github.com/Starcounter-Jack/JSON-Patch
   * (c) 2017-2022 Joachim Wester
   * MIT licensed
   *)

@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
  (*!
   * https://github.com/Starcounter-Jack/JSON-Patch
   * (c) 2013-2021 Joachim Wester
   * MIT license
   *)

mustache/mustache.mjs:
  (*!
   * mustache.js - Logic-less {{mustache}} templates with JavaScript
   * http://github.com/janl/mustache.js
   *)

react/cjs/react.development.js:
  (**
   * @license React
   * react.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

scheduler/cjs/scheduler.development.js:
  (**
   * @license React
   * scheduler.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-dom/cjs/react-dom.development.js:
  (**
   * @license React
   * react-dom.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
  (**
   * Checks if an event is supported in the current execution environment.
   *
   * NOTE: This will not work correctly for non-generic events such as `change`,
   * `reset`, `load`, `error`, and `select`.
   *
   * Borrows from Modernizr.
   *
   * @param {string} eventNameSuffix Event name, e.g. "click".
   * @return {boolean} True if the event is supported.
   * @internal
   * @license Modernizr 3.0.0pre (Custom Build) | MIT
   *)

react/cjs/react-jsx-runtime.development.js:
  (**
   * @license React
   * react-jsx-runtime.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

moment/moment.js:
  (*! moment.js *)
  (*! version : 2.29.4 *)
  (*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
  (*! license : MIT *)
  (*! momentjs.com *)

ieee754/index.js:
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)

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

tslib/tslib.es6.js:
  (*! *****************************************************************************
  Copyright (c) Microsoft Corporation.
  
  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted.
  
  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  PERFORMANCE OF THIS SOFTWARE.
  ***************************************************************************** *)

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

@langchain/core/dist/utils/js-sha1/hash.js:
  (*
   * [js-sha1]{@link https://github.com/emn178/js-sha1}
   *
   * @version 0.6.0
   * @author Chen, Yi-Cyuan [emn178@gmail.com]
   * @copyright Chen, Yi-Cyuan 2014-2017
   * @license MIT
   *)

crypto-js/ripemd160.js:
  (** @preserve
  	(c) 2012 by Cédric Mesnil. All rights reserved.
  
  	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  
  	    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  	    - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  
  	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  	*)

crypto-js/mode-ctr-gladman.js:
  (** @preserve
   * Counter block mode compatible with  Dr Brian Gladman fileenc.c
   * derived from CryptoJS.mode.CTR
   * Jan Hruby jhruby.web@gmail.com
   *)

react-is/cjs/react-is.development.js:
  (** @license React v16.13.1
   * react-is.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

object-assign/index.js:
  (*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  *)

lucide-react/dist/esm/shared/src/utils.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/defaultAttributes.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/Icon.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/createLucideIcon.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/arrow-big-up.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/arrow-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/bot.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/check.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-down.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-up.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-help.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-stop.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/cog.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/command.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/copy.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/corner-down-left.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/cpu.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/database.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/download.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/ellipsis.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/external-link.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/eye-off.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/eye.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-text.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/image.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/info.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/key.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/library-big.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/loader-circle.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/message-circle-plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pen-line.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pencil.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/refresh-ccw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/refresh-cw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/rotate-cw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/sparkles.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/square-pen.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/text-cursor-input.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/trash-2.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/triangle-alert.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/user.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/wrench.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/x.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/lucide-react.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

@google/generative-ai/dist/index.mjs:
  (**
   * @license
   * Copyright 2024 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

@google/generative-ai/dist/index.mjs:
  (**
   * @license
   * Copyright 2024 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)
*/

/* nosourcemap */