master-degree-notes/.obsidian/plugins/copilot/main.js

143807 lines
No EOL
5.2 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
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 name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
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,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
// then global default map
].filter((x2) => !!x2)
});
ctx.common.issues.push(issue);
}
function __classPrivateFieldGet(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.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 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(a4, b3) {
const aType = getParsedType(a4);
const bType = getParsedType(b3);
if (a4 === b3) {
return { valid: true, data: a4 };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b3);
const sharedKeys = util.objectKeys(a4).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a4, ...b3 };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a4[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 (a4.length !== b3.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a4.length; index++) {
const itemA = a4[index];
const itemB = b3[index];
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 && +a4 === +b3) {
return { valid: true, data: a4 };
} 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 p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b = (_a5 = p4.fatal) !== null && _a5 !== void 0 ? _a5 : fatal) !== null && _b !== void 0 ? _b : true;
const p22 = typeof p4 === "string" ? { message: p4 } : p4;
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, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv6Regex, base64Regex, 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(e4) {
return obj[e4];
});
};
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 t4 = typeof data;
switch (t4) {
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 {
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;
}
get errors() {
return this.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 i4 = 0;
while (i4 < issue.path.length) {
const el = issue.path[i4];
const terminal = i4 === 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];
i4++;
}
}
}
};
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 {
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);
}
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);
}
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);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
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}$/;
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;
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])$/;
ipv6Regex = /^(([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})))$/;
base64Regex = /^([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 === "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 {
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) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...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)
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
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 isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _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 min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null, min = 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 (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params)
});
};
ZodBigInt = class extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
input.data = BigInt(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType
});
return INVALID;
}
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 };
}
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 min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _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 min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
ZodArray = class 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, i4) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
})).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i4) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
});
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(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
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], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "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, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) }
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) }
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
ZodFunction = class 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((e4) => {
error.addIssue(makeArgsIssue(args, e4));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e4) => {
error.addIssue(makeReturnsIssue(result, e4));
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(a4, b3) {
return new ZodPipeline({
in: a4,
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 i4 = 0; i4 < this._errors.length; i4++) {
var error = this._errors[i4];
var message = error.message;
var count3 = (counts[message] || 0) + 1;
counts[message] = count3;
if (count3 >= mainErrorCount) {
mainError = error;
mainErrorCount = count3;
}
}
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 i4 = 0; i4 < opts.retries; i4++) {
timeouts.push(this.createTimeout(i4, opts));
}
if (options && options.forever && !timeouts.length) {
timeouts.push(this.createTimeout(i4, opts));
}
timeouts.sort(function(a4, b3) {
return a4 - 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 i4 = 0; i4 < methods2.length; i4++) {
var method = methods2[i4];
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, offset = 0) {
return (byteToHex[arr2[offset + 0]] + byteToHex[arr2[offset + 1]] + byteToHex[arr2[offset + 2]] + byteToHex[arr2[offset + 3]] + "-" + byteToHex[arr2[offset + 4]] + byteToHex[arr2[offset + 5]] + "-" + byteToHex[arr2[offset + 6]] + byteToHex[arr2[offset + 7]] + "-" + byteToHex[arr2[offset + 8]] + byteToHex[arr2[offset + 9]] + "-" + byteToHex[arr2[offset + 10]] + byteToHex[arr2[offset + 11]] + byteToHex[arr2[offset + 12]] + byteToHex[arr2[offset + 13]] + byteToHex[arr2[offset + 14]] + byteToHex[arr2[offset + 15]]).toLowerCase();
}
var byteToHex, i4;
var init_stringify = __esm({
"node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/stringify.js"() {
byteToHex = [];
for (i4 = 0; i4 < 256; ++i4) {
byteToHex.push((i4 + 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, offset) {
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) {
offset = offset || 0;
for (var i4 = 0; i4 < 16; ++i4) {
buf[offset + i4] = rnds[i4];
}
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/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"() {
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 (runTree === void 0) {
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 i4 in obj) {
if (hasOwnProperty(obj, i4)) {
keys.push(i4);
}
}
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 i4 = 0;
const len = str2.length;
let charCode;
while (i4 < len) {
charCode = str2.charCodeAt(i4);
if (charCode >= 48 && charCode <= 57) {
i4++;
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 i5 = 0, len = obj.length; i5 < len; i5++) {
if (hasUndefined(obj[i5])) {
return true;
}
}
} else if (typeof obj === "object") {
const objKeys = _objectKeys(obj);
const objKeysLength = objKeys.length;
for (var i4 = 0; i4 < objKeysLength; i4++) {
if (hasUndefined(obj[objKeys[i4]])) {
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, name2, index, operation, tree) {
super(patchErrorMessageFormatter(message, { name: name2, index, operation, tree }));
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: name2
});
Object.defineProperty(this, "index", {
enumerable: true,
configurable: true,
writable: true,
value: index
});
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: name2,
index,
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: () => validate2,
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, index = 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", index, 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", index, operation, document2);
} else {
return returnValue;
}
}
} else {
if (!mutateDocument) {
document2 = _deepClone(document2);
}
const path = operation.path || "";
const keys = path.split("/");
let obj = document2;
let t4 = 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[t4];
if (key && key.indexOf("~") != -1) {
key = unescapePathComponent(key);
}
if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t4 > 0 && keys[t4 - 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, t4).join("/");
} else if (t4 == len - 1) {
existingPathFragment = operation.path;
}
if (existingPathFragment !== void 0) {
validateFunction(operation, 0, document2, existingPathFragment);
}
}
}
t4++;
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", index, operation, document2);
} else if (isInteger(key)) {
key = ~~key;
}
}
if (t4 >= 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", index, 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", index, operation, document2);
}
return returnValue;
}
} else {
if (t4 >= len) {
const returnValue = objOps[operation.op].call(operation, obj, key, document2);
if (returnValue.test === false) {
throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2);
}
return returnValue;
}
}
obj = obj[key];
if (validateOperation && t4 < len && (!obj || typeof obj !== "object")) {
throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, 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 i4 = 0, length = patch.length; i4 < length; i4++) {
results[i4] = applyOperation(document2, patch[i4], validateOperation, true, banPrototypeModifications, i4);
document2 = results[i4].newDocument;
}
results.newDocument = document2;
return results;
}
function applyReducer(document2, operation, index) {
const operationResult = applyOperation(document2, operation);
if (operationResult.test === false) {
throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2);
}
return operationResult.newDocument;
}
function validator(operation, index, document2, existingPathFragment) {
if (typeof operation !== "object" || operation === null || Array.isArray(operation)) {
throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, 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", index, operation, document2);
} else if (typeof operation.path !== "string") {
throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document2);
} else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) {
throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, 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", index, 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", index, 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", index, 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", index, 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", index, operation, document2);
}
} else if (operation.op === "move" || operation.op === "copy") {
var existingValue = {
op: "_get",
path: operation.from,
value: void 0
};
var error = validate2([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", index, operation, document2);
}
}
}
}
function validate2(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 i4 = 0; i4 < sequence.length; i4++) {
externalValidator(sequence[i4], i4, document2, void 0);
}
}
} catch (e4) {
if (e4 instanceof JsonPatchError) {
return e4;
} else {
throw e4;
}
}
}
function _areEquals(a4, b3) {
if (a4 === b3)
return true;
if (a4 && b3 && typeof a4 == "object" && typeof b3 == "object") {
var arrA = Array.isArray(a4), arrB = Array.isArray(b3), i4, length, key;
if (arrA && arrB) {
length = a4.length;
if (length != b3.length)
return false;
for (i4 = length; i4-- !== 0; )
if (!_areEquals(a4[i4], b3[i4]))
return false;
return true;
}
if (arrA != arrB)
return false;
var keys = Object.keys(a4);
length = keys.length;
if (length !== Object.keys(b3).length)
return false;
for (i4 = length; i4-- !== 0; )
if (!b3.hasOwnProperty(keys[i4]))
return false;
for (i4 = length; i4-- !== 0; ) {
key = keys[i4];
if (!_areEquals(a4[key], b3[key]))
return false;
}
return true;
}
return a4 !== a4 && 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, i4, document2) {
if (isInteger(i4)) {
arr2.splice(i4, 0, this.value);
} else {
arr2[i4] = this.value;
}
return { newDocument: document2, index: i4 };
},
remove: function(arr2, i4, document2) {
var removedList = arr2.splice(i4, 1);
return { newDocument: document2, removed: removedList[0] };
},
replace: function(arr2, i4, document2) {
var removed = arr2[i4];
arr2[i4] = 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 t4 = oldKeys.length - 1; t4 >= 0; t4--) {
var key = oldKeys[t4];
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 t4 = 0; t4 < newKeys.length; t4++) {
var key = newKeys[t4];
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 i4 = 0; i4 < string.length; i4++) {
const character = string[i4];
if (isLastCharLower && UPPERCASE.test(character)) {
string = string.slice(0, i4) + "-" + string.slice(i4);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i4++;
} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {
string = string.slice(0, i4 - 1) + "-" + string.slice(i4 - 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 getRuntimeEnvironment() {
if (runtimeEnvironment === void 0) {
const env = getEnv();
runtimeEnvironment = {
library: "langchain-js",
runtime: env
};
}
return runtimeEnvironment;
}
function getEnvironmentVariable(name2) {
try {
return typeof process !== "undefined" ? (
// eslint-disable-next-line no-process-env
process.env?.[name2]
) : void 0;
} catch (e4) {
return void 0;
}
}
var isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment;
var init_env = __esm({
"node_modules/@langchain/core/dist/utils/env.js"() {
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 = () => {
let env;
if (isBrowser()) {
env = "browser";
} else if (isNode()) {
env = "node";
} else if (isWebWorker()) {
env = "webworker";
} else if (isJsDom()) {
env = "jsdom";
} else if (isDeno()) {
env = "deno";
} else {
env = "other";
}
return env;
};
}
});
// node_modules/@langchain/core/dist/callbacks/base.js
var BaseCallbackHandlerMethodsClass, BaseCallbackHandler;
var init_base = __esm({
"node_modules/@langchain/core/dist/callbacks/base.js"() {
init_esm_browser();
init_serializable();
init_env();
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: getEnvironmentVariable("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();
}
};
}
});
// node_modules/@langchain/core/dist/tracers/base.js
function _coerceToDict(value, defaultKey) {
return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value };
}
function stripNonAlphanumeric(input) {
return input.replace(/[-:.]/g, "");
}
function convertToDottedOrderFormat(epoch, runId, executionOrder) {
const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
return stripNonAlphanumeric(`${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 = convertToDottedOrderFormat(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, name2) {
const execution_order = this._getExecutionOrder(parentRunId);
const start_time = Date.now();
const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams;
const run = {
id: runId,
name: name2 ?? 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, name2) {
const run = this.runMap.get(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name2);
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, name2) {
const execution_order = this._getExecutionOrder(parentRunId);
const start_time = Date.now();
const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams;
const run = {
id: runId,
name: name2 ?? 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, name2) {
const run = this.runMap.get(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name2);
await this.onRunCreate?.(run);
await this.onLLMStart?.(run);
return run;
}
async handleLLMEnd(output, runId) {
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()
});
await this.onLLMEnd?.(run);
await this._endTrace(run);
return run;
}
async handleLLMError(error, runId) {
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()
});
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, name2) {
const execution_order = this._getExecutionOrder(parentRunId);
const start_time = Date.now();
const run = {
id: runId,
name: name2 ?? 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, name2) {
const run = this.runMap.get(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name2);
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(tool, input, runId, parentRunId, tags, metadata, name2) {
const execution_order = this._getExecutionOrder(parentRunId);
const start_time = Date.now();
const run = {
id: runId,
name: name2 ?? tool.id[tool.id.length - 1],
parent_run_id: parentRunId,
start_time,
serialized: tool,
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(tool, input, runId, parentRunId, tags, metadata, name2) {
const run = this.runMap.get(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name2);
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, name2) {
const execution_order = this._getExecutionOrder(parentRunId);
const start_time = Date.now();
const run = {
id: runId,
name: name2 ?? 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, name2) {
const run = this.runMap.get(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name2);
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/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 validate3(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 = validate3;
}
});
// node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js
function unsafeStringify2(arr2, offset = 0) {
return (byteToHex2[arr2[offset + 0]] + byteToHex2[arr2[offset + 1]] + byteToHex2[arr2[offset + 2]] + byteToHex2[arr2[offset + 3]] + "-" + byteToHex2[arr2[offset + 4]] + byteToHex2[arr2[offset + 5]] + "-" + byteToHex2[arr2[offset + 6]] + byteToHex2[arr2[offset + 7]] + "-" + byteToHex2[arr2[offset + 8]] + byteToHex2[arr2[offset + 9]] + "-" + byteToHex2[arr2[offset + 10]] + byteToHex2[arr2[offset + 11]] + byteToHex2[arr2[offset + 12]] + byteToHex2[arr2[offset + 13]] + byteToHex2[arr2[offset + 14]] + byteToHex2[arr2[offset + 15]]).toLowerCase();
}
var byteToHex2, i4;
var init_stringify2 = __esm({
"node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js"() {
byteToHex2 = [];
for (i4 = 0; i4 < 256; ++i4) {
byteToHex2.push((i4 + 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, offset) {
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) {
offset = offset || 0;
for (var i4 = 0; i4 < 16; ++i4) {
buf[offset + i4] = rnds[i4];
}
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, once2) {
this.fn = fn;
this.context = context;
this.once = once2 || false;
}
function addListener(emitter, event, fn, context, once2) {
if (typeof fn !== "function") {
throw new TypeError("The listener must be a function");
}
var listener = new EE(fn, context || emitter, once2), 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 EventEmitter2() {
this._events = new Events();
this._eventsCount = 0;
}
EventEmitter2.prototype.eventNames = function eventNames() {
var names = [], events, name2;
if (this._eventsCount === 0)
return names;
for (name2 in events = this._events) {
if (has2.call(events, name2))
names.push(prefix ? name2.slice(1) : name2);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
EventEmitter2.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 i4 = 0, l4 = handlers.length, ee = new Array(l4); i4 < l4; i4++) {
ee[i4] = handlers[i4].fn;
}
return ee;
};
EventEmitter2.prototype.listenerCount = function listenerCount2(event) {
var evt = prefix ? prefix + event : event, listeners = this._events[evt];
if (!listeners)
return 0;
if (listeners.fn)
return 1;
return listeners.length;
};
EventEmitter2.prototype.emit = function emit(event, a1, a22, a32, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt])
return false;
var listeners = this._events[evt], len = arguments.length, args, i4;
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, a32), true;
case 5:
return listeners.fn.call(listeners.context, a1, a22, a32, a4), true;
case 6:
return listeners.fn.call(listeners.context, a1, a22, a32, a4, a5), true;
}
for (i4 = 1, args = new Array(len - 1); i4 < len; i4++) {
args[i4 - 1] = arguments[i4];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length, j3;
for (i4 = 0; i4 < length; i4++) {
if (listeners[i4].once)
this.removeListener(event, listeners[i4].fn, void 0, true);
switch (len) {
case 1:
listeners[i4].fn.call(listeners[i4].context);
break;
case 2:
listeners[i4].fn.call(listeners[i4].context, a1);
break;
case 3:
listeners[i4].fn.call(listeners[i4].context, a1, a22);
break;
case 4:
listeners[i4].fn.call(listeners[i4].context, a1, a22, a32);
break;
default:
if (!args)
for (j3 = 1, args = new Array(len - 1); j3 < len; j3++) {
args[j3 - 1] = arguments[j3];
}
listeners[i4].fn.apply(listeners[i4].context, args);
}
}
}
return true;
};
EventEmitter2.prototype.on = function on2(event, fn, context) {
return addListener(this, event, fn, context, false);
};
EventEmitter2.prototype.once = function once2(event, fn, context) {
return addListener(this, event, fn, context, true);
};
EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once2) {
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 && (!once2 || listeners.once) && (!context || listeners.context === context)) {
clearEvent(this, evt);
}
} else {
for (var i4 = 0, events = [], length = listeners.length; i4 < length; i4++) {
if (listeners[i4].fn !== fn || once2 && !listeners[i4].once || context && listeners[i4].context !== context) {
events.push(listeners[i4]);
}
}
if (events.length)
this._events[evt] = events.length === 1 ? events[0] : events;
else
clearEvent(this, evt);
}
return this;
};
EventEmitter2.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;
};
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
EventEmitter2.prefixed = prefix;
EventEmitter2.EventEmitter = EventEmitter2;
if ("undefined" !== typeof module2) {
module2.exports = EventEmitter2;
}
}
});
// 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 count3 = array.length;
while (count3 > 0) {
const step = count3 / 2 | 0;
let it = first + step;
if (comparator(array[it], value) <= 0) {
first = ++it;
count3 -= step + 1;
} else {
count3 = 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 index = lower_bound_1.default(this._queue, element, (a4, b3) => b3.priority - a4.priority);
this._queue.splice(index, 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 EventEmitter2 = 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 EventEmitter2 {
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 now = Date.now();
if (this._intervalId === void 0) {
const delay = this._intervalEnd - now;
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/env.js
async function getRuntimeEnvironment2() {
if (runtimeEnvironment2 === void 0) {
const env = getEnv2();
const releaseEnv = getShas();
runtimeEnvironment2 = {
library: "langsmith",
runtime: env,
sdk: "langsmith-js",
sdk_version: __version__,
...releaseEnv
};
}
return runtimeEnvironment2;
}
function getLangChainEnvVarsMetadata() {
const allEnvVars = getEnvironmentVariables() || {};
const envVars = {};
const excluded = [
"LANGCHAIN_API_KEY",
"LANGCHAIN_ENDPOINT",
"LANGCHAIN_TRACING_V2",
"LANGCHAIN_PROJECT",
"LANGCHAIN_SESSION"
];
for (const [key, value] of Object.entries(allEnvVars)) {
if (key.startsWith("LANGCHAIN_") && 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 (e4) {
return void 0;
}
}
function getEnvironmentVariable2(name2) {
try {
return typeof process !== "undefined" ? (
// eslint-disable-next-line no-process-env
process.env?.[name2]
) : void 0;
} catch (e4) {
return void 0;
}
}
function getLangSmithEnvironmentVariable(name2) {
return getEnvironmentVariable2(`LANGSMITH_${name2}`) || getEnvironmentVariable2(`LANGCHAIN_${name2}`);
}
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 = getEnvironmentVariable2(env);
if (envVar !== void 0) {
shas[env] = envVar;
}
}
cachedCommitSHAs = shas;
return shas;
}
var globalEnv, isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2, cachedCommitSHAs;
var init_env2 = __esm({
"node_modules/langsmith/dist/utils/env.js"() {
init_dist();
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 = () => {
if (globalEnv) {
return globalEnv;
}
if (isBrowser2()) {
globalEnv = "browser";
} else if (isNode2()) {
globalEnv = "node";
} else if (isWebWorker2()) {
globalEnv = "webworker";
} else if (isJsDom2()) {
globalEnv = "jsdom";
} else if (isDeno2()) {
globalEnv = "deno";
} else {
globalEnv = "other";
}
return globalEnv;
};
}
});
// 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 t4 = 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, max] of safeRegexReplacements) {
value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
}
return value;
};
var createToken = (name2, value, isGlobal) => {
const safe = makeSafeRegex(value);
const index = R++;
debug4(name2, index, value);
t4[name2] = index;
src[index] = value;
re[index] = new RegExp(value, isGlobal ? "g" : void 0);
safeRe[index] = 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[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})`);
createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NUMERICIDENTIFIER]}|${src[t4.NONNUMERICIDENTIFIER]})`);
createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NUMERICIDENTIFIERLOOSE]}|${src[t4.NONNUMERICIDENTIFIER]})`);
createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`);
createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`);
createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`);
createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`);
createToken("FULL", `^${src[t4.FULLPLAIN]}$`);
createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`);
createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`);
createToken("GTLT", "((?:<|>)?=?)");
createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?)?)?`);
createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?)?)?`);
createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`);
createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.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[t4.COERCEPLAIN]}(?:$|[^\\d])`);
createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?(?:${src[t4.BUILD]})?(?:$|[^\\d])`);
createToken("COERCERTL", src[t4.COERCE], true);
createToken("COERCERTLFULL", src[t4.COERCEFULL], true);
createToken("LONETILDE", "(?:~>?)");
createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = "$1~";
createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`);
createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`);
createToken("LONECARET", "(?:\\^)");
createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true);
exports.caretTrimReplace = "$1^";
createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`);
createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`);
createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`);
createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`);
createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = "$1$2$3";
createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})\\s+-\\s+(${src[t4.XRANGEPLAIN]})\\s*$`);
createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t4.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 = (a4, b3) => {
const anum = numeric.test(a4);
const bnum = numeric.test(b3);
if (anum && bnum) {
a4 = +a4;
b3 = +b3;
}
return a4 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a4 < b3 ? -1 : 1;
};
var rcompareIdentifiers = (a4, b3) => compareIdentifiers(b3, a4);
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: t4 } = 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[t4.LOOSE] : re[t4.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 i4 = 0;
do {
const a4 = this.prerelease[i4];
const b3 = other.prerelease[i4];
debug4("prerelease compare", i4, a4, b3);
if (a4 === void 0 && b3 === void 0) {
return 0;
} else if (b3 === void 0) {
return 1;
} else if (a4 === void 0) {
return -1;
} else if (a4 === b3) {
continue;
} else {
return compareIdentifiers(a4, b3);
}
} while (++i4);
}
compareBuild(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
let i4 = 0;
do {
const a4 = this.build[i4];
const b3 = other.build[i4];
debug4("build compare", i4, a4, b3);
if (a4 === void 0 && b3 === void 0) {
return 0;
} else if (b3 === void 0) {
return 1;
} else if (a4 === void 0) {
return -1;
} else if (a4 === b3) {
continue;
} else {
return compareIdentifiers(a4, b3);
}
} while (++i4);
}
// 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 i4 = this.prerelease.length;
while (--i4 >= 0) {
if (typeof this.prerelease[i4] === "number") {
this.prerelease[i4]++;
i4 = -2;
}
}
if (i4 === -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 parse3 = (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 = parse3;
}
});
// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
"node_modules/semver/functions/valid.js"(exports, module2) {
var parse3 = require_parse();
var valid = (version2, options) => {
const v6 = parse3(version2, options);
return v6 ? v6.version : null;
};
module2.exports = valid;
}
});
// node_modules/semver/functions/clean.js
var require_clean = __commonJS({
"node_modules/semver/functions/clean.js"(exports, module2) {
var parse3 = require_parse();
var clean = (version2, options) => {
const s4 = parse3(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 parse3 = require_parse();
var diff = (version1, version2) => {
const v1 = parse3(version1, null, true);
const v22 = parse3(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 = (a4, loose) => new SemVer(a4, 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 = (a4, loose) => new SemVer(a4, 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 = (a4, loose) => new SemVer(a4, loose).patch;
module2.exports = patch;
}
});
// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
"node_modules/semver/functions/prerelease.js"(exports, module2) {
var parse3 = require_parse();
var prerelease = (version2, options) => {
const parsed = parse3(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 = (a4, b3, loose) => new SemVer(a4, 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 = (a4, b3, loose) => compare2(b3, a4, 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 = (a4, b3) => compare2(a4, 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 = (a4, b3, loose) => {
const versionA = new SemVer(a4, 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((a4, b3) => compareBuild(a4, 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((a4, b3) => compareBuild(b3, a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, b3, loose) => compare2(a4, 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 = (a4, op, b3, loose) => {
switch (op) {
case "===":
if (typeof a4 === "object") {
a4 = a4.version;
}
if (typeof b3 === "object") {
b3 = b3.version;
}
return a4 === b3;
case "!==":
if (typeof a4 === "object") {
a4 = a4.version;
}
if (typeof b3 === "object") {
b3 = b3.version;
}
return a4 !== b3;
case "":
case "=":
case "==":
return eq(a4, b3, loose);
case "!=":
return neq(a4, b3, loose);
case ">":
return gt(a4, b3, loose);
case ">=":
return gte(a4, b3, loose);
case "<":
return lt(a4, b3, loose);
case "<=":
return lte(a4, 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 parse3 = require_parse();
var { safeRe: re, t: t4 } = 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 match = null;
if (!options.rtl) {
match = version2.match(options.includePrerelease ? re[t4.COERCEFULL] : re[t4.COERCE]);
} else {
const coerceRtlRegex = options.includePrerelease ? re[t4.COERCERTLFULL] : re[t4.COERCERTL];
let next;
while ((next = coerceRtlRegex.exec(version2)) && (!match || match.index + match[0].length !== version2.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) {
match = next;
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
}
coerceRtlRegex.lastIndex = -1;
}
if (match === null) {
return null;
}
const major = match[2];
const minor = match[3] || "0";
const patch = match[4] || "0";
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
return parse3(`${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 Range = class {
constructor(range, options) {
options = parseOptions(options);
if (range instanceof Range) {
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
return range;
} else {
return new Range(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((c5) => c5.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((c5) => !isNullSet(c5[0]));
if (this.set.length === 0) {
this.set = [first];
} else if (this.set.length > 1) {
for (const c5 of this.set) {
if (c5.length === 1 && isAny(c5[0])) {
this.set = [c5];
break;
}
}
}
}
this.formatted = void 0;
}
get range() {
if (this.formatted === void 0) {
this.formatted = "";
for (let i4 = 0; i4 < this.set.length; i4++) {
if (i4 > 0) {
this.formatted += "||";
}
const comps = this.set[i4];
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[t4.HYPHENRANGELOOSE] : re[t4.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug4("hyphen replace", range);
range = range.replace(re[t4.COMPARATORTRIM], comparatorTrimReplace);
debug4("comparator trim", range);
range = range.replace(re[t4.TILDETRIM], tildeTrimReplace);
debug4("tilde trim", range);
range = range.replace(re[t4.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[t4.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 Range)) {
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 i4 = 0; i4 < this.set.length; i4++) {
if (testSet(this.set[i4], version2, this.options)) {
return true;
}
}
return false;
}
};
module2.exports = Range;
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: t4,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = require_re();
var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
var isNullSet = (c5) => c5.value === "<0.0.0-0";
var isAny = (c5) => c5.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((c5) => replaceTilde(c5, options)).join(" ");
};
var replaceTilde = (comp, options) => {
const r4 = options.loose ? re[t4.TILDELOOSE] : re[t4.TILDE];
return comp.replace(r4, (_2, M, m3, p4, pr) => {
debug4("tilde", comp, _2, M, m3, p4, pr);
let ret;
if (isX(M)) {
ret = "";
} else if (isX(m3)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
} else if (isX(p4)) {
ret = `>=${M}.${m3}.0 <${M}.${+m3 + 1}.0-0`;
} else if (pr) {
debug4("replaceTilde pr", pr);
ret = `>=${M}.${m3}.${p4}-${pr} <${M}.${+m3 + 1}.0-0`;
} else {
ret = `>=${M}.${m3}.${p4} <${M}.${+m3 + 1}.0-0`;
}
debug4("tilde return", ret);
return ret;
});
};
var replaceCarets = (comp, options) => {
return comp.trim().split(/\s+/).map((c5) => replaceCaret(c5, options)).join(" ");
};
var replaceCaret = (comp, options) => {
debug4("caret", comp, options);
const r4 = options.loose ? re[t4.CARETLOOSE] : re[t4.CARET];
const z3 = options.includePrerelease ? "-0" : "";
return comp.replace(r4, (_2, M, m3, p4, pr) => {
debug4("caret", comp, _2, M, m3, p4, pr);
let ret;
if (isX(M)) {
ret = "";
} else if (isX(m3)) {
ret = `>=${M}.0.0${z3} <${+M + 1}.0.0-0`;
} else if (isX(p4)) {
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}.${p4}-${pr} <${M}.${m3}.${+p4 + 1}-0`;
} else {
ret = `>=${M}.${m3}.${p4}-${pr} <${M}.${+m3 + 1}.0-0`;
}
} else {
ret = `>=${M}.${m3}.${p4}-${pr} <${+M + 1}.0.0-0`;
}
} else {
debug4("no pr");
if (M === "0") {
if (m3 === "0") {
ret = `>=${M}.${m3}.${p4}${z3} <${M}.${m3}.${+p4 + 1}-0`;
} else {
ret = `>=${M}.${m3}.${p4}${z3} <${M}.${+m3 + 1}.0-0`;
}
} else {
ret = `>=${M}.${m3}.${p4} <${+M + 1}.0.0-0`;
}
}
debug4("caret return", ret);
return ret;
});
};
var replaceXRanges = (comp, options) => {
debug4("replaceXRanges", comp, options);
return comp.split(/\s+/).map((c5) => replaceXRange(c5, options)).join(" ");
};
var replaceXRange = (comp, options) => {
comp = comp.trim();
const r4 = options.loose ? re[t4.XRANGELOOSE] : re[t4.XRANGE];
return comp.replace(r4, (ret, gtlt, M, m3, p4, pr) => {
debug4("xRange", comp, ret, gtlt, M, m3, p4, pr);
const xM = isX(M);
const xm = xM || isX(m3);
const xp = xm || isX(p4);
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;
}
p4 = 0;
if (gtlt === ">") {
gtlt = ">=";
if (xm) {
M = +M + 1;
m3 = 0;
p4 = 0;
} else {
m3 = +m3 + 1;
p4 = 0;
}
} else if (gtlt === "<=") {
gtlt = "<";
if (xm) {
M = +M + 1;
} else {
m3 = +m3 + 1;
}
}
if (gtlt === "<") {
pr = "-0";
}
ret = `${gtlt + M}.${m3}.${p4}${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[t4.STAR], "");
};
var replaceGTE0 = (comp, options) => {
debug4("replaceGTE0", comp, options);
return comp.trim().replace(re[options.includePrerelease ? t4.GTE0PRE : t4.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 i4 = 0; i4 < set.length; i4++) {
if (!set[i4].test(version2)) {
return false;
}
}
if (version2.prerelease.length && !options.includePrerelease) {
for (let i4 = 0; i4 < set.length; i4++) {
debug4(set[i4].semver);
if (set[i4].semver === Comparator.ANY) {
continue;
}
if (set[i4].semver.prerelease.length > 0) {
const allowed = set[i4].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[t4.COMPARATORLOOSE] : re[t4.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 Range(comp.value, options).test(this.value);
} else if (comp.operator === "") {
if (comp.value === "") {
return true;
}
return new Range(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: t4 } = require_re();
var cmp = require_cmp();
var debug4 = require_debug();
var SemVer = require_semver();
var Range = require_range();
}
});
// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
"node_modules/semver/functions/satisfies.js"(exports, module2) {
var Range = require_range();
var satisfies = (version2, range, options) => {
try {
range = new Range(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 Range = require_range();
var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c5) => c5.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 Range = require_range();
var maxSatisfying = (versions, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions.forEach((v6) => {
if (rangeObj.test(v6)) {
if (!max || maxSV.compare(v6) === -1) {
max = v6;
maxSV = new SemVer(max, options);
}
}
});
return max;
};
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 Range = require_range();
var minSatisfying = (versions, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions.forEach((v6) => {
if (rangeObj.test(v6)) {
if (!min || minSV.compare(v6) === 1) {
min = v6;
minSV = new SemVer(min, options);
}
}
});
return min;
};
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 Range = require_range();
var gt = require_gt();
var minVersion = (range, loose) => {
range = new Range(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 i4 = 0; i4 < range.set.length; ++i4) {
const comparators = range.set[i4];
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 Range = require_range();
var validRange = (range, options) => {
try {
return new Range(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 Range = 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 Range(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 i4 = 0; i4 < range.set.length; ++i4) {
const comparators = range.set[i4];
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 Range = require_range();
var intersects = (r1, r22, options) => {
r1 = new Range(r1, options);
r22 = new Range(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 v6 = versions.sort((a4, b3) => compare2(a4, b3, options));
for (const version2 of v6) {
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 [min, max] of set) {
if (min === max) {
ranges.push(min);
} else if (!max && min === v6[0]) {
ranges.push("*");
} else if (!max) {
ranges.push(`>=${min}`);
} else if (min === v6[0]) {
ranges.push(`<=${max}`);
} else {
ranges.push(`${min} - ${max}`);
}
}
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 Range = 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 Range(sub, options);
dom = new Range(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 c5 of sub) {
if (c5.operator === ">" || c5.operator === ">=") {
gt = higherGT(gt, c5, options);
} else if (c5.operator === "<" || c5.operator === "<=") {
lt = lowerLT(lt, c5, options);
} else {
eqSet.add(c5.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 c5 of dom) {
if (!satisfies(eq, String(c5), 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 c5 of dom) {
hasDomGT = hasDomGT || c5.operator === ">" || c5.operator === ">=";
hasDomLT = hasDomLT || c5.operator === "<" || c5.operator === "<=";
if (gt) {
if (needDomGTPre) {
if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomGTPre.major && c5.semver.minor === needDomGTPre.minor && c5.semver.patch === needDomGTPre.patch) {
needDomGTPre = false;
}
}
if (c5.operator === ">" || c5.operator === ">=") {
higher = higherGT(gt, c5, options);
if (higher === c5 && higher !== gt) {
return false;
}
} else if (gt.operator === ">=" && !satisfies(gt.semver, String(c5), options)) {
return false;
}
}
if (lt) {
if (needDomLTPre) {
if (c5.semver.prerelease && c5.semver.prerelease.length && c5.semver.major === needDomLTPre.major && c5.semver.minor === needDomLTPre.minor && c5.semver.patch === needDomLTPre.patch) {
needDomLTPre = false;
}
}
if (c5.operator === "<" || c5.operator === "<=") {
lower = lowerLT(lt, c5, options);
if (lower === c5 && lower !== lt) {
return false;
}
} else if (lt.operator === "<=" && !satisfies(lt.semver, String(c5), options)) {
return false;
}
}
if (!c5.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 = (a4, b3, options) => {
if (!a4) {
return b3;
}
const comp = compare2(a4.semver, b3.semver, options);
return comp > 0 ? a4 : comp < 0 ? b3 : b3.operator === ">" && a4.operator === ">=" ? b3 : a4;
};
var lowerLT = (a4, b3, options) => {
if (!a4) {
return b3;
}
const comp = compare2(a4.semver, b3.semver, options);
return comp < 0 ? a4 : comp > 0 ? b3 : b3.operator === "<" && a4.operator === "<=" ? b3 : a4;
};
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 parse3 = 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 Range = 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: parse3,
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,
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 isVersionGreaterOrEqual(current_version, target_version) {
const current = (0, import_semver.parse)(current_version);
const target = (0, import_semver.parse)(target_version);
if (!current || !target) {
throw new Error("Invalid version format.");
}
return current.compare(target) >= 0;
}
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, name2] = ownerNamePart.split("/", 2);
if (!owner || !name2) {
throw new Error(`Invalid identifier format: ${identifier}`);
}
return [owner, name2, 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) {
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 i4;
if (typeof val2 === "object" && val2 !== null) {
for (i4 = 0; i4 < stack.length; i4++) {
if (stack[i4] === 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 (i4 = 0; i4 < val2.length; i4++) {
decirc(val2[i4], i4, i4, stack, val2, depth, options);
}
} else {
var keys = Object.keys(val2);
for (i4 = 0; i4 < keys.length; i4++) {
var key = keys[i4];
decirc(val2[key], key, i4, stack, val2, depth, options);
}
}
stack.pop();
}
}
function replaceGetterValues(replacer) {
replacer = typeof replacer !== "undefined" ? replacer : function(k3, v6) {
return v6;
};
return function(key, val2) {
if (replacerStack.length > 0) {
for (var i4 = 0; i4 < replacerStack.length; i4++) {
var part = replacerStack[i4];
if (part[1] === key && part[0] === val2) {
val2 = part[2];
replacerStack.splice(i4, 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
async function mergeRuntimeEnvIntoRunCreates(runs) {
const runtimeEnv = await getRuntimeEnvironment2();
const envVars = getLangChainEnvVarsMetadata();
return runs.map((run) => {
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, Queue, DEFAULT_BATCH_SIZE_LIMIT_BYTES, Client;
var init_client = __esm({
"node_modules/langsmith/dist/client.js"() {
init_esm_browser2();
init_async_caller();
init_messages();
init_env2();
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;
};
Queue = class {
constructor() {
Object.defineProperty(this, "items", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
}
get size() {
return this.items.length;
}
push(item) {
return new Promise((resolve) => {
this.items.push([item, resolve]);
});
}
pop(upToN) {
if (upToN < 1) {
throw new Error("Number of items to pop off may not be less than 1.");
}
const popped = [];
while (popped.length < upToN && this.items.length) {
const item = this.items.shift();
if (item) {
popped.push(item);
} else {
break;
}
}
return [popped.map((it) => it[0]), () => popped.forEach((it) => it[1]())];
}
};
DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520;
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, "batchEndpointSupported", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "autoBatchQueue", {
enumerable: true,
configurable: true,
writable: true,
value: new Queue()
});
Object.defineProperty(this, "pendingAutoBatchedRunLimit", {
enumerable: true,
configurable: true,
writable: true,
value: 100
});
Object.defineProperty(this, "autoBatchTimeout", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "autoBatchInitialDelayMs", {
enumerable: true,
configurable: true,
writable: true,
value: 250
});
Object.defineProperty(this, "autoBatchAggregationDelayMs", {
enumerable: true,
configurable: true,
writable: true,
value: 50
});
Object.defineProperty(this, "serverInfo", {
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
});
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 ?? 12e3;
this.caller = new AsyncCaller(config.callerOptions ?? {});
this.batchIngestCaller = new AsyncCaller({
...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.pendingAutoBatchedRunLimit = config.pendingAutoBatchedRunLimit ?? this.pendingAutoBatchedRunLimit;
this.fetchOptions = config.fetchOptions || {};
}
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 offset = Number(queryParams.get("offset")) || 0;
const limit2 = Number(queryParams.get("limit")) || 100;
while (true) {
queryParams.set("offset", String(offset));
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;
}
offset += 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 drainAutoBatchQueue() {
while (this.autoBatchQueue.size >= 0) {
const [batch, done] = this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);
if (!batch.length) {
done();
return;
}
try {
await this.batchIngestRuns({
runCreates: batch.filter((item) => item.action === "create").map((item) => item.item),
runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
});
} finally {
done();
}
}
}
async processRunOperation(item, immediatelyTriggerBatch) {
const oldTimeout = this.autoBatchTimeout;
clearTimeout(this.autoBatchTimeout);
this.autoBatchTimeout = void 0;
const itemPromise = this.autoBatchQueue.push(item);
if (immediatelyTriggerBatch || this.autoBatchQueue.size > this.pendingAutoBatchedRunLimit) {
await this.drainAutoBatchQueue().catch(console.error);
}
if (this.autoBatchQueue.size > 0) {
this.autoBatchTimeout = setTimeout(() => {
this.autoBatchTimeout = void 0;
void this.drainAutoBatchQueue().catch(console.error);
}, oldTimeout ? this.autoBatchAggregationDelayMs : this.autoBatchInitialDelayMs);
}
return itemPromise;
}
async _getServerInfo() {
const response = await _getFetchImplementation()(`${this.apiUrl}/info`, {
method: "GET",
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(this.timeout_ms),
...this.fetchOptions
});
await raiseForStatus(response, "get server info");
return response.json();
}
async batchEndpointIsSupported() {
try {
this.serverInfo = await this._getServerInfo();
} catch (e4) {
return false;
}
return true;
}
async _getSettings() {
if (!this.settings) {
this.settings = this._get("/settings");
}
return await this.settings;
}
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 mergedRunCreateParams = await mergeRuntimeEnvIntoRunCreates([
runCreate
]);
const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs`, {
method: "POST",
headers,
body: stringify(mergedRunCreateParams[0]),
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;
}
preparedCreateParams = await mergeRuntimeEnvIntoRunCreates(preparedCreateParams);
if (this.batchEndpointSupported === void 0) {
this.batchEndpointSupported = await this.batchEndpointIsSupported();
}
if (!this.batchEndpointSupported) {
this.autoBatchTracing = false;
for (const preparedCreateParam of rawBatch.post) {
await this.createRun(preparedCreateParam);
}
for (const preparedUpdateParam of rawBatch.patch) {
if (preparedUpdateParam.id !== void 0) {
await this.updateRun(preparedUpdateParam.id, preparedUpdateParam);
}
}
return;
}
const sizeLimitBytes = this.serverInfo?.batch_ingest_config?.size_limit_bytes ?? DEFAULT_BATCH_SIZE_LIMIT_BYTES;
const batchChunks = {
post: [],
patch: []
};
let currentBatchSizeBytes = 0;
for (const k3 of ["post", "patch"]) {
const key = k3;
const batchItems = rawBatch[key].reverse();
let batchItem = batchItems.pop();
while (batchItem !== void 0) {
const stringifiedBatchItem = stringify(batchItem);
if (currentBatchSizeBytes > 0 && currentBatchSizeBytes + stringifiedBatchItem.length > sizeLimitBytes) {
await this._postBatchIngestRuns(stringify(batchChunks));
currentBatchSizeBytes = 0;
batchChunks.post = [];
batchChunks.patch = [];
}
currentBatchSizeBytes += stringifiedBatchItem.length;
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);
}
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) {
await this.processRunOperation({ action: "update", item: data }, true);
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((a4, b3) => (a4?.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((name2) => this.readProject({ projectName: name2 }).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((name2) => this.readProject({ projectName: name2 }).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((v6) => urlParams.append(key, v6));
} 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: name2 = 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: name2,
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 (e4) {
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: name2, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata } = {}) {
const params = new URLSearchParams();
if (projectIds !== void 0) {
for (const projectId of projectIds) {
params.append("id", projectId);
}
}
if (name2 !== void 0) {
params.append("name", name2);
}
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: name2 }) {
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 (name2) {
formData.append("name", name2);
}
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(name2, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) {
const body = {
name: name2,
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 (e4) {
if (
// eslint-disable-next-line no-instanceof/no-instanceof
e4 instanceof Error && e4.message.toLocaleLowerCase().includes("not found")
) {
return false;
}
throw e4;
}
}
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 = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) {
const path = "/datasets";
const params = new URLSearchParams({
limit: limit2.toString(),
offset: offset.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}`;
return await this._get(path);
}
async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit: limit2, offset, filter: filter2 } = {}) {
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 (offset !== void 0) {
params.append("offset", offset.toString());
}
if (filter2 !== void 0) {
params.append("filter", filter2);
}
let i4 = 0;
for await (const examples of this._getPaginated("/examples", params)) {
for (const example of examples) {
yield example;
i4++;
}
if (limit2 !== void 0 && i4 >= 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: name2, 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: name2,
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: name2, nameContains, limit: limit2 } = options;
const params = new URLSearchParams();
if (queueIds) {
queueIds.forEach((id, i4) => {
assertUuid(id, `queueIds[${i4}]`);
params.append("ids", id);
});
}
if (name2)
params.append("name", name2);
if (nameContains)
params.append("name_contains", nameContains);
params.append("limit", (limit2 !== void 0 ? Math.min(limit2, 100) : 100).toString());
let count3 = 0;
for await (const queues of this._getPaginated("/annotation-queues", params)) {
yield* queues;
count3++;
if (limit2 !== void 0 && count3 >= 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: name2, description, queueId } = options;
const body = {
name: name2,
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, v6]) => v6 !== 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: name2, 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: name2, 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, i4) => assertUuid(id, `runIds[${i4}]`).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, index) {
const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`;
const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${baseUrl}/${index}`, {
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}` : ""}`);
}
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 serverInfo = await this._getServerInfo();
const useOptimization = isVersionGreaterOrEqual(serverInfo.version, "0.5.23");
let passedCommitHash = commitHash;
if (!useOptimization && commitHash === "latest") {
const latestCommitHash = await this._getLatestCommitHash(`${owner}/${promptName}`);
if (!latestCommitHash) {
throw new Error("No commits found");
} else {
passedCommitHash = latestCommitHash;
}
}
const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${owner}/${promptName}/${passedCommitHash}${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((e4) => e4.inputs),
outputs: examples.flatMap((e4) => e4.outputs ? [e4.outputs] : []),
datasetId: dataset.id
});
} catch (e4) {
console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`);
throw e4;
}
}
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}`);
}
}
};
}
});
// node_modules/langsmith/dist/env.js
var isTracingEnabled;
var init_env3 = __esm({
"node_modules/langsmith/dist/env.js"() {
init_env2();
isTracingEnabled = (tracingEnabled) => {
if (tracingEnabled !== void 0) {
return tracingEnabled;
}
const envVars = ["TRACING_V2", "TRACING"];
return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true");
};
}
});
// node_modules/langsmith/dist/run_trees.js
function stripNonAlphanumeric2(input) {
return input.replace(/[-:.]/g, "");
}
function convertToDottedOrderFormat2(epoch, runId, executionOrder = 1) {
const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");
return stripNonAlphanumeric2(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId;
}
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_env2();
init_client();
init_env3();
init_warn();
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
});
const defaultConfig = RunTree.getDefaultConfig();
const { metadata, ...config } = originalConfig;
const client = config.client ?? RunTree.getSharedClient();
const dedupedMetadata = {
...metadata,
...config?.extra?.metadata
};
config.extra = { ...config.extra, metadata: dedupedMetadata };
Object.assign(this, { ...defaultConfig, ...config, client });
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 = convertToDottedOrderFormat2(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: getEnvironmentVariable2("LANGCHAIN_PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION") ?? // TODO: Deprecate
"default",
child_runs: [],
api_url: getEnvironmentVariable2("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984",
api_key: getEnvironmentVariable2("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
});
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()) {
this.outputs = this.outputs ?? outputs;
this.error = this.error ?? error;
this.end_time = this.end_time ?? endTime;
}
_convertToCreate(run, runtimeEnv, excludeChildRuns = true) {
const runExtra = run.extra ?? {};
if (!runExtra.runtime) {
runExtra.runtime = {};
}
if (runtimeEnv) {
for (const [k3, v6] of Object.entries(runtimeEnv)) {
if (!runExtra.runtime[k3]) {
runExtra.runtime[k3] = v6;
}
}
}
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
};
return persistedRun;
}
async postRun(excludeChildRuns = true) {
try {
const runtimeEnv = await getRuntimeEnvironment2();
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
};
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 client;
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;
client = langChainTracer?.client;
tracingEnabled = tracingEnabled || !!langChainTracer;
}
if (!parentRun) {
return new RunTree({
...props,
client,
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,
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/index.js
var __version__;
var init_dist = __esm({
"node_modules/langsmith/dist/index.js"() {
init_client();
init_run_trees();
init_fetch();
__version__ = "0.1.61";
}
});
// node_modules/langsmith/index.js
var init_langsmith = __esm({
"node_modules/langsmith/index.js"() {
init_dist();
}
});
// 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 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};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, i4, arr2) => {
const name2 = `${parent.execution_order}:${parent.run_type}:${parent.name}`;
return i4 === arr2.length - 1 ? wrap(import_ansi_styles.default.bold, name2) : name2;
}).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((p4) => p4.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/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 match = /```(json)?(.*)```/s.exec(s4);
if (!match) {
return parser(s4);
} else {
return parser(match[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 i4 = stack.length - 1; i4 >= 0; i4 -= 1) {
new_s += stack[i4];
}
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 : "";
}
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 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, name2) {
if (typeof fields === "string") {
fields = { content: fields, name: name2, tool_call_id };
}
super(fields);
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";
}
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 (e4) {
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: []
};
} 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 (e4) {
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
};
}
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 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
};
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 _constructMessageFromParams(params) {
const { type, ...rest } = params;
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 === "tool" && "tool_call_id" in rest) {
return new ToolMessage({
...rest,
content: rest.content,
tool_call_id: rest.tool_call_id,
name: rest.name
});
} else {
throw new Error(`Unable to coerce message from array: only human, AI, or system message coercion is currently supported.`);
}
}
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_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/@langchain/core/dist/tracers/tracer_langchain.js
var LangChainTracer;
var init_tracer_langchain = __esm({
"node_modules/@langchain/core/dist/tracers/tracer_langchain.js"() {
init_langsmith();
init_run_trees2();
init_traceable2();
init_env();
init_base2();
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 } = fields;
this.projectName = projectName ?? getEnvironmentVariable("LANGCHAIN_PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION");
this.exampleId = exampleId;
this.client = client ?? new Client({});
const traceableTree = LangChainTracer.getTraceableRunTree();
if (traceableTree) {
this.updateFromRunTree(traceableTree);
}
}
async _convertToCreate(run, example_id = void 0) {
return {
...run,
extra: {
...run.extra,
runtime: await getRuntimeEnvironment()
},
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
};
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((a4, b3) => {
if (!a4[1] || !b3[1])
return 0;
return a4[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/callbacks/promises.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
});
}
async function consumeCallback(promiseFn, wait) {
if (wait === true) {
await promiseFn();
} else {
if (typeof queue === "undefined") {
queue = createQueue();
}
void queue.add(promiseFn);
}
}
var import_p_queue2, queue;
var init_promises = __esm({
"node_modules/@langchain/core/dist/callbacks/promises.js"() {
import_p_queue2 = __toESM(require_dist(), 1);
}
});
// node_modules/@langchain/core/dist/utils/callbacks.js
var isTracingEnabled2;
var init_callbacks = __esm({
"node_modules/@langchain/core/dist/utils/callbacks.js"() {
init_env();
isTracingEnabled2 = (tracingEnabled) => {
if (tracingEnabled !== void 0) {
return tracingEnabled;
}
const envVars = [
"LANGSMITH_TRACING_V2",
"LANGCHAIN_TRACING_V2",
"LANGSMITH_TRACING",
"LANGCHAIN_TRACING"
];
return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true");
};
}
});
// 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_env();
init_tracer_langchain();
init_promises();
init_callbacks();
init_base2();
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) {
await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
if (!handler.ignoreLLM) {
try {
await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags);
} 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) {
await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
if (!handler.ignoreLLM) {
try {
await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags);
} 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(tool, 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(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);
}
return consumeCallback(async () => {
try {
await handler.handleToolStart?.(tool, 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((h4) => h4.name === "console_callback_handler").some((h4) => h4.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 = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose;
const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled2();
const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("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;
}
}
}
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/index.js
var MockAsyncLocalStorage2, mockAsyncLocalStorage2, TRACING_ALS_KEY2, LC_CHILD_KEY, AsyncLocalStorageProvider2, AsyncLocalStorageProviderSingleton2;
var init_singletons = __esm({
"node_modules/@langchain/core/dist/singletons/index.js"() {
init_langsmith();
init_manager();
MockAsyncLocalStorage2 = class {
getStore() {
return void 0;
}
run(_store, callback) {
return callback();
}
};
mockAsyncLocalStorage2 = new MockAsyncLocalStorage2();
TRACING_ALS_KEY2 = Symbol.for("ls:tracing_async_local_storage");
LC_CHILD_KEY = Symbol.for("lc:child_config");
AsyncLocalStorageProvider2 = class {
getInstance() {
return globalThis[TRACING_ALS_KEY2] ?? 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 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 };
}
return storage.run(runTree, callback);
}
initializeGlobalInstance(instance) {
if (globalThis[TRACING_ALS_KEY2] === void 0) {
globalThis[TRACING_ALS_KEY2] = instance;
}
}
};
AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2();
}
});
// 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_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 (e4) {
this.reader.releaseLock();
throw e4;
}
}
async return() {
this.ensureReader();
if (this.locked) {
const cancelPromise = this.reader.cancel();
this.reader.releaseLock();
await cancelPromise;
}
return { done: true, value: void 0 };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async throw(e4) {
this.ensureReader();
if (this.locked) {
const cancelPromise = this.reader.cancel();
this.reader.releaseLock();
await cancelPromise;
}
throw e4;
}
[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(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(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(e4) {
return this.generator.throw(e4);
}
[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"
});
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 count3 = this.counterMapByRunName[run.name];
this.keyMapByRunId[run.id] = count3 === 1 ? run.name : `${run.name}:${count3}`;
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: name2, serialized }) {
if (name2 !== void 0) {
return name2;
}
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"
});
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/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((c5) => !!c5)) {
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;
}
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/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(([name2, def]) => [
def._def,
{
def: def._def,
path: [..._options.basePath, _options.definitionPath, name2],
// 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?.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, i4) => 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: 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"
};
function processPattern(value) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(value) : value;
}
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(`^${processPattern(check.value)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${processPattern(check.value)}$`), 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(processPattern(check.value)), 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 "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;
}
var emojiRegex2, zodPatterns, escapeNonAlphaNumeric, addFormat, addPattern, processRegExp;
var init_string = __esm({
"node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() {
init_errorMessages();
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])$/,
/**
* 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}$/
};
escapeNonAlphaNumeric = (value) => Array.from(value).map((c5) => /[a-zA-Z0-9]/.test(c5) ? c5 : `\\${c5}`).join("");
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);
}
};
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: processRegExp(regex2, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else {
setResponseValueAndErrors(schema, "pattern", processRegExp(regex2, refs), message, refs);
}
};
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 i4 = 0; i4 < source.length; i4++) {
if (isEscaped) {
pattern += source[i4];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i4].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i4];
pattern += `${source[i4 - 2]}-${source[i4]}`.toUpperCase();
inCharRange = false;
} else if (source[i4 + 1] === "-" && source[i4 + 2]?.match(/[a-z]/)) {
pattern += source[i4];
inCharRange = true;
} else {
pattern += `${source[i4]}${source[i4].toUpperCase()}`;
}
continue;
}
} else if (source[i4].match(/[a-z]/)) {
pattern += `[${source[i4]}${source[i4].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i4] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i4] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i4] === ".") {
pattern += inCharGroup ? `${source[i4]}\r
` : `[${source[i4]}\r
]`;
continue;
}
pattern += source[i4];
if (source[i4] === "\\") {
isEscaped = true;
} else if (inCharGroup && source[i4] === "]") {
inCharGroup = false;
} else if (!inCharGroup && source[i4] === "[") {
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/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(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]: 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 keyType = Object.entries(parseStringDef(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;
}
var init_record = __esm({
"node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() {
init_lib();
init_parseDef();
init_string();
}
});
// 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, i4, a4) => a4.indexOf(x2) === i4);
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, i4) => parseDef(x2._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", `${i4}`]
})).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 result = {
type: "object",
...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
if (propDef === void 0 || propDef._def === void 0)
return acc;
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: propDef.isOptional() ? 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_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 a4 = parseDef(def.in._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"]
});
const b3 = parseDef(def.out._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", a4 ? "1" : "0"]
});
return {
allOf: [a4, 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, i4) => parseDef(x2._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i4}`]
})).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, i4) => parseDef(x2._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i4}`]
})).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, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return {};
}
return refs.$refStrategy === "seen" ? {} : void 0;
}
}
};
getRelativePath = (pathA, pathB) => {
let i4 = 0;
for (; i4 < pathA.length && i4 < pathB.length; i4++) {
if (pathA[i4] !== pathB[i4])
break;
}
return [(pathA.length - i4).toString(), ...pathB.slice(i4)].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, [name3, schema2]) => ({
...acc,
[name3]: parseDef(schema2._def, {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name3]
}, true) ?? {}
}), {}) : void 0;
const name2 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
const main = parseDef(schema._def, name2 === void 0 ? refs : {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name2]
}, 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 = name2 === void 0 ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name2
].join("/"),
[refs.definitionPath]: {
...definitions,
[name2]: 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/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 _adjustMermaidEdge(edge, nodes) {
const sourceNodeLabel = nodes[edge.source] ?? edge.source;
const targetNodeLabel = nodes[edge.target] ?? edge.target;
return [sourceNodeLabel, targetNodeLabel];
}
function _generateMermaidGraphStyles(nodeColors) {
let styles2 = "";
for (const [className, color2] of Object.entries(nodeColors)) {
styles2 += ` classDef ${className}class fill:${color2};
`;
}
return styles2;
}
function drawMermaid(nodes, edges, config) {
const { firstNodeLabel, lastNodeLabel, 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}]):::otherclass"
};
if (firstNodeLabel !== void 0) {
formatDict[firstNodeLabel] = "{0}[{0}]:::startclass";
}
if (lastNodeLabel !== void 0) {
formatDict[lastNodeLabel] = "{0}[{0}]:::endclass";
}
for (const node of Object.values(nodes)) {
const nodeLabel = formatDict[node] ?? formatDict[defaultClassLabel];
const escapedNodeLabel = _escapeNodeLabel(node);
const nodeParts = node.split(":");
const nodeSplit = nodeParts[nodeParts.length - 1];
mermaidGraph += ` ${nodeLabel.replace(/\{0\}/g, escapedNodeLabel).replace(/\{1\}/g, nodeSplit)};
`;
}
}
let subgraph = "";
for (const edge of edges) {
const sourcePrefix = edge.source.includes(":") ? edge.source.split(":")[0] : void 0;
const targetPrefix = edge.target.includes(":") ? edge.target.split(":")[0] : void 0;
if (subgraph !== "" && (subgraph !== sourcePrefix || subgraph !== targetPrefix)) {
mermaidGraph += " end\n";
subgraph = "";
}
if (subgraph === "" && sourcePrefix !== void 0 && sourcePrefix === targetPrefix) {
mermaidGraph = ` subgraph ${sourcePrefix}
`;
subgraph = sourcePrefix;
}
const [source, target] = _adjustMermaidEdge(edge, nodes);
let edgeLabel = "";
if (edge.data !== void 0) {
let edgeData = edge.data;
const words = edgeData.split(" ");
if (words.length > wrapLabelNWords) {
edgeData = words.reduce((acc, word, i4) => {
if (i4 % wrapLabelNWords === 0)
acc.push("");
acc[acc.length - 1] += ` ${word}`;
return acc;
}, []).join("<br>");
}
if (edge.conditional) {
edgeLabel = ` -. ${edgeData} .-> `;
} else {
edgeLabel = ` -- ${edgeData} --> `;
}
} else {
if (edge.conditional) {
edgeLabel = ` -.-> `;
} else {
edgeLabel = ` --> `;
}
}
mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};
`;
}
if (subgraph !== "") {
mermaidGraph += "end\n";
}
if (withStyles && nodeColors !== void 0) {
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 init_graph_mermaid = __esm({
"node_modules/@langchain/core/dist/runnables/graph_mermaid.js"() {
}
});
// node_modules/@langchain/core/dist/runnables/graph.js
function nodeDataStr(node) {
if (!validate_default(node.id)) {
return node.id;
} else if (isRunnableInterface(node.data)) {
try {
let data = node.data.getName();
data = data.startsWith("Runnable") ? data.slice("Runnable".length) : data;
if (data.length > MAX_DATA_DISPLAY_NAME_LENGTH) {
data = `${data.substring(0, MAX_DATA_DISPLAY_NAME_LENGTH)}...`;
}
return data;
} catch (error) {
return node.data.getName();
}
} else {
return node.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 }
};
}
}
var MAX_DATA_DISPLAY_NAME_LENGTH, Graph;
var init_graph = __esm({
"node_modules/@langchain/core/dist/runnables/graph.js"() {
init_esm();
init_esm_browser();
init_utils3();
init_graph_mermaid();
MAX_DATA_DISPLAY_NAME_LENGTH = 42;
Graph = class {
constructor() {
Object.defineProperty(this, "nodes", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "edges", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
}
// 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, i4) => {
stableNodeIds[node.id] = validate_default(node.id) ? i4 : 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) {
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 };
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() {
const targets = new Set(this.edges.map((edge) => edge.target));
const found = [];
Object.values(this.nodes).forEach((node) => {
if (!targets.has(node.id)) {
found.push(node);
}
});
return found[0];
}
lastNode() {
const sources = new Set(this.edges.map((edge) => edge.source));
const found = [];
Object.values(this.nodes).forEach((node) => {
if (!sources.has(node.id)) {
found.push(node);
}
});
return found[0];
}
/**
* 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) {
const outgoingEdges = this.edges.filter((edge) => edge.source === firstNode.id);
if (Object.keys(this.nodes).length === 1 || outgoingEdges.length === 1) {
this.removeNode(firstNode);
}
}
}
trimLastNode() {
const lastNode = this.lastNode();
if (lastNode) {
const incomingEdges = this.edges.filter((edge) => edge.target === lastNode.id);
if (Object.keys(this.nodes).length === 1 || incomingEdges.length === 1) {
this.removeNode(lastNode);
}
}
}
drawMermaid(params) {
const { withStyles, curveStyle, nodeColors = { start: "#ffdfba", end: "#baffc9", other: "#fad7de" }, wrapLabelNWords } = params ?? {};
const nodes = {};
for (const node of Object.values(this.nodes)) {
nodes[node.id] = nodeDataStr(node);
}
const firstNode = this.firstNode();
const firstNodeLabel = firstNode ? nodeDataStr(firstNode) : void 0;
const lastNode = this.lastNode();
const lastNodeLabel = lastNode ? nodeDataStr(lastNode) : void 0;
return drawMermaid(nodes, this.edges, {
firstNodeLabel,
lastNodeLabel,
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(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(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();
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 name2 = fields.name ?? runnable.getName();
const description = fields.description ?? fields.schema?.description;
if (fields.schema.constructor === z.ZodString) {
return new RunnableToolLike({
name: name2,
description,
schema: z.object({
input: z.string()
}).transform((input) => input.input),
bound: runnable
});
}
return new RunnableToolLike({
name: name2,
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 name2 = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.name ?? this.constructor.lc_name() ?? this.constructor.name
);
return suffix ? `${name2}${suffix}` : name2;
}
/**
* 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, i4) => ensureConfig(i4 === 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: (e4) => {
throw e4;
}
});
const batchCalls = inputs.map((input, i4) => caller2.call(async () => {
try {
const result = await this.invoke(input, configList[i4]);
return result;
} catch (e4) {
if (batchOptions?.returnExceptions) {
return e4;
}
throw e4;
}
}));
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 (e4) {
await runManager?.handleChainError(e4);
throw e4;
}
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, i4) => {
const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i4], "input"), optionsList[i4].runId, optionsList[i4].runType, void 0, void 0, optionsList[i4].runName ?? this.getName());
delete optionsList[i4].runId;
return handleStartRes;
}));
let outputs;
try {
const promise = func.call(this, inputs, optionsList, runManagers, batchOptions);
outputs = await raceWithSignal(promise, optionsList?.[0]?.signal);
} catch (e4) {
await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e4)));
throw e4;
}
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 (e4) {
await runManager?.handleChainError(e4, void 0, void 0, void 0, {
inputs: _coerceToDict2(finalInput, "input")
});
throw e4;
}
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 outerThis = this;
async function consumeRunnableStream() {
try {
const runnableStream = await outerThis.stream(input, config);
const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);
for await (const _2 of tappedStream) {
}
} 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 {
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, i4) => i4).filter((i4) => resultsMap[i4.toString()] === void 0 || // eslint-disable-next-line no-instanceof/no-instanceof
resultsMap[i4.toString()] instanceof Error);
const remainingInputs = remainingIndexes.map((i4) => inputs[i4]);
const patchedConfigs = remainingIndexes.map((i4) => this._patchConfigForRetry(attemptNumber, configs?.[i4], runManagers?.[i4]));
const results = await super.batch(remainingInputs, patchedConfigs, {
...batchOptions,
returnExceptions: true
});
let firstException;
for (let i4 = 0; i4 < results.length; i4 += 1) {
const result = results[i4];
const resultMapIndex = remainingIndexes[i4];
if (result instanceof Error) {
if (firstException === void 0) {
firstException = result;
firstException.input = remainingInputs[i4];
}
}
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 (e4) {
if (batchOptions?.returnExceptions !== true) {
throw e4;
}
}
return Object.keys(resultsMap).sort((a4, b3) => parseInt(a4, 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, "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;
}
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 i4 = 0; i4 < initialSteps.length; i4 += 1) {
const step = initialSteps[i4];
const promise = step.invoke(nextStepInput, patchConfig(config, {
callbacks: runManager?.getChild(`seq:step:${i4 + 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(`seq:step:${this.steps.length}`)
}));
} catch (e4) {
await runManager?.handleChainError(e4);
throw e4;
}
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, i4) => {
const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i4], "input"), configList[i4].runId, void 0, void 0, void 0, configList[i4].runName);
delete configList[i4].runId;
return handleStartRes;
}));
let nextStepInputs = inputs;
try {
for (let i4 = 0; i4 < this.steps.length; i4 += 1) {
const step = this.steps[i4];
const promise = step.batch(nextStepInputs, runManagers.map((runManager, j3) => {
const childRunManager = runManager?.getChild(`seq:step:${i4 + 1}`);
return patchConfig(configList[j3], { callbacks: childRunManager });
}), batchOptions);
nextStepInputs = await raceWithSignal(promise, configList[0]?.signal);
}
} catch (e4) {
await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e4)));
throw e4;
}
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(`seq:step:1`)
}));
for (let i4 = 1; i4 < steps.length; i4 += 1) {
const step = steps[i4];
finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, {
callbacks: runManager?.getChild(`seq:step:${i4 + 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 (e4) {
finalOutput = void 0;
concatSupported = false;
}
}
}
}
} catch (e4) {
await runManager?.handleChainError(e4);
throw e4;
}
await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output"));
}
getGraph(config) {
const graph = new Graph();
let currentLastNode = null;
this.steps.forEach((step, index) => {
const stepGraph = step.getGraph(config);
if (index !== 0) {
stepGraph.trimFirstNode();
}
if (index !== 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], name2) {
return new RunnableSequence({
first: _coerceToRunnable(first),
middle: runnables.slice(0, -1).map(_coerceToRunnable),
last: _coerceToRunnable(runnables[runnables.length - 1]),
name: name2
});
}
};
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 (e4) {
await runManager?.handleChainError(e4);
throw e4;
}
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], i4) => {
const gen = runnable.transform(inputCopies[i4], 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(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 (e4) {
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 (e4) {
finalOutput = chunk;
}
}
}
output = finalOutput;
}
resolve(output);
} catch (e4) {
reject(e4);
}
});
});
}
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 (e4) {
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(childConfig, async () => {
try {
const res = await this.func(finalChunk, {
...childConfig,
config: childConfig
});
resolve(res);
} catch (e4) {
reject(e4);
}
});
});
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(options);
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;
for (const runnable of this.runnables()) {
config?.signal?.throwIfAborted();
try {
const output = await runnable.invoke(input, patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }));
await runManager?.handleChainEnd(_coerceToDict2(output, "output"));
return output;
} catch (e4) {
if (firstError === void 0) {
firstError = e4;
}
}
}
if (firstError === void 0) {
throw new Error("No error stored at end of fallback.");
}
await runManager?.handleChainError(firstError);
throw firstError;
}
async *_streamIterator(input, options) {
const config = ensureConfig(options);
const callbackManager_ = await getCallbackManagerForConfig(options);
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 {
stream = await runnable.stream(input, childConfig);
break;
} catch (e4) {
if (firstError === void 0) {
firstError = e4;
}
}
}
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 (e4) {
output = void 0;
}
}
} catch (e4) {
await runManager?.handleChainError(e4);
throw e4;
}
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, i4) => {
const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i4], "input"), configList[i4].runId, void 0, void 0, void 0, configList[i4].runName);
delete configList[i4].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, i4) => runManager?.handleChainEnd(_coerceToDict2(outputs[i4], "output"))));
return outputs;
} catch (e4) {
if (firstError === void 0) {
firstError = e4;
}
}
}
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((v6) => v6[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 (e4) {
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_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();
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");
}
}
}
};
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/deep-compare-strict.js
function deepCompareStrict(a4, b3) {
const typeofa = typeof a4;
if (typeofa !== typeof b3) {
return false;
}
if (Array.isArray(a4)) {
if (!Array.isArray(b3)) {
return false;
}
const length = a4.length;
if (length !== b3.length) {
return false;
}
for (let i4 = 0; i4 < length; i4++) {
if (!deepCompareStrict(a4[i4], b3[i4])) {
return false;
}
}
return true;
}
if (typeofa === "object") {
if (!a4 || !b3) {
return a4 === b3;
}
const aKeys = Object.keys(a4);
const bKeys = Object.keys(b3);
const length = aKeys.length;
if (length !== bKeys.length) {
return false;
}
for (const k3 of aKeys) {
if (!deepCompareStrict(a4[k3], b3[k3])) {
return false;
}
}
return true;
}
return a4 === b3;
}
var init_deep_compare_strict = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/deep-compare-strict.js"() {
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/pointer.js
var init_pointer = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/pointer.js"() {
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/dereference.js
var initialBaseURI;
var init_dereference = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/dereference.js"() {
init_pointer();
initialBaseURI = // @ts-ignore
typeof self !== "undefined" && self.location && self.location.origin !== "null" ? (
//@ts-ignore
/* @__PURE__ */ new URL(self.location.origin + self.location.pathname + location.search)
) : /* @__PURE__ */ new URL("https://github.com/cfworker");
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/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);
return true;
} catch (e4) {
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/@langchain/core/dist/utils/@cfworker/json-schema/src/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 [name2, host, ...rest] = input.split("@");
if (!name2 || !host || rest.length !== 0 || name2.length > 64 || host.length > 253)
return false;
if (name2[0] === "." || name2.endsWith(".") || name2.includes(".."))
return false;
if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name2))
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: /* @__PURE__ */ time.bind(void 0, false),
"date-time": date_time,
duration: DURATION,
uri,
"uri-reference": /* @__PURE__ */ bind(URIREF),
"uri-template": /* @__PURE__ */ bind(URITEMPLATE),
url: /* @__PURE__ */ bind(URL_),
email: EMAIL,
hostname: /* @__PURE__ */ bind(HOSTNAME),
ipv4: /* @__PURE__ */ bind(IPV4),
ipv6: /* @__PURE__ */ bind(IPV6),
regex,
uuid: /* @__PURE__ */ bind(UUID),
"json-pointer": /* @__PURE__ */ bind(JSON_POINTER),
"json-pointer-uri-fragment": /* @__PURE__ */ bind(JSON_POINTER_URI_FRAGMENT),
"relative-json-pointer": /* @__PURE__ */ bind(RELATIVE_JSON_POINTER)
};
fastFormat = {
...fullFormat,
date: /* @__PURE__ */ bind(FASTDATE),
time: /* @__PURE__ */ bind(FASTTIME),
"date-time": /* @__PURE__ */ bind(FASTDATETIME),
"uri-reference": /* @__PURE__ */ 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/@langchain/core/dist/utils/@cfworker/json-schema/src/types.js
var init_types = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/types.js"() {
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/ucs2-length.js
var init_ucs2_length = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/ucs2-length.js"() {
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validate.js
var init_validate3 = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validate.js"() {
init_deep_compare_strict();
init_dereference();
init_format();
init_pointer();
init_ucs2_length();
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validator.js
var init_validator = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/validator.js"() {
init_dereference();
init_validate3();
}
});
// node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/index.js
var init_src = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/src/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/utils/@cfworker/json-schema/index.js
var init_json_schema = __esm({
"node_modules/@langchain/core/dist/utils/@cfworker/json-schema/index.js"() {
init_src();
}
});
// 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_base5();
init_base3();
init_utils2();
init_outputs();
init_json_schema();
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(([name2, description]) => [name2, 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 (e4) {
throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e4}`, 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 i4 = 0, valueLength = value.length; i4 < valueLength; ++i4) {
chr = value.charAt(i4);
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 i4 = 0, numTokens = tokens.length; i4 < numTokens; ++i4) {
token = tokens[i4];
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 i4 = 0, numTokens = tokens.length; i4 < numTokens; ++i4) {
token = tokens[i4];
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 match = this.tail.match(re);
if (!match || match.index !== 0)
return "";
var string = match[0];
this.tail = this.tail.substring(string.length);
this.pos += string.length;
return string;
};
Scanner.prototype.scanUntil = function scanUntil(re) {
var index = this.tail.search(re), match;
switch (index) {
case -1:
match = this.tail;
this.tail = "";
break;
case 0:
match = "";
break;
default:
match = this.tail.substring(0, index);
this.tail = this.tail.substring(index);
}
this.pos += match.length;
return match;
};
Context.prototype.push = function push(view) {
return new Context(view, this);
};
Context.prototype.lookup = function lookup(name2) {
var cache2 = this.cache;
var value;
if (cache2.hasOwnProperty(name2)) {
value = cache2[name2];
} else {
var context = this, intermediateValue, names, index, lookupHit = false;
while (context) {
if (name2.indexOf(".") > 0) {
intermediateValue = context.view;
names = name2.split(".");
index = 0;
while (intermediateValue != null && index < names.length) {
if (index === names.length - 1)
lookupHit = hasProperty(intermediateValue, names[index]) || primitiveHasOwnProperty(intermediateValue, names[index]);
intermediateValue = intermediateValue[names[index++]];
}
} else {
intermediateValue = context.view[name2];
lookupHit = hasProperty(context.view, name2);
}
if (lookupHit) {
value = intermediateValue;
break;
}
context = context.parent;
}
cache2[name2] = 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 i4 = 0, numTokens = tokens.length; i4 < numTokens; ++i4) {
value = void 0;
token = tokens[i4];
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 i4 = 0; i4 < partialByNl.length; i4++) {
if (partialByNl[i4].length && (i4 > 0 || !lineHasNonSpace)) {
partialByNl[i4] = filteredIndentation + partialByNl[i4];
}
}
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();
parseFString = (template) => {
const chars = template.split("");
const nodes = [];
const nextBracket = (bracket, start) => {
for (let i5 = start; i5 < chars.length; i5 += 1) {
if (bracket.includes(chars[i5])) {
return i5;
}
}
return -1;
};
let i4 = 0;
while (i4 < chars.length) {
if (chars[i4] === "{" && i4 + 1 < chars.length && chars[i4 + 1] === "{") {
nodes.push({ type: "literal", text: "{" });
i4 += 2;
} else if (chars[i4] === "}" && i4 + 1 < chars.length && chars[i4 + 1] === "}") {
nodes.push({ type: "literal", text: "}" });
i4 += 2;
} else if (chars[i4] === "{") {
const j3 = nextBracket("}", i4);
if (j3 < 0) {
throw new Error("Unclosed '{' in template.");
}
nodes.push({
type: "variable",
name: chars.slice(i4 + 1, j3).join("")
});
i4 = j3 + 1;
} else if (chars[i4] === "}") {
throw new Error("Single '}' in template.");
} else {
const next = nextBracket("{}", i4);
const text = (next < 0 ? chars.slice(i4) : chars.slice(i4, next)).join("");
nodes.push({ type: "literal", text });
i4 = next < 0 ? chars.length : next;
}
}
return nodes;
};
mustacheTemplateToNodes = (template) => template.map((temp) => {
if (temp[0] === "name") {
const name2 = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1];
return { type: "variable", name: name2 };
} 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) => parseFString(template).reduce((res, node) => {
if (node.type === "variable") {
if (node.name in values) {
return res + values[node.name];
}
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) => DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);
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, v6) => {
acc[v6] = "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 (e4) {
throw new Error(`Invalid prompt schema: ${e4.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 (typeof messageContent !== "string" || messageContent[0] !== "{" || messageContent[messageContent.length - 1] !== "}") {
throw new Error(`Invalid placeholder template: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by curly braces.`);
}
const variableName = messageContent.slice(1, -1);
return new MessagesPlaceholder({ variableName, optional: true });
}
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();
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 (e4) {
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: ${e4.message}`
].join("\n\n"));
error.name = "InputFormatError";
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(name2) {
switch (name2) {
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)) {
throw new Error(`Missing value for input variable \`${inputVariable.toString()}\``);
}
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
});
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) {
return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { ...options, 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/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 isObject(input) {
return input != null && Object.prototype.toString.call(input) === "[object Object]";
}
function hasOwnProp(a4, b3) {
return Object.prototype.hasOwnProperty.call(a4, 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 isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]";
}
function isDate(input) {
return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]";
}
function map(arr2, fn) {
var res = [], i4, arrLen = arr2.length;
for (i4 = 0; i4 < arrLen; ++i4) {
res.push(fn(arr2[i4], i4));
}
return res;
}
function extend(a4, b3) {
for (var i4 in b3) {
if (hasOwnProp(b3, i4)) {
a4[i4] = b3[i4];
}
}
if (hasOwnProp(b3, "toString")) {
a4.toString = b3.toString;
}
if (hasOwnProp(b3, "valueOf")) {
a4.valueOf = b3.valueOf;
}
return a4;
}
function createUTC(input, format2, locale2, strict) {
return createLocalOrUTC(input, format2, locale2, strict, 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 t4 = Object(this), len = t4.length >>> 0, i4;
for (i4 = 0; i4 < len; i4++) {
if (i4 in t4 && fun.call(this, t4[i4], i4, t4)) {
return true;
}
}
return false;
};
}
function isValid2(m3) {
if (m3._isValid == null) {
var flags = getParsingFlags(m3), parsedParts = some.call(flags.parsedDateParts, function(i4) {
return i4 != 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 i4, prop, val2, momentPropertiesLen = momentProperties.length;
if (!isUndefined(from2._isAMomentObject)) {
to2._isAMomentObject = from2._isAMomentObject;
}
if (!isUndefined(from2._i)) {
to2._i = from2._i;
}
if (!isUndefined(from2._f)) {
to2._f = from2._f;
}
if (!isUndefined(from2._l)) {
to2._l = from2._l;
}
if (!isUndefined(from2._strict)) {
to2._strict = from2._strict;
}
if (!isUndefined(from2._tzm)) {
to2._tzm = from2._tzm;
}
if (!isUndefined(from2._isUTC)) {
to2._isUTC = from2._isUTC;
}
if (!isUndefined(from2._offset)) {
to2._offset = from2._offset;
}
if (!isUndefined(from2._pf)) {
to2._pf = getParsingFlags(from2);
}
if (!isUndefined(from2._locale)) {
to2._locale = from2._locale;
}
if (momentPropertiesLen > 0) {
for (i4 = 0; i4 < momentPropertiesLen; i4++) {
prop = momentProperties[i4];
val2 = from2[prop];
if (!isUndefined(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, i4, key, argLen = arguments.length;
for (i4 = 0; i4 < argLen; i4++) {
arg = "";
if (typeof arguments[i4] === "object") {
arg += "\n[" + i4 + "] ";
for (key in arguments[0]) {
if (hasOwnProp(arguments[0], key)) {
arg += key + ": " + arguments[0][key] + ", ";
}
}
arg = arg.slice(0, -2);
} else {
arg = arguments[i4];
}
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(name2, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name2, msg);
}
if (!deprecations[name2]) {
warn2(msg);
deprecations[name2] = 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, i4;
for (i4 in config) {
if (hasOwnProp(config, i4)) {
prop = config[i4];
if (isFunction2(prop)) {
this[i4] = prop;
} else {
this["_" + i4] = prop;
}
}
}
this._config = config;
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source
);
}
function mergeConfigs2(parentConfig, childConfig) {
var res = extend({}, parentConfig), prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(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) && isObject(parentConfig[prop])) {
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function(obj) {
var i4, res = [];
for (i4 in obj) {
if (hasOwnProp(obj, i4)) {
res.push(i4);
}
}
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, now2) {
var output = this._calendar[key] || this._calendar["sameElse"];
return isFunction2(output) ? output.call(mom, now2) : 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), i4, length;
for (i4 = 0, length = array.length; i4 < length; i4++) {
if (formatTokenFunctions[array[i4]]) {
array[i4] = formatTokenFunctions[array[i4]];
} else {
array[i4] = removeFormattingTokens(array[i4]);
}
}
return function(mom) {
var output = "", i5;
for (i5 = 0; i5 < length; i5++) {
output += isFunction2(array[i5]) ? array[i5].call(mom, format2) : array[i5];
}
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 i4 = 5;
function replaceLongDateFormatTokens(input) {
return locale2.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i4 >= 0 && localFormattingTokens.test(format2)) {
format2 = format2.replace(
localFormattingTokens,
replaceLongDateFormatTokens
);
localFormattingTokens.lastIndex = 0;
i4 -= 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 = [], u4;
for (u4 in unitsObj) {
if (hasOwnProp(unitsObj, u4)) {
units.push({ unit: u4, priority: priorities[u4] });
}
}
units.sort(function(a4, b3) {
return a4.priority - b3.priority;
});
return units;
}
function isLeapYear3(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" && isLeapYear3(mom.year()) && mom.month() === 1 && mom.date() === 29) {
value = toInt(value);
mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](
value,
mom.month(),
daysInMonth(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), i4, prioritizedLen = prioritized.length;
for (i4 = 0; i4 < prioritizedLen; i4++) {
this[prioritized[i4].unit](units[prioritized[i4].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, p32, p4) {
return p1 || p22 || p32 || p4;
}
)
);
}
function regexEscape(s4) {
return s4.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
}
var tokens = {};
function addParseToken(token2, callback) {
var i4, func = callback, tokenLen;
if (typeof token2 === "string") {
token2 = [token2];
}
if (isNumber(callback)) {
func = function(input, array) {
array[callback] = toInt(input);
};
}
tokenLen = token2.length;
for (i4 = 0; i4 < tokenLen; i4++) {
tokens[token2[i4]] = 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(o4) {
var i4;
for (i4 = 0; i4 < this.length; ++i4) {
if (this[i4] === o4) {
return i4;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1 ? isLeapYear3(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, strict) {
var i4, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i4 = 0; i4 < 12; ++i4) {
mom = createUTC([2e3, i4]);
this._shortMonthsParse[i4] = this.monthsShort(
mom,
""
).toLocaleLowerCase();
this._longMonthsParse[i4] = this.months(mom, "").toLocaleLowerCase();
}
}
if (strict) {
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, strict) {
var i4, mom, regex2;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format2, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
for (i4 = 0; i4 < 12; i4++) {
mom = createUTC([2e3, i4]);
if (strict && !this._longMonthsParse[i4]) {
this._longMonthsParse[i4] = new RegExp(
"^" + this.months(mom, "").replace(".", "") + "$",
"i"
);
this._shortMonthsParse[i4] = new RegExp(
"^" + this.monthsShort(mom, "").replace(".", "") + "$",
"i"
);
}
if (!strict && !this._monthsParse[i4]) {
regex2 = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, "");
this._monthsParse[i4] = new RegExp(regex2.replace(".", ""), "i");
}
if (strict && format2 === "MMMM" && this._longMonthsParse[i4].test(monthName)) {
return i4;
} else if (strict && format2 === "MMM" && this._shortMonthsParse[i4].test(monthName)) {
return i4;
} else if (!strict && this._monthsParse[i4].test(monthName)) {
return i4;
}
}
}
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 (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(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 daysInMonth(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(a4, b3) {
return b3.length - a4.length;
}
var shortPieces = [], longPieces = [], mixedPieces = [], i4, mom;
for (i4 = 0; i4 < 12; i4++) {
mom = createUTC([2e3, i4]);
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 (i4 = 0; i4 < 12; i4++) {
shortPieces[i4] = regexEscape(shortPieces[i4]);
longPieces[i4] = regexEscape(longPieces[i4]);
}
for (i4 = 0; i4 < 24; i4++) {
mixedPieces[i4] = regexEscape(mixedPieces[i4]);
}
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 y3 = this.year();
return y3 <= 9999 ? zeroFill(y3, 4) : "+" + y3;
});
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 daysInYear(year) {
return isLeapYear3(year) ? 366 : 365;
}
hooks.parseTwoDigitYear = function(input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3);
};
var getSetYear = makeGetSet("FullYear", true);
function getIsLeapYear() {
return isLeapYear3(this.year());
}
function createDate(y3, m3, d3, h4, M, s4, ms) {
var date2;
if (y3 < 100 && y3 >= 0) {
date2 = new Date(y3 + 400, m3, d3, h4, M, s4, ms);
if (isFinite(date2.getFullYear())) {
date2.setFullYear(y3);
}
} else {
date2 = new Date(y3, m3, d3, h4, M, s4, ms);
}
return date2;
}
function createUTCDate(y3) {
var date2, args;
if (y3 < 100 && y3 >= 0) {
args = Array.prototype.slice.call(arguments);
args[0] = y3 + 400;
date2 = new Date(Date.UTC.apply(null, args));
if (isFinite(date2.getUTCFullYear())) {
date2.setUTCFullYear(y3);
}
} else {
date2 = new Date(Date.UTC.apply(null, arguments));
}
return date2;
}
function firstWeekOffset(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 = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(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 = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(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 weekdays = isArray2(this._weekdays) ? this._weekdays : this._weekdays[m3 && m3 !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"];
return m3 === true ? shiftWeekdays(weekdays, this._week.dow) : m3 ? weekdays[m3.day()] : weekdays;
}
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, strict) {
var i4, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i4 = 0; i4 < 7; ++i4) {
mom = createUTC([2e3, 1]).day(i4);
this._minWeekdaysParse[i4] = this.weekdaysMin(
mom,
""
).toLocaleLowerCase();
this._shortWeekdaysParse[i4] = this.weekdaysShort(
mom,
""
).toLocaleLowerCase();
this._weekdaysParse[i4] = this.weekdays(mom, "").toLocaleLowerCase();
}
}
if (strict) {
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, strict) {
var i4, mom, regex2;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format2, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i4 = 0; i4 < 7; i4++) {
mom = createUTC([2e3, 1]).day(i4);
if (strict && !this._fullWeekdaysParse[i4]) {
this._fullWeekdaysParse[i4] = new RegExp(
"^" + this.weekdays(mom, "").replace(".", "\\.?") + "$",
"i"
);
this._shortWeekdaysParse[i4] = new RegExp(
"^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$",
"i"
);
this._minWeekdaysParse[i4] = new RegExp(
"^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$",
"i"
);
}
if (!this._weekdaysParse[i4]) {
regex2 = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, "");
this._weekdaysParse[i4] = new RegExp(regex2.replace(".", ""), "i");
}
if (strict && format2 === "dddd" && this._fullWeekdaysParse[i4].test(weekdayName)) {
return i4;
} else if (strict && format2 === "ddd" && this._shortWeekdaysParse[i4].test(weekdayName)) {
return i4;
} else if (strict && format2 === "dd" && this._minWeekdaysParse[i4].test(weekdayName)) {
return i4;
} else if (!strict && this._weekdaysParse[i4].test(weekdayName)) {
return i4;
}
}
}
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(a4, b3) {
return b3.length - a4.length;
}
var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i4, mom, minp, shortp, longp;
for (i4 = 0; i4 < 7; i4++) {
mom = createUTC([2e3, 1]).day(i4);
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 i4, minl = Math.min(arr1.length, arr2.length);
for (i4 = 0; i4 < minl; i4 += 1) {
if (arr1[i4] !== arr2[i4]) {
return i4;
}
}
return minl;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace("_", "-") : key;
}
function chooseLocale(names) {
var i4 = 0, j3, next, locale2, split;
while (i4 < names.length) {
split = normalizeLocale(names[i4]).split("-");
j3 = split.length;
next = normalizeLocale(names[i4 + 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--;
}
i4++;
}
return globalLocale;
}
function isLocaleNameSane(name2) {
return name2.match("^[^/\\\\]*$") != null;
}
function loadLocale(name2) {
var oldLocale = null, aliasedRequire;
if (locales[name2] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name2)) {
try {
oldLocale = globalLocale._abbr;
aliasedRequire = require;
aliasedRequire("./locale/" + name2);
getSetGlobalLocale(oldLocale);
} catch (e4) {
locales[name2] = null;
}
}
return locales[name2];
}
function getSetGlobalLocale(key, values) {
var data;
if (key) {
if (isUndefined(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(name2, config) {
if (config !== null) {
var locale2, parentConfig = baseConfig;
config.abbr = name2;
if (locales[name2] != 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[name2]._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: name2,
config
});
return null;
}
}
}
locales[name2] = new Locale(mergeConfigs2(parentConfig, config));
if (localeFamilies[name2]) {
localeFamilies[name2].forEach(function(x2) {
defineLocale(x2.name, x2.config);
});
}
getSetGlobalLocale(name2);
return locales[name2];
} else {
delete locales[name2];
return null;
}
}
function updateLocale(name2, config) {
if (config != null) {
var locale2, tmpLocale, parentConfig = baseConfig;
if (locales[name2] != null && locales[name2].parentLocale != null) {
locales[name2].set(mergeConfigs2(locales[name2]._config, config));
} else {
tmpLocale = loadLocale(name2);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs2(parentConfig, config);
if (tmpLocale == null) {
config.abbr = name2;
}
locale2 = new Locale(config);
locale2.parentLocale = locales[name2];
locales[name2] = locale2;
}
getSetGlobalLocale(name2);
} else {
if (locales[name2] != null) {
if (locales[name2].parentLocale != null) {
locales[name2] = locales[name2].parentLocale;
if (name2 === getSetGlobalLocale()) {
getSetGlobalLocale(name2);
}
} else if (locales[name2] != null) {
delete locales[name2];
}
}
}
return locales[name2];
}
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, a4 = m3._a;
if (a4 && getParsingFlags(m3).overflow === -2) {
overflow = a4[MONTH] < 0 || a4[MONTH] > 11 ? MONTH : a4[DATE2] < 1 || a4[DATE2] > daysInMonth(a4[YEAR], a4[MONTH]) ? DATE2 : a4[HOUR] < 0 || a4[HOUR] > 24 || a4[HOUR] === 24 && (a4[MINUTE] !== 0 || a4[SECOND] !== 0 || a4[MILLISECOND] !== 0) ? HOUR : a4[MINUTE] < 0 || a4[MINUTE] > 59 ? MINUTE : a4[SECOND] < 0 || a4[SECOND] > 59 ? SECOND : a4[MILLISECOND] < 0 || a4[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, 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{4}))$/, obsOffsets = {
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 i4, l4, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length;
if (match) {
getParsingFlags(config).iso = true;
for (i4 = 0, l4 = isoDatesLen; i4 < l4; i4++) {
if (isoDates[i4][1].exec(match[1])) {
dateFormat = isoDates[i4][0];
allowTime = isoDates[i4][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i4 = 0, l4 = isoTimesLen; i4 < l4; i4++) {
if (isoTimes[i4][1].exec(match[3])) {
timeFormat = (match[2] || " ") + isoTimes[i4][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[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 = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10)
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2e3 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(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 obsOffsets[obsOffset];
} else if (militaryOffset) {
return 0;
} else {
var hm = parseInt(numOffset, 10), m3 = hm % 100, h4 = (hm - m3) / 100;
return h4 * 60 + m3;
}
}
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i)), parsedArray;
if (match) {
parsedArray = extractFromRFC2822Strings(
match[4],
match[3],
match[2],
match[5],
match[6],
match[7]
);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[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(a4, b3, c5) {
if (a4 != null) {
return a4;
}
if (b3 != null) {
return b3;
}
return c5;
}
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 i4, 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 > daysInYear(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 (i4 = 0; i4 < 3 && config._a[i4] == null; ++i4) {
config._a[i4] = input[i4] = currentDate[i4];
}
for (; i4 < 7; i4++) {
config._a[i4] = input[i4] = config._a[i4] == null ? i4 === 2 ? 1 : 0 : config._a[i4];
}
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, i4, parsedInput, tokens2, token2, skipped, stringLength = string.length, totalParsedInputLength = 0, era, tokenLen;
tokens2 = expandFormat(config._f, config._locale).match(formattingTokens) || [];
tokenLen = tokens2.length;
for (i4 = 0; i4 < tokenLen; i4++) {
token2 = tokens2[i4];
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, i4, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config._f.length;
if (configfLen === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i4 = 0; i4 < configfLen; i4++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i4];
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 i4 = normalizeObjectUnits(config._i), dayOrDate = i4.day === void 0 ? i4.date : i4.day;
config._a = map(
[i4.year, i4.month, dayOrDate, i4.hour, i4.minute, i4.second, i4.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 (isDate(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 (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(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 (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC(input, format2, locale2, strict, isUTC) {
var c5 = {};
if (format2 === true || format2 === false) {
strict = format2;
format2 = void 0;
}
if (locale2 === true || locale2 === false) {
strict = locale2;
locale2 = void 0;
}
if (isObject(input) && isObjectEmpty(input) || isArray2(input) && input.length === 0) {
input = void 0;
}
c5._isAMomentObject = true;
c5._useUTC = c5._isUTC = isUTC;
c5._l = locale2;
c5._i = input;
c5._f = format2;
c5._strict = strict;
return createFromConfig(c5);
}
function createLocal(input, format2, locale2, strict) {
return createLocalOrUTC(input, format2, locale2, strict, 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, i4;
if (moments.length === 1 && isArray2(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i4 = 1; i4 < moments.length; ++i4) {
if (!moments[i4].isValid() || moments[i4][fn](res)) {
res = moments[i4];
}
}
return res;
}
function min() {
var args = [].slice.call(arguments, 0);
return pickBy("isBefore", args);
}
function max() {
var args = [].slice.call(arguments, 0);
return pickBy("isAfter", args);
}
var now = 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, i4, 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 (i4 = 0; i4 < orderLen; ++i4) {
if (m3[ordering[i4]]) {
if (unitHasDecimal) {
return false;
}
if (parseFloat(m3[ordering[i4]]) !== toInt(m3[ordering[i4]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = 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 = +months2 + quarters * 3 + years2 * 12;
this._data = {};
this._locale = getLocale2();
this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
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, i4;
for (i4 = 0; i4 < len; i4++) {
if (dontConvert && array1[i4] !== array2[i4] || !dontConvert && toInt(array1[i4]) !== toInt(array2[i4])) {
diffs++;
}
}
return diffs + lengthDiff;
}
function offset(token2, separator) {
addFormatToken(token2, 0, 0, function() {
var offset2 = this.utcOffset(), sign2 = "+";
if (offset2 < 0) {
offset2 = -offset2;
sign2 = "-";
}
return sign2 + zeroFill(~~(offset2 / 60), 2) + separator + zeroFill(~~offset2 % 60, 2);
});
}
offset("Z", ":");
offset("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) || isDate(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 offset2 = 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 (offset2 !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(
this,
createDuration(input - offset2, "m"),
1,
false
);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset2 : 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 (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c5 = {}, other;
copyConfig(c5, this);
c5 = prepareConfig(c5);
if (c5._a) {
other = c5._isUTC ? createUTC(c5._a) : createLocal(c5._a);
this._isDSTShifted = this.isValid() && compareArrays(c5._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, match = null, sign2, ret, diffRes;
if (isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
};
} else if (isNumber(input) || !isNaN(+input)) {
duration = {};
if (key) {
duration[key] = +input;
} else {
duration.milliseconds = +input;
}
} else if (match = aspNetRegex.exec(input)) {
sign2 = match[1] === "-" ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE2]) * sign2,
h: toInt(match[HOUR]) * sign2,
m: toInt(match[MINUTE]) * sign2,
s: toInt(match[SECOND]) * sign2,
ms: toInt(absRound(match[MILLISECOND] * 1e3)) * sign2
// the millisecond decimal point is included in the match
};
} else if (match = isoRegex.exec(input)) {
sign2 = match[1] === "-" ? -1 : 1;
duration = {
y: parseIso(match[2], sign2),
M: parseIso(match[3], sign2),
w: parseIso(match[4], sign2),
d: parseIso(match[5], sign2),
h: parseIso(match[6], sign2),
m: parseIso(match[7], sign2),
s: parseIso(match[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 Duration(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 = Duration.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, name2) {
return function(val2, period) {
var dur, tmp;
if (period !== null && !isNaN(+period)) {
deprecateSimple(
name2,
"moment()." + name2 + "(period, number) is deprecated. Please use moment()." + name2 + "(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), months2 = absRound(duration._months);
if (!mom.isValid()) {
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months2) {
setMonth(mom, get4(mom, "Month") + months2 * 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 || months2);
}
}
var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract");
function isString(input) {
return typeof input === "string" || input instanceof String;
}
function isMomentInput(input) {
return isMoment(input) || isDate(input) || isString(input) || isNumber(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0;
}
function isMomentInputObject(input) {
var objectTest = isObject(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"
], i4, property, propertyLen = properties.length;
for (i4 = 0; i4 < propertyLen; i4 += 1) {
property = properties[i4];
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 !isNumber(item) && isString(input);
}).length === 0;
}
return arrayTest && dataTypeTest;
}
function isCalendarSpec(input) {
var objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = false, properties = [
"sameDay",
"nextDay",
"lastDay",
"nextWeek",
"lastWeek",
"sameElse"
], i4, property;
for (i4 = 0; i4 < properties.length; i4 += 1) {
property = properties[i4];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function getCalendarFormat(myMoment, now2) {
var diff2 = myMoment.diff(now2, "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 now2 = time2 || createLocal(), sod = cloneWithOffset(now2, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now2) : formats[format2]);
return this.format(
output || this.localeData().calendar(format2, this, createLocal(now2))
);
}
function clone() {
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(a4, b3) {
if (a4.date() < b3.date()) {
return -monthDiff(b3, a4);
}
var wholeMonthDiff = (b3.year() - a4.year()) * 12 + (b3.month() - a4.month()), anchor = a4.clone().add(wholeMonthDiff, "months"), anchor2, adjust;
if (b3 - anchor < 0) {
anchor2 = a4.clone().add(wholeMonthDiff - 1, "months");
adjust = (b3 - anchor) / (anchor - anchor2);
} else {
anchor2 = a4.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(y3, m3, d3) {
if (y3 < 100 && y3 >= 0) {
return new Date(y3 + 400, m3, d3) - MS_PER_400_YEARS;
} else {
return new Date(y3, m3, d3).valueOf();
}
}
function utcStartOfDate(y3, m3, d3) {
if (y3 < 100 && y3 >= 0) {
return Date.UTC(y3 + 400, m3, d3) - MS_PER_400_YEARS;
} else {
return Date.UTC(y3, 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 match;
if (config._locale._eraYearOrdinalRegex) {
match = input.match(config._locale._eraYearOrdinalRegex);
}
if (config._locale.eraYearOrdinalParse) {
array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
} else {
array[YEAR] = parseInt(input, 10);
}
});
function localeEras(m3, format2) {
var i4, l4, date2, eras = this._eras || getLocale2("en")._eras;
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
switch (typeof eras[i4].since) {
case "string":
date2 = hooks(eras[i4].since).startOf("day");
eras[i4].since = date2.valueOf();
break;
}
switch (typeof eras[i4].until) {
case "undefined":
eras[i4].until = Infinity;
break;
case "string":
date2 = hooks(eras[i4].until).startOf("day").valueOf();
eras[i4].until = date2.valueOf();
break;
}
}
return eras;
}
function localeErasParse(eraName, format2, strict) {
var i4, l4, eras = this.eras(), name2, abbr, narrow;
eraName = eraName.toUpperCase();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
name2 = eras[i4].name.toUpperCase();
abbr = eras[i4].abbr.toUpperCase();
narrow = eras[i4].narrow.toUpperCase();
if (strict) {
switch (format2) {
case "N":
case "NN":
case "NNN":
if (abbr === eraName) {
return eras[i4];
}
break;
case "NNNN":
if (name2 === eraName) {
return eras[i4];
}
break;
case "NNNNN":
if (narrow === eraName) {
return eras[i4];
}
break;
}
} else if ([name2, abbr, narrow].indexOf(eraName) >= 0) {
return eras[i4];
}
}
}
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 i4, l4, val2, eras = this.localeData().eras();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
val2 = this.clone().startOf("day").valueOf();
if (eras[i4].since <= val2 && val2 <= eras[i4].until) {
return eras[i4].name;
}
if (eras[i4].until <= val2 && val2 <= eras[i4].since) {
return eras[i4].name;
}
}
return "";
}
function getEraNarrow() {
var i4, l4, val2, eras = this.localeData().eras();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
val2 = this.clone().startOf("day").valueOf();
if (eras[i4].since <= val2 && val2 <= eras[i4].until) {
return eras[i4].narrow;
}
if (eras[i4].until <= val2 && val2 <= eras[i4].since) {
return eras[i4].narrow;
}
}
return "";
}
function getEraAbbr() {
var i4, l4, val2, eras = this.localeData().eras();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
val2 = this.clone().startOf("day").valueOf();
if (eras[i4].since <= val2 && val2 <= eras[i4].until) {
return eras[i4].abbr;
}
if (eras[i4].until <= val2 && val2 <= eras[i4].since) {
return eras[i4].abbr;
}
}
return "";
}
function getEraYear() {
var i4, l4, dir, val2, eras = this.localeData().eras();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
dir = eras[i4].since <= eras[i4].until ? 1 : -1;
val2 = this.clone().startOf("day").valueOf();
if (eras[i4].since <= val2 && val2 <= eras[i4].until || eras[i4].until <= val2 && val2 <= eras[i4].since) {
return (this.year() - hooks(eras[i4].since).year()) * dir + eras[i4].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 = [], i4, l4, eras = this.eras();
for (i4 = 0, l4 = eras.length; i4 < l4; ++i4) {
namePieces.push(regexEscape(eras[i4].name));
abbrPieces.push(regexEscape(eras[i4].abbr));
narrowPieces.push(regexEscape(eras[i4].narrow));
mixedPieces.push(regexEscape(eras[i4].name));
mixedPieces.push(regexEscape(eras[i4].abbr));
mixedPieces.push(regexEscape(eras[i4].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 = clone;
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 = Locale.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, index, field, setter) {
var locale2 = getLocale2(), utc = createUTC().set(setter, index);
return locale2[field](utc, format2);
}
function listMonthsImpl(format2, index, field) {
if (isNumber(format2)) {
index = format2;
format2 = void 0;
}
format2 = format2 || "";
if (index != null) {
return get$1(format2, index, field, "month");
}
var i4, out = [];
for (i4 = 0; i4 < 12; i4++) {
out[i4] = get$1(format2, i4, field, "month");
}
return out;
}
function listWeekdaysImpl(localeSorted, format2, index, field) {
if (typeof localeSorted === "boolean") {
if (isNumber(format2)) {
index = format2;
format2 = void 0;
}
format2 = format2 || "";
} else {
format2 = localeSorted;
index = format2;
localeSorted = false;
if (isNumber(format2)) {
index = format2;
format2 = void 0;
}
format2 = format2 || "";
}
var locale2 = getLocale2(), shift = localeSorted ? locale2._week.dow : 0, i4, out = [];
if (index != null) {
return get$1(format2, (index + shift) % 7, field, "day");
}
for (i4 = 0; i4 < 7; i4++) {
out[i4] = get$1(format2, (i4 + shift) % 7, field, "day");
}
return out;
}
function listMonths(format2, index) {
return listMonthsImpl(format2, index, "months");
}
function listMonthsShort(format2, index) {
return listMonthsImpl(format2, index, "monthsShort");
}
function listWeekdays(localeSorted, format2, index) {
return listWeekdaysImpl(localeSorted, format2, index, "weekdays");
}
function listWeekdaysShort(localeSorted, format2, index) {
return listWeekdaysImpl(localeSorted, format2, index, "weekdaysShort");
}
function listWeekdaysMin(localeSorted, format2, index) {
return listWeekdaysImpl(localeSorted, format2, index, "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, months2 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays;
if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) {
milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5;
days2 = 0;
months2 = 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));
months2 += monthsFromDays;
days2 -= absCeil(monthsToDays(monthsFromDays));
years2 = absFloor(months2 / 12);
months2 %= 12;
data.days = days2;
data.months = months2;
data.years = years2;
return this;
}
function daysToMonths(days2) {
return days2 * 4800 / 146097;
}
function monthsToDays(months2) {
return months2 * 146097 / 4800;
}
function as(units) {
if (!this.isValid()) {
return NaN;
}
var days2, months2, milliseconds2 = this._milliseconds;
units = normalizeUnits(units);
if (units === "month" || units === "quarter" || units === "year") {
days2 = this._days + milliseconds2 / 864e5;
months2 = this._months + daysToMonths(days2);
switch (units) {
case "month":
return months2;
case "quarter":
return months2 / 3;
case "year":
return months2 / 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(name2) {
return function() {
return this.isValid() ? this._data[name2] : NaN;
};
}
var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years");
function weeks() {
return absFloor(this.days() / 7);
}
var round = 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 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a4 = 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) {
a4 = a4 || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2];
}
a4 = a4 || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2];
a4[2] = withoutSuffix;
a4[3] = +posNegDuration > 0;
a4[4] = locale2;
return substituteTimeAgo.apply(null, a4);
}
function getSetRelativeTimeRounding(roundingFunction) {
if (roundingFunction === void 0) {
return round;
}
if (typeof roundingFunction === "function") {
round = 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), months2 = 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(months2 / 12);
months2 %= 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" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s4 + "S" : "");
}
var proto$2 = Duration.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 = months;
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 = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
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/@langchain/core/outputs.js
var init_outputs2 = __esm({
"node_modules/@langchain/core/outputs.js"() {
init_outputs();
}
});
// 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, index = 0, i4, length = message.length || 0, blocks2 = this.blocks;
while (index < 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 (i4 = this.start; index < length && i4 < 64; ++index) {
blocks2[i4 >> 2] |= message[index] << SHIFT[i4++ & 3];
}
} else {
for (i4 = this.start; index < length && i4 < 64; ++index) {
code = message.charCodeAt(index);
if (code < 128) {
blocks2[i4 >> 2] |= code << SHIFT[i4++ & 3];
} else if (code < 2048) {
blocks2[i4 >> 2] |= (192 | code >> 6) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code & 63) << SHIFT[i4++ & 3];
} else if (code < 55296 || code >= 57344) {
blocks2[i4 >> 2] |= (224 | code >> 12) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code & 63) << SHIFT[i4++ & 3];
} else {
code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023);
blocks2[i4 >> 2] |= (240 | code >> 18) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i4++ & 3];
blocks2[i4 >> 2] |= (128 | code & 63) << SHIFT[i4++ & 3];
}
}
}
this.lastByteIndex = i4;
this.bytes += i4 - this.start;
if (i4 >= 64) {
this.block = blocks2[16];
this.start = i4 - 64;
this.hash();
this.hashed = true;
} else {
this.start = i4;
}
}
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, i4 = this.lastByteIndex;
blocks2[16] = this.block;
blocks2[i4 >> 2] |= EXTRA[i4 & 3];
this.block = blocks2[16];
if (i4 >= 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 a4 = this.h0, b3 = this.h1, c5 = this.h2, d3 = this.h3, e4 = this.h4;
var f4, j3, t4, blocks2 = this.blocks;
for (j3 = 16; j3 < 80; ++j3) {
t4 = blocks2[j3 - 3] ^ blocks2[j3 - 8] ^ blocks2[j3 - 14] ^ blocks2[j3 - 16];
blocks2[j3] = t4 << 1 | t4 >>> 31;
}
for (j3 = 0; j3 < 20; j3 += 5) {
f4 = b3 & c5 | ~b3 & d3;
t4 = a4 << 5 | a4 >>> 27;
e4 = t4 + f4 + e4 + 1518500249 + blocks2[j3] << 0;
b3 = b3 << 30 | b3 >>> 2;
f4 = a4 & b3 | ~a4 & c5;
t4 = e4 << 5 | e4 >>> 27;
d3 = t4 + f4 + d3 + 1518500249 + blocks2[j3 + 1] << 0;
a4 = a4 << 30 | a4 >>> 2;
f4 = e4 & a4 | ~e4 & b3;
t4 = d3 << 5 | d3 >>> 27;
c5 = t4 + f4 + c5 + 1518500249 + blocks2[j3 + 2] << 0;
e4 = e4 << 30 | e4 >>> 2;
f4 = d3 & e4 | ~d3 & a4;
t4 = c5 << 5 | c5 >>> 27;
b3 = t4 + f4 + b3 + 1518500249 + blocks2[j3 + 3] << 0;
d3 = d3 << 30 | d3 >>> 2;
f4 = c5 & d3 | ~c5 & e4;
t4 = b3 << 5 | b3 >>> 27;
a4 = t4 + f4 + a4 + 1518500249 + blocks2[j3 + 4] << 0;
c5 = c5 << 30 | c5 >>> 2;
}
for (; j3 < 40; j3 += 5) {
f4 = b3 ^ c5 ^ d3;
t4 = a4 << 5 | a4 >>> 27;
e4 = t4 + f4 + e4 + 1859775393 + blocks2[j3] << 0;
b3 = b3 << 30 | b3 >>> 2;
f4 = a4 ^ b3 ^ c5;
t4 = e4 << 5 | e4 >>> 27;
d3 = t4 + f4 + d3 + 1859775393 + blocks2[j3 + 1] << 0;
a4 = a4 << 30 | a4 >>> 2;
f4 = e4 ^ a4 ^ b3;
t4 = d3 << 5 | d3 >>> 27;
c5 = t4 + f4 + c5 + 1859775393 + blocks2[j3 + 2] << 0;
e4 = e4 << 30 | e4 >>> 2;
f4 = d3 ^ e4 ^ a4;
t4 = c5 << 5 | c5 >>> 27;
b3 = t4 + f4 + b3 + 1859775393 + blocks2[j3 + 3] << 0;
d3 = d3 << 30 | d3 >>> 2;
f4 = c5 ^ d3 ^ e4;
t4 = b3 << 5 | b3 >>> 27;
a4 = t4 + f4 + a4 + 1859775393 + blocks2[j3 + 4] << 0;
c5 = c5 << 30 | c5 >>> 2;
}
for (; j3 < 60; j3 += 5) {
f4 = b3 & c5 | b3 & d3 | c5 & d3;
t4 = a4 << 5 | a4 >>> 27;
e4 = t4 + f4 + e4 - 1894007588 + blocks2[j3] << 0;
b3 = b3 << 30 | b3 >>> 2;
f4 = a4 & b3 | a4 & c5 | b3 & c5;
t4 = e4 << 5 | e4 >>> 27;
d3 = t4 + f4 + d3 - 1894007588 + blocks2[j3 + 1] << 0;
a4 = a4 << 30 | a4 >>> 2;
f4 = e4 & a4 | e4 & b3 | a4 & b3;
t4 = d3 << 5 | d3 >>> 27;
c5 = t4 + f4 + c5 - 1894007588 + blocks2[j3 + 2] << 0;
e4 = e4 << 30 | e4 >>> 2;
f4 = d3 & e4 | d3 & a4 | e4 & a4;
t4 = c5 << 5 | c5 >>> 27;
b3 = t4 + f4 + b3 - 1894007588 + blocks2[j3 + 3] << 0;
d3 = d3 << 30 | d3 >>> 2;
f4 = c5 & d3 | c5 & e4 | d3 & e4;
t4 = b3 << 5 | b3 >>> 27;
a4 = t4 + f4 + a4 - 1894007588 + blocks2[j3 + 4] << 0;
c5 = c5 << 30 | c5 >>> 2;
}
for (; j3 < 80; j3 += 5) {
f4 = b3 ^ c5 ^ d3;
t4 = a4 << 5 | a4 >>> 27;
e4 = t4 + f4 + e4 - 899497514 + blocks2[j3] << 0;
b3 = b3 << 30 | b3 >>> 2;
f4 = a4 ^ b3 ^ c5;
t4 = e4 << 5 | e4 >>> 27;
d3 = t4 + f4 + d3 - 899497514 + blocks2[j3 + 1] << 0;
a4 = a4 << 30 | a4 >>> 2;
f4 = e4 ^ a4 ^ b3;
t4 = d3 << 5 | d3 >>> 27;
c5 = t4 + f4 + c5 - 899497514 + blocks2[j3 + 2] << 0;
e4 = e4 << 30 | e4 >>> 2;
f4 = d3 ^ e4 ^ a4;
t4 = c5 << 5 | c5 >>> 27;
b3 = t4 + f4 + b3 - 899497514 + blocks2[j3 + 3] << 0;
d3 = d3 << 30 | d3 >>> 2;
f4 = c5 ^ d3 ^ e4;
t4 = b3 << 5 | b3 >>> 27;
a4 = t4 + f4 + a4 - 899497514 + blocks2[j3 + 4] << 0;
c5 = c5 << 30 | c5 >>> 2;
}
this.h0 = this.h0 + a4 << 0;
this.h1 = this.h1 + b3 << 0;
this.h2 = this.h2 + c5 << 0;
this.h3 = this.h3 + d3 << 0;
this.h4 = this.h4 + e4 << 0;
};
Sha1.prototype.hex = function() {
this.finalize();
var h0 = this.h0, h1 = this.h1, h22 = this.h2, h32 = 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[h32 >> 28 & 15] + HEX_CHARS[h32 >> 24 & 15] + HEX_CHARS[h32 >> 20 & 15] + HEX_CHARS[h32 >> 16 & 15] + HEX_CHARS[h32 >> 12 & 15] + HEX_CHARS[h32 >> 8 & 15] + HEX_CHARS[h32 >> 4 & 15] + HEX_CHARS[h32 & 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, h32 = 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,
h32 >> 24 & 255,
h32 >> 16 & 255,
h32 >> 8 & 255,
h32 & 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/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 (i4 = 0, len = code.length; i4 < len; ++i4) {
lookup2[i4] = code[i4];
revLookup[code.charCodeAt(i4)] = i4;
}
var i4;
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 i5;
for (i5 = 0; i5 < len2; i5 += 4) {
tmp = revLookup[b64.charCodeAt(i5)] << 18 | revLookup[b64.charCodeAt(i5 + 1)] << 12 | revLookup[b64.charCodeAt(i5 + 2)] << 6 | revLookup[b64.charCodeAt(i5 + 3)];
arr2[curByte++] = tmp >> 16 & 255;
arr2[curByte++] = tmp >> 8 & 255;
arr2[curByte++] = tmp & 255;
}
if (placeHoldersLen === 2) {
tmp = revLookup[b64.charCodeAt(i5)] << 2 | revLookup[b64.charCodeAt(i5 + 1)] >> 4;
arr2[curByte++] = tmp & 255;
}
if (placeHoldersLen === 1) {
tmp = revLookup[b64.charCodeAt(i5)] << 10 | revLookup[b64.charCodeAt(i5 + 1)] << 4 | revLookup[b64.charCodeAt(i5 + 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 i5 = start; i5 < end; i5 += 3) {
tmp = (uint8[i5] << 16 & 16711680) + (uint8[i5 + 1] << 8 & 65280) + (uint8[i5 + 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 i5 = 0, len22 = len2 - extraBytes; i5 < len22; i5 += maxChunkLength) {
parts.push(encodeChunk(uint8, i5, i5 + maxChunkLength > len22 ? len22 : i5 + 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/js-tiktoken/dist/chunk-XX6PTLQF.js
function bytePairMerge(piece, ranks) {
let parts = Array.from(
{ length: piece.length },
(_2, i4) => ({ start: i4, end: i4 + 1 })
);
while (parts.length > 1) {
let minRank = null;
for (let i4 = 0; i4 < parts.length - 1; i4++) {
const slice = piece.slice(parts[i4].start, parts[i4 + 1].end);
const rank = ranks.get(slice.join(","));
if (rank == null)
continue;
if (minRank == null || rank < minRank[0]) {
minRank = [rank, i4];
}
}
if (minRank != null) {
const i4 = minRank[1];
parts[i4] = { start: parts[i4].start, end: parts[i4 + 1].end };
parts.splice(i4 + 1, 1);
} else {
break;
}
}
return parts;
}
function bytePairEncode(piece, ranks) {
if (piece.length === 1)
return [ranks.get(piece.join(","))];
return bytePairMerge(piece, ranks).map((p4) => ranks.get(piece.slice(p4.start, p4.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((memo, x2) => {
const [_2, offsetStr, ...tokens] = x2.split(" ");
const offset = Number.parseInt(offsetStr, 10);
tokens.forEach((token, i4) => memo[token] = offset + i4);
return memo;
}, {});
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((memo, [text, rank]) => {
memo[rank] = this.textEncoder.encode(text);
return memo;
}, {});
}
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 match of text.substring(start, end).matchAll(regexes)) {
const piece = this.textEncoder.encode(match[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 i4 = 0;
for (const bytes of res) {
mergedArray.set(bytes, i4);
i4 += bytes.length;
}
return this.textDecoder.decode(mergedArray);
}
};
Tiktoken = _Tiktoken;
__publicField2(Tiktoken, "specialTokenRegex", (tokens) => {
return new RegExp(tokens.map((i4) => escapeRegex(i4)).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((e4) => {
delete cache[encoding];
throw e4;
});
}
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(tool) {
if (typeof tool !== "object" || !tool)
return false;
if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.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 }) {
super({
callbacks: callbacks ?? callbackManager,
...params
});
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 params.cache === "object") {
this.cache = params.cache;
} else if (params.cache) {
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/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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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_client = __commonJS({
"node_modules/cohere-ai/api/resources/v2/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types(), exports);
__exportStar5(require_client(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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_client2 = __commonJS({
"node_modules/cohere-ai/api/resources/embedJobs/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types2(), exports);
__exportStar5(require_client2(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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_client3 = __commonJS({
"node_modules/cohere-ai/api/resources/datasets/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types3(), exports);
__exportStar5(require_client3(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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_client4 = __commonJS({
"node_modules/cohere-ai/api/resources/finetuning/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_resources(), exports);
__exportStar5(require_client4(), 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_client5 = __commonJS({
"node_modules/cohere-ai/api/resources/connectors/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_client5(), 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_client6 = __commonJS({
"node_modules/cohere-ai/api/resources/models/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_client6(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 BadRequestError7 = class extends errors2.CohereError {
constructor(body) {
super({
message: "BadRequestError",
statusCode: 400,
body
});
Object.setPrototypeOf(this, BadRequestError7.prototype);
}
};
exports.BadRequestError = BadRequestError7;
}
});
// 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 NotFoundError7 = class extends errors2.CohereError {
constructor(body) {
super({
message: "NotFoundError",
statusCode: 404,
body
});
Object.setPrototypeOf(this, NotFoundError7.prototype);
}
};
exports.NotFoundError = NotFoundError7;
}
});
// 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 UnprocessableEntityError7 = class extends errors2.CohereError {
constructor(body) {
super({
message: "UnprocessableEntityError",
statusCode: 422,
body
});
Object.setPrototypeOf(this, UnprocessableEntityError7.prototype);
}
};
exports.UnprocessableEntityError = UnprocessableEntityError7;
}
});
// 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 InternalServerError7 = class extends errors2.CohereError {
constructor(body) {
super({
message: "InternalServerError",
statusCode: 500,
body
});
Object.setPrototypeOf(this, InternalServerError7.prototype);
}
};
exports.InternalServerError = InternalServerError7;
}
});
// 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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_client7 = __commonJS({
"node_modules/cohere-ai/api/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_resources2(), exports);
__exportStar5(require_types5(), exports);
__exportStar5(require_errors2(), exports);
__exportStar5(require_client7(), 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: () => __classPrivateFieldGet10,
__classPrivateFieldIn: () => __classPrivateFieldIn,
__classPrivateFieldSet: () => __classPrivateFieldSet9,
__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, e4) {
var t4 = {};
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
t4[p4] = s4[p4];
if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) {
if (e4.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4]))
t4[p4[i4]] = s4[p4[i4]];
}
return t4;
}
function __decorate(decorators, target, key, desc) {
var c5 = arguments.length, r4 = c5 < 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 i4 = decorators.length - 1; i4 >= 0; i4--)
if (d3 = decorators[i4])
r4 = (c5 < 3 ? d3(r4) : c5 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
return c5 > 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(f4) {
if (f4 !== void 0 && typeof f4 !== "function")
throw new TypeError("Function expected");
return f4;
}
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 i4 = decorators.length - 1; i4 >= 0; i4--) {
var context = {};
for (var p4 in contextIn)
context[p4] = p4 === "access" ? {} : contextIn[p4];
for (var p4 in contextIn.access)
context.access[p4] = contextIn.access[p4];
context.addInitializer = function(f4) {
if (done)
throw new TypeError("Cannot add initializers after decoration has completed");
extraInitializers.push(accept(f4 || null));
};
var result = (0, decorators[i4])(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 i4 = 0; i4 < initializers.length; i4++) {
value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg);
}
return useValue ? value : void 0;
}
function __propKey(x2) {
return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName(f4, name2, prefix) {
if (typeof name2 === "symbol")
name2 = name2.description ? "[".concat(name2.description, "]") : "";
return Object.defineProperty(f4, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name2) : name2 });
}
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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 (t4[0] & 1)
throw t4[1];
return t4[1];
}, trys: [], ops: [] }, f4, y3, t4, 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(v6) {
return step([n4, v6]);
};
}
function step(op) {
if (f4)
throw new TypeError("Generator is already executing.");
while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
try {
if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
return t4;
if (y3 = 0, t4)
op = [op[0] & 2, t4.value];
switch (op[0]) {
case 0:
case 1:
t4 = op;
break;
case 4:
_2.label++;
return { value: op[1], done: false };
case 5:
_2.label++;
y3 = op[1];
op = [0];
continue;
case 7:
op = _2.ops.pop();
_2.trys.pop();
continue;
default:
if (!(t4 = _2.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_2 = 0;
continue;
}
if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
_2.label = op[1];
break;
}
if (op[0] === 6 && _2.label < t4[1]) {
_2.label = t4[1];
t4 = op;
break;
}
if (t4 && _2.label < t4[2]) {
_2.label = t4[2];
_2.ops.push(op);
break;
}
if (t4[2])
_2.ops.pop();
_2.trys.pop();
continue;
}
op = body.call(thisArg, _2);
} catch (e4) {
op = [6, e4];
y3 = 0;
} finally {
f4 = t4 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m3, o4) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(o4, p4))
__createBinding(o4, m3, p4);
}
function __values2(o4) {
var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o4[s4], i4 = 0;
if (m3)
return m3.call(o4);
if (o4 && typeof o4.length === "number")
return {
next: function() {
if (o4 && i4 >= o4.length)
o4 = void 0;
return { value: o4 && o4[i4++], done: !o4 };
}
};
throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o4, n4) {
var m3 = typeof Symbol === "function" && o4[Symbol.iterator];
if (!m3)
return o4;
var i4 = m3.call(o4), r4, ar = [], e4;
try {
while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done)
ar.push(r4.value);
} catch (error) {
e4 = { error };
} finally {
try {
if (r4 && !r4.done && (m3 = i4["return"]))
m3.call(i4);
} finally {
if (e4)
throw e4.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
ar = ar.concat(__read(arguments[i4]));
return ar;
}
function __spreadArrays() {
for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++)
s4 += arguments[i4].length;
for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
for (var a4 = arguments[i4], j3 = 0, jl = a4.length; j3 < jl; j3++, k3++)
r4[k3] = a4[j3];
return r4;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2)
for (var i4 = 0, l4 = from.length, ar; i4 < l4; i4++) {
if (ar || !(i4 in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i4);
ar[i4] = from[i4];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v6) {
return this instanceof __await ? (this.v = v6, this) : new __await(v6);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function awaitReturn(f4) {
return function(v6) {
return Promise.resolve(v6).then(f4, reject);
};
}
function verb(n4, f4) {
if (g4[n4]) {
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
if (f4)
i4[n4] = f4(i4[n4]);
}
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), q3.shift(), q3.length)
resume(q3[0][0], q3[0][1]);
}
}
function __asyncDelegator(o4) {
var i4, p4;
return i4 = {}, verb("next"), verb("throw", function(e4) {
throw e4;
}), verb("return"), i4[Symbol.iterator] = function() {
return this;
}, i4;
function verb(n4, f4) {
i4[n4] = o4[n4] ? function(v6) {
return (p4 = !p4) ? { value: __await(o4[n4](v6)), done: false } : f4 ? f4(v6) : v6;
} : f4;
}
}
function __asyncValues(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values2 === "function" ? __values2(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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 __classPrivateFieldGet10(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}
function __classPrivateFieldSet9(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.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 (e4) {
return Promise.reject(e4);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
}
function __disposeResources(env) {
function fail(e4) {
env.error = env.hasError ? new _SuppressedError(e4, env.error, "An error was suppressed during disposal.") : e4;
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(e4) {
fail(e4);
return next();
});
} else
s4 |= 1;
} catch (e4) {
fail(e4);
}
}
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 p4 in b4)
if (Object.prototype.hasOwnProperty.call(b4, p4))
d4[p4] = b4[p4];
};
return extendStatics(d3, b3);
};
__assign = function() {
__assign = Object.assign || function __assign5(t4) {
for (var s4, i4 = 1, n4 = arguments.length; i4 < n4; i4++) {
s4 = arguments[i4];
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4))
t4[p4] = s4[p4];
}
return t4;
};
return __assign.apply(this, arguments);
};
__createBinding = Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
};
__setModuleDefault = Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
};
_SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e4 = new Error(message);
return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
};
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: __classPrivateFieldGet10,
__classPrivateFieldSet: __classPrivateFieldSet9,
__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 i4 = this.bufferLength; i4 < constants_1.BLOCK_SIZE; i4++) {
bufferView.setUint8(i4, 0);
}
this.hashBuffer();
this.bufferLength = 0;
}
for (var i4 = this.bufferLength; i4 < constants_1.BLOCK_SIZE - 8; i4++) {
bufferView.setUint8(i4, 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 i4 = 0; i4 < 8; i4++) {
out[i4 * 4] = this.state[i4] >>> 24 & 255;
out[i4 * 4 + 1] = this.state[i4] >>> 16 & 255;
out[i4 * 4 + 2] = this.state[i4] >>> 8 & 255;
out[i4 * 4 + 3] = this.state[i4] >>> 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 i4 = 0; i4 < constants_1.BLOCK_SIZE; i4++) {
if (i4 < 16) {
this.temp[i4] = (buffer[i4 * 4] & 255) << 24 | (buffer[i4 * 4 + 1] & 255) << 16 | (buffer[i4 * 4 + 2] & 255) << 8 | buffer[i4 * 4 + 3] & 255;
} else {
var u4 = this.temp[i4 - 2];
var t1_1 = (u4 >>> 17 | u4 << 15) ^ (u4 >>> 19 | u4 << 13) ^ u4 >>> 10;
u4 = this.temp[i4 - 15];
var t2_1 = (u4 >>> 7 | u4 << 25) ^ (u4 >>> 18 | u4 << 14) ^ u4 >>> 3;
this.temp[i4] = (t1_1 + this.temp[i4 - 7] | 0) + (t2_1 + this.temp[i4 - 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[i4] + this.temp[i4] | 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 __defProp5 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp5(target, "name", { value, configurable: true });
var __export2 = (target, all) => {
for (var name2 in all)
__defProp5(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps2 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp3.call(to, key) && key !== except)
__defProp5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps2(__defProp5({}, "__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/ieee754/index.js
var require_ieee754 = __commonJS({
"node_modules/ieee754/index.js"(exports) {
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e4, m3;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i4 = isLE ? nBytes - 1 : 0;
var d3 = isLE ? -1 : 1;
var s4 = buffer[offset + i4];
i4 += d3;
e4 = s4 & (1 << -nBits) - 1;
s4 >>= -nBits;
nBits += eLen;
for (; nBits > 0; e4 = e4 * 256 + buffer[offset + i4], i4 += d3, nBits -= 8) {
}
m3 = e4 & (1 << -nBits) - 1;
e4 >>= -nBits;
nBits += mLen;
for (; nBits > 0; m3 = m3 * 256 + buffer[offset + i4], i4 += d3, nBits -= 8) {
}
if (e4 === 0) {
e4 = 1 - eBias;
} else if (e4 === eMax) {
return m3 ? NaN : (s4 ? -1 : 1) * Infinity;
} else {
m3 = m3 + Math.pow(2, mLen);
e4 = e4 - eBias;
}
return (s4 ? -1 : 1) * m3 * Math.pow(2, e4 - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e4, m3, c5;
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 i4 = 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;
e4 = eMax;
} else {
e4 = Math.floor(Math.log(value) / Math.LN2);
if (value * (c5 = Math.pow(2, -e4)) < 1) {
e4--;
c5 *= 2;
}
if (e4 + eBias >= 1) {
value += rt / c5;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c5 >= 2) {
e4++;
c5 /= 2;
}
if (e4 + eBias >= eMax) {
m3 = 0;
e4 = eMax;
} else if (e4 + eBias >= 1) {
m3 = (value * c5 - 1) * Math.pow(2, mLen);
e4 = e4 + eBias;
} else {
m3 = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e4 = 0;
}
}
for (; mLen >= 8; buffer[offset + i4] = m3 & 255, i4 += d3, m3 /= 256, mLen -= 8) {
}
e4 = e4 << mLen | m3;
eLen += mLen;
for (; eLen > 0; buffer[offset + i4] = e4 & 255, i4 += d3, e4 /= 256, eLen -= 8) {
}
buffer[offset + i4 - 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 (e4) {
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(size) {
if (typeof size !== "number") {
throw new TypeError('"size" argument must be of type number');
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"');
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== void 0) {
return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}
return createBuffer(size);
}
Buffer2.alloc = function(size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
Buffer2.allocUnsafe = function(size) {
return allocUnsafe(size);
};
Buffer2.allocUnsafeSlow = function(size) {
return allocUnsafe(size);
};
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 i4 = 0; i4 < length; i4 += 1) {
buf[i4] = array[i4] & 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(a4, b3) {
if (isInstance(a4, Uint8Array))
a4 = Buffer2.from(a4, a4.offset, a4.byteLength);
if (isInstance(b3, Uint8Array))
b3 = Buffer2.from(b3, b3.offset, b3.byteLength);
if (!Buffer2.isBuffer(a4) || !Buffer2.isBuffer(b3)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
);
}
if (a4 === b3)
return 0;
let x2 = a4.length;
let y3 = b3.length;
for (let i4 = 0, len = Math.min(x2, y3); i4 < len; ++i4) {
if (a4[i4] !== b3[i4]) {
x2 = a4[i4];
y3 = b3[i4];
break;
}
}
if (x2 < y3)
return -1;
if (y3 < 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 i4;
if (length === void 0) {
length = 0;
for (i4 = 0; i4 < list.length; ++i4) {
length += list[i4].length;
}
}
const buffer = Buffer2.allocUnsafe(length);
let pos = 0;
for (i4 = 0; i4 < list.length; ++i4) {
let buf = list[i4];
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 i4 = b3[n4];
b3[n4] = b3[m3];
b3[m3] = i4;
}
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 i4 = 0; i4 < len; i4 += 2) {
swap(this, i4, i4 + 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 i4 = 0; i4 < len; i4 += 4) {
swap(this, i4, i4 + 3);
swap(this, i4 + 1, i4 + 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 i4 = 0; i4 < len; i4 += 8) {
swap(this, i4, i4 + 7);
swap(this, i4 + 1, i4 + 6);
swap(this, i4 + 2, i4 + 5);
swap(this, i4 + 3, i4 + 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 max = exports.INSPECT_MAX_BYTES;
str2 = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
if (this.length > max)
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 y3 = end - start;
const len = Math.min(x2, y3);
const thisCopy = this.slice(thisStart, thisEnd);
const targetCopy = target.slice(start, end);
for (let i4 = 0; i4 < len; ++i4) {
if (thisCopy[i4] !== targetCopy[i4]) {
x2 = thisCopy[i4];
y3 = targetCopy[i4];
break;
}
}
if (x2 < y3)
return -1;
if (y3 < 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, i5) {
if (indexSize === 1) {
return buf[i5];
} else {
return buf.readUInt16BE(i5 * indexSize);
}
}
let i4;
if (dir) {
let foundIndex = -1;
for (i4 = byteOffset; i4 < arrLength; i4++) {
if (read(arr2, i4) === read(val2, foundIndex === -1 ? 0 : i4 - foundIndex)) {
if (foundIndex === -1)
foundIndex = i4;
if (i4 - foundIndex + 1 === valLength)
return foundIndex * indexSize;
} else {
if (foundIndex !== -1)
i4 -= i4 - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength)
byteOffset = arrLength - valLength;
for (i4 = byteOffset; i4 >= 0; i4--) {
let found = true;
for (let j3 = 0; j3 < valLength; j3++) {
if (read(arr2, i4 + j3) !== read(val2, j3)) {
found = false;
break;
}
}
if (found)
return i4;
}
}
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, offset, length) {
offset = Number(offset) || 0;
const remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
const strLen = string.length;
if (length > strLen / 2) {
length = strLen / 2;
}
let i4;
for (i4 = 0; i4 < length; ++i4) {
const parsed = parseInt(string.substr(i4 * 2, 2), 16);
if (numberIsNaN(parsed))
return i4;
buf[offset + i4] = parsed;
}
return i4;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer2.prototype.write = function write(string, offset, length, encoding) {
if (offset === void 0) {
encoding = "utf8";
length = this.length;
offset = 0;
} else if (length === void 0 && typeof offset === "string") {
encoding = offset;
length = this.length;
offset = 0;
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === void 0)
encoding = "utf8";
} else {
encoding = length;
length = void 0;
}
} else {
throw new Error(
"Buffer.write(string, encoding, offset[, length]) is no longer supported"
);
}
const remaining = this.length - offset;
if (length === void 0 || length > remaining)
length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
throw new RangeError("Attempt to write outside buffer bounds");
}
if (!encoding)
encoding = "utf8";
let loweredCase = false;
for (; ; ) {
switch (encoding) {
case "hex":
return hexWrite(this, string, offset, length);
case "utf8":
case "utf-8":
return utf8Write(this, string, offset, length);
case "ascii":
case "latin1":
case "binary":
return asciiWrite(this, string, offset, length);
case "base64":
return base64Write(this, string, offset, length);
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return ucs2Write(this, string, offset, length);
default:
if (loweredCase)
throw new TypeError("Unknown encoding: " + encoding);
encoding = ("" + encoding).toLowerCase();
loweredCase = true;
}
}
};
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 i4 = start;
while (i4 < end) {
const firstByte = buf[i4];
let codePoint = null;
let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
if (i4 + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 128) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i4 + 1];
if ((secondByte & 192) === 128) {
tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
if (tempCodePoint > 127) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i4 + 1];
thirdByte = buf[i4 + 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[i4 + 1];
thirdByte = buf[i4 + 2];
fourthByte = buf[i4 + 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);
i4 += 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 i4 = 0;
while (i4 < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i4, i4 += MAX_ARGUMENTS_LENGTH)
);
}
return res;
}
function asciiSlice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i4 = start; i4 < end; ++i4) {
ret += String.fromCharCode(buf[i4] & 127);
}
return ret;
}
function latin1Slice(buf, start, end) {
let ret = "";
end = Math.min(buf.length, end);
for (let i4 = start; i4 < end; ++i4) {
ret += String.fromCharCode(buf[i4]);
}
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 i4 = start; i4 < end; ++i4) {
out += hexSliceLookupTable[buf[i4]];
}
return out;
}
function utf16leSlice(buf, start, end) {
const bytes = buf.slice(start, end);
let res = "";
for (let i4 = 0; i4 < bytes.length - 1; i4 += 2) {
res += String.fromCharCode(bytes[i4] + bytes[i4 + 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(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0)
throw new RangeError("offset is not uint");
if (offset + ext > length)
throw new RangeError("Trying to access beyond buffer length");
}
Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert)
checkOffset(offset, byteLength2, this.length);
let val2 = this[offset];
let mul = 1;
let i4 = 0;
while (++i4 < byteLength2 && (mul *= 256)) {
val2 += this[offset + i4] * mul;
}
return val2;
};
Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength2, this.length);
}
let val2 = this[offset + --byteLength2];
let mul = 1;
while (byteLength2 > 0 && (mul *= 256)) {
val2 += this[offset + --byteLength2] * mul;
}
return val2;
};
Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
};
Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32));
});
Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
return (BigInt(hi) << BigInt(32)) + BigInt(lo);
});
Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert)
checkOffset(offset, byteLength2, this.length);
let val2 = this[offset];
let mul = 1;
let i4 = 0;
while (++i4 < byteLength2 && (mul *= 256)) {
val2 += this[offset + i4] * mul;
}
mul *= 128;
if (val2 >= mul)
val2 -= Math.pow(2, 8 * byteLength2);
return val2;
};
Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert)
checkOffset(offset, byteLength2, this.length);
let i4 = byteLength2;
let mul = 1;
let val2 = this[offset + --i4];
while (i4 > 0 && (mul *= 256)) {
val2 += this[offset + --i4] * mul;
}
mul *= 128;
if (val2 >= mul)
val2 -= Math.pow(2, 8 * byteLength2);
return val2;
};
Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 1, this.length);
if (!(this[offset] & 128))
return this[offset];
return (255 - this[offset] + 1) * -1;
};
Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 2, this.length);
const val2 = this[offset] | this[offset + 1] << 8;
return val2 & 32768 ? val2 | 4294901760 : val2;
};
Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 2, this.length);
const val2 = this[offset + 1] | this[offset] << 8;
return val2 & 32768 ? val2 | 4294901760 : val2;
};
Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const val2 = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
return (BigInt(val2) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
});
Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, "offset");
const first = this[offset];
const last = this[offset + 7];
if (first === void 0 || last === void 0) {
boundsError(offset, this.length - 8);
}
const val2 = (first << 24) + // Overflow
this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
return (BigInt(val2) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
});
Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert)
checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer2.isBuffer(buf))
throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min)
throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length)
throw new RangeError("Index out of range");
}
Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
checkInt(this, value, offset, byteLength2, maxBytes, 0);
}
let mul = 1;
let i4 = 0;
this[offset] = value & 255;
while (++i4 < byteLength2 && (mul *= 256)) {
this[offset + i4] = value / mul & 255;
}
return offset + byteLength2;
};
Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength2 = byteLength2 >>> 0;
if (!noAssert) {
const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
checkInt(this, value, offset, byteLength2, maxBytes, 0);
}
let i4 = byteLength2 - 1;
let mul = 1;
this[offset + i4] = value & 255;
while (--i4 >= 0 && (mul *= 256)) {
this[offset + i4] = value / mul & 255;
}
return offset + byteLength2;
};
Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 1, 255, 0);
this[offset] = value & 255;
return offset + 1;
};
Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 2, 65535, 0);
this[offset] = value & 255;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 2, 65535, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 255;
return offset + 2;
};
Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 4, 4294967295, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 255;
return offset + 4;
};
Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 4, 4294967295, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 255;
return offset + 4;
};
function wrtBigUInt64LE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
let lo = Number(value & BigInt(4294967295));
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
let hi = Number(value >> BigInt(32) & BigInt(4294967295));
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
return offset;
}
function wrtBigUInt64BE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
let lo = Number(value & BigInt(4294967295));
buf[offset + 7] = lo;
lo = lo >> 8;
buf[offset + 6] = lo;
lo = lo >> 8;
buf[offset + 5] = lo;
lo = lo >> 8;
buf[offset + 4] = lo;
let hi = Number(value >> BigInt(32) & BigInt(4294967295));
buf[offset + 3] = hi;
hi = hi >> 8;
buf[offset + 2] = hi;
hi = hi >> 8;
buf[offset + 1] = hi;
hi = hi >> 8;
buf[offset] = hi;
return offset + 8;
}
Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
});
Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
});
Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
const limit2 = Math.pow(2, 8 * byteLength2 - 1);
checkInt(this, value, offset, byteLength2, limit2 - 1, -limit2);
}
let i4 = 0;
let mul = 1;
let sub = 0;
this[offset] = value & 255;
while (++i4 < byteLength2 && (mul *= 256)) {
if (value < 0 && sub === 0 && this[offset + i4 - 1] !== 0) {
sub = 1;
}
this[offset + i4] = (value / mul >> 0) - sub & 255;
}
return offset + byteLength2;
};
Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
const limit2 = Math.pow(2, 8 * byteLength2 - 1);
checkInt(this, value, offset, byteLength2, limit2 - 1, -limit2);
}
let i4 = byteLength2 - 1;
let mul = 1;
let sub = 0;
this[offset + i4] = value & 255;
while (--i4 >= 0 && (mul *= 256)) {
if (value < 0 && sub === 0 && this[offset + i4 + 1] !== 0) {
sub = 1;
}
this[offset + i4] = (value / mul >> 0) - sub & 255;
}
return offset + byteLength2;
};
Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 1, 127, -128);
if (value < 0)
value = 255 + value + 1;
this[offset] = value & 255;
return offset + 1;
};
Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 2, 32767, -32768);
this[offset] = value & 255;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 2, 32767, -32768);
this[offset] = value >>> 8;
this[offset + 1] = value & 255;
return offset + 2;
};
Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 4, 2147483647, -2147483648);
this[offset] = value & 255;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert)
checkInt(this, value, offset, 4, 2147483647, -2147483648);
if (value < 0)
value = 4294967295 + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 255;
return offset + 4;
};
Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
});
Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
});
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length)
throw new RangeError("Index out of range");
if (offset < 0)
throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, 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 i4;
if (typeof val2 === "number") {
for (i4 = start; i4 < end; ++i4) {
this[i4] = 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 (i4 = 0; i4 < end - start; ++i4) {
this[i4 + start] = bytes[i4 % 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(name2) {
if (name2) {
return `${name2} is outside of buffer bounds`;
}
return "Attempt to access memory outside buffer bounds";
},
RangeError
);
E2(
"ERR_INVALID_ARG_TYPE",
function(name2, actual) {
return `The "${name2}" 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 i4 = val2.length;
const start = val2[0] === "-" ? 1 : 0;
for (; i4 >= start + 4; i4 -= 3) {
res = `_${val2.slice(i4 - 3, i4)}${res}`;
}
return `${val2.slice(0, i4)}${res}`;
}
function checkBounds(buf, offset, byteLength2) {
validateNumber(offset, "offset");
if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
boundsError(offset, buf.length - (byteLength2 + 1));
}
}
function checkIntBI(value, min, max, buf, offset, byteLength2) {
if (value > max || value < min) {
const n4 = typeof min === "bigint" ? "n" : "";
let range;
if (byteLength2 > 3) {
if (min === 0 || min === 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 = `>= ${min}${n4} and <= ${max}${n4}`;
}
throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
}
checkBounds(buf, offset, byteLength2);
}
function validateNumber(value, name2) {
if (typeof value !== "number") {
throw new errors2.ERR_INVALID_ARG_TYPE(name2, "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 i4 = 0; i4 < length; ++i4) {
codePoint = string.charCodeAt(i4);
if (codePoint > 55295 && codePoint < 57344) {
if (!leadSurrogate) {
if (codePoint > 56319) {
if ((units -= 3) > -1)
bytes.push(239, 191, 189);
continue;
} else if (i4 + 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 i4 = 0; i4 < str2.length; ++i4) {
byteArray.push(str2.charCodeAt(i4) & 255);
}
return byteArray;
}
function utf16leToBytes(str2, units) {
let c5, hi, lo;
const byteArray = [];
for (let i4 = 0; i4 < str2.length; ++i4) {
if ((units -= 2) < 0)
break;
c5 = str2.charCodeAt(i4);
hi = c5 >> 8;
lo = c5 % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str2) {
return base642.toByteArray(base64clean(str2));
}
function blitBuffer(src, dst, offset, length) {
let i4;
for (i4 = 0; i4 < length; ++i4) {
if (i4 + offset >= dst.length || i4 >= src.length)
break;
dst[i4 + offset] = src[i4];
}
return i4;
}
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 i4 = 0; i4 < 16; ++i4) {
const i16 = i4 * 16;
for (let j3 = 0; j3 < 16; ++j3) {
table[i16 + j3] = alphabet[i4] + 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 __defProp5 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp5(target, "name", { value, configurable: true });
var __export2 = (target, all) => {
for (var name2 in all)
__defProp5(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps2 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp3.call(to, key) && key !== except)
__defProp5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps2(__defProp5({}, "__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, offset = 0, length = input.byteLength - offset) => {
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, offset, 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 __defProp5 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp5(target, "name", { value, configurable: true });
var __export2 = (target, all) => {
for (var name2 in all)
__defProp5(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps2 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp3.call(to, key) && key !== except)
__defProp5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps2(__defProp5({}, "__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 (e4) {
this.error = e4;
}
};
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 i4 = 0; i4 < constants_1.BLOCK_SIZE; i4++) {
inner[i4] ^= 54;
outer[i4] ^= 92;
}
this.hash.update(inner);
this.outer.update(outer);
for (var i4 = 0; i4 < inner.byteLength; i4++) {
inner[i4] = 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, name2) => {
const tokenOrProvider = logins[name2];
if (typeof tokenOrProvider === "string") {
arr2.push([name2, tokenOrProvider]);
} else {
arr2.push(tokenOrProvider().then((token) => [name2, 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, index) => {
if (typeof acc !== "object") {
throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`);
} else if (Array.isArray(acc)) {
return acc[parseInt(index)];
}
return acc[index];
}, 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, v6]) => `${k3}=${v6}`).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, (c5) => `%${c5.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(([, v6]) => v6.default != null).map(([k3, v6]) => [k3, v6.default]);
if (paramsWithDefault.length > 0) {
for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
}
}
const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.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 (e4) {
}
}
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, partition3, getUserAgentPrefix;
var init_partition = __esm({
"node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() {
init_partitions();
selectedPartitionsInfo = partitions_default;
selectedUserAgentPrefix = "";
partition3 = (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: partition3
};
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_constants = __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_constants();
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 name2 = 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 = name2.indexOf(UA_NAME_SEPARATOR);
const prefix = name2.substring(0, prefixSeparatorIndex);
let uaName = name2.substring(prefixSeparatorIndex + 1);
if (prefix === "api") {
uaName = uaName.toLowerCase();
}
return [prefix, uaName, version2].filter((item) => item && item.length > 0).reduce((acc, item, index) => {
switch (index) {
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 [name2, instruction] of Object.entries(instructions)) {
switch (instruction.type) {
case "staticContextParams":
endpointParams[name2] = instruction.value;
break;
case "contextParams":
endpointParams[name2] = commandInput[instruction.name];
break;
case "clientContextParams":
case "builtInParams":
endpointParams[name2] = await createConfigValueProvider(instruction.name, name2, 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_constants2 = __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_constants2();
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 t4 = this.getCurrentTimeInSeconds();
const timeBucket = Math.floor(t4 * 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_constants3 = __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_constants3();
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_constants3();
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_constants3();
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_constants3();
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_constants3();
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, offset = 0) {
return byteToHex3[arr2[offset + 0]] + byteToHex3[arr2[offset + 1]] + byteToHex3[arr2[offset + 2]] + byteToHex3[arr2[offset + 3]] + "-" + byteToHex3[arr2[offset + 4]] + byteToHex3[arr2[offset + 5]] + "-" + byteToHex3[arr2[offset + 6]] + byteToHex3[arr2[offset + 7]] + "-" + byteToHex3[arr2[offset + 8]] + byteToHex3[arr2[offset + 9]] + "-" + byteToHex3[arr2[offset + 10]] + byteToHex3[arr2[offset + 11]] + byteToHex3[arr2[offset + 12]] + byteToHex3[arr2[offset + 13]] + byteToHex3[arr2[offset + 14]] + byteToHex3[arr2[offset + 15]];
}
var byteToHex3;
var init_stringify3 = __esm({
"node_modules/uuid/dist/esm-browser/stringify.js"() {
byteToHex3 = [];
for (let i4 = 0; i4 < 256; ++i4) {
byteToHex3.push((i4 + 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, offset) {
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) {
offset = offset || 0;
for (let i4 = 0; i4 < 16; ++i4) {
buf[offset + i4] = rnds[i4];
}
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 = (name2, aliases) => {
const _aliases = [];
if (name2) {
_aliases.push(name2);
}
if (aliases) {
for (const alias of aliases) {
_aliases.push(alias);
}
}
return _aliases;
};
getMiddlewareNameWithAliases = (name2, aliases) => {
return `${name2 || "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((a4, b3) => stepWeights[b3.step] - stepWeights[a4.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a4.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: name2, override, aliases: _aliases } = options;
const entry = {
step: "initialize",
priority: "normal",
middleware,
...options
};
const aliases = getAllAliases(name2, _aliases);
if (aliases.length > 0) {
if (aliases.some((alias) => entriesNameSet.has(alias))) {
if (!override)
throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name2, _aliases)}'`);
for (const alias of aliases) {
const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a4) => a4 === 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(name2, _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: name2, override, aliases: _aliases } = options;
const entry = {
middleware,
...options
};
const aliases = getAllAliases(name2, _aliases);
if (aliases.length > 0) {
if (aliases.some((alias) => entriesNameSet.has(alias))) {
if (!override)
throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name2, _aliases)}'`);
for (const alias of aliases) {
const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a4) => a4 === 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(name2, _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: name2, aliases: _aliases } = entry;
if (tags && tags.includes(toRemove)) {
const aliases = getAllAliases(name2, _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 i4 = 0, start = "A".charCodeAt(0), limit2 = "Z".charCodeAt(0); i4 + start <= limit2; i4++) {
const char = String.fromCharCode(i4 + start);
alphabetByEncoding[char] = i4;
alphabetByValue[i4] = char;
}
for (let i4 = 0, start = "a".charCodeAt(0), limit2 = "z".charCodeAt(0); i4 + start <= limit2; i4++) {
const char = String.fromCharCode(i4 + start);
const index = i4 + 26;
alphabetByEncoding[char] = index;
alphabetByValue[index] = char;
}
for (let i4 = 0; i4 < 10; i4++) {
alphabetByEncoding[i4.toString(10)] = i4 + 52;
const char = i4.toString(10);
const index = i4 + 52;
alphabetByEncoding[char] = index;
alphabetByValue[index] = 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 i4 = 0; i4 < input.length; i4 += 4) {
let bits = 0;
let bitLength = 0;
for (let j3 = i4, limit2 = i4 + 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 = i4 / 4 * 3;
bits >>= bitLength % bitsPerByte;
const byteLength = Math.floor(bitLength / bitsPerByte);
for (let k3 = 0; k3 < byteLength; k3++) {
const offset = (byteLength - k3 - 1) * bitsPerByte;
dataView.setUint8(chunkOffset + k3, (bits & 255 << offset) >> offset);
}
}
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 i4 = 0; i4 < input.length; i4 += 3) {
let bits = 0;
let bitLength = 0;
for (let j3 = i4, limit2 = Math.min(i4 + 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 offset = (bitClusterCount - k3) * bitsPerLetter;
str2 += alphabetByValue[(bits & maxLetterValue << offset) >> offset];
}
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 = (c5) => `%${c5.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 i4 = 0, iLen = value.length; i4 < iLen; i4++) {
parts.push(`${key}=${escapeUri(value[i4])}`);
}
} 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 offset = 0;
for (const chunk of chunks) {
collected.set(chunk, offset);
offset += 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 i4 = 0; i4 < bytes.byteLength; i4++) {
out += SHORT_TO_HEX[bytes[i4]];
}
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 i4 = 0; i4 < 256; i4++) {
let encodedByte = i4.toString(16).toLowerCase();
if (encodedByte.length === 1) {
encodedByte = `0${encodedByte}`;
}
SHORT_TO_HEX[i4] = encodedByte;
HEX_TO_SHORT[encodedByte] = i4;
}
}
});
// 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 name2 = stream?.__proto__?.constructor?.name || stream;
throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name2}`);
}
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 Command, ClassBuilder;
var init_command2 = __esm({
"node_modules/@smithy/smithy-client/dist-es/command.js"() {
init_dist_es23();
init_dist_es2();
Command = class {
constructor() {
this.middlewareStack = constructStack();
}
static classBuilder() {
return new ClassBuilder();
}
resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
this.middlewareStack.use(mw);
}
const stack = clientStack.concat(this.middlewareStack);
const { logger: logger2 } = configuration;
const handlerExecutionContext = {
logger: logger2,
clientName,
commandName,
inputFilterSensitiveLog,
outputFilterSensitiveLog,
[SMITHY_CONTEXT_KEY]: {
commandInstance: this,
...smithyContext
},
...additionalContext
};
const { requestHandler } = configuration;
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 Command {
static getEndpointParameterInstructions() {
return closure._ep;
}
constructor(...[input]) {
super();
this.serialize = closure._serializer;
this.deserialize = closure._deserializer;
this.input = input ?? {};
closure._init(this);
}
resolveMiddleware(stack, configuration, options) {
return this.resolveMiddlewareWithContext(stack, configuration, 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_constants4 = __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, size) => {
const expected = expectLong(value);
if (expected !== void 0 && castInt(expected, size) !== expected) {
throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
}
return expected;
};
castInt = (value, size) => {
switch (size) {
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 match = RFC3339.exec(value);
if (!match) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match;
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 match = RFC3339_WITH_OFFSET.exec(value);
if (!match) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match;
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(([, v6]) => v6 !== void 0).forEach(([k3, v6]) => {
if (exception[k3] == void 0 || exception[k3] === "") {
exception[k3] = v6;
}
});
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(c5) {
return "%" + c5.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_constants4();
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 (e4) {
const retryErrorInfo = getRetryErrorInfo(e4);
lastError = asSdkError(e4);
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, client, input, ...args) => {
return await client.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 = (name2, property) => {
if (!property) {
throw new Error(`Property \`${name2}\` 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 i4 = 0; i4 < encoded.length; i4 += 2) {
const encodedByte = encoded.slice(i4, i4 + 2).toLowerCase();
if (encodedByte in HEX_TO_SHORT2) {
out[i4 / 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 i4 = 0; i4 < bytes.byteLength; i4++) {
out += SHORT_TO_HEX2[bytes[i4]];
}
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 i4 = 0; i4 < 256; i4++) {
let encodedByte = i4.toString(16).toLowerCase();
if (encodedByte.length === 1) {
encodedByte = `0${encodedByte}`;
}
SHORT_TO_HEX2[i4] = encodedByte;
HEX_TO_SHORT2[encodedByte] = i4;
}
}
});
// 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_constants5 = __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_constants5();
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_constants5();
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_constants5();
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_constants5();
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 i4 = 0; i4 < 8; i4++) {
bytes[i4] ^= 255;
}
for (let i4 = 7; i4 > -1; i4--) {
bytes[i4]++;
if (bytes[i4] !== 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 i4 = 7, remaining = Math.abs(Math.round(number)); i4 > -1 && remaining > 0; i4--, remaining /= 256) {
bytes[i4] = 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 name2 of Object.keys(headers)) {
const lname = name2.toLowerCase();
if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) {
query[name2] = headers[name2];
delete headers[name2];
}
}
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_constants5();
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_constants5();
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((name2) => `${name2}:${canonicalHeaders[name2]}`).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 = (now) => {
const longDate = iso8601(now).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 (e4) {
if (e4?.name === "SyntaxError") {
Object.defineProperty(e4, "$responseBodyText", {
value: encoded
});
}
throw e4;
}
}
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 match = regex2.exec(string);
while (match) {
const allmatches = [];
allmatches.startIndex = regex2.lastIndex - match[0].length;
const len = match.length;
for (let index = 0; index < len; index++) {
allmatches.push(match[index]);
}
matches.push(allmatches);
match = regex2.exec(string);
}
return matches;
};
var isName = function(string) {
const match = regexName.exec(string);
return !(match === null || typeof match === "undefined");
};
exports.isExist = function(v6) {
return typeof v6 !== "undefined";
};
exports.isEmptyObject = function(obj) {
return Object.keys(obj).length === 0;
};
exports.merge = function(target, a4, arrayMode) {
if (a4) {
const keys = Object.keys(a4);
const len = keys.length;
for (let i4 = 0; i4 < len; i4++) {
if (arrayMode === "strict") {
target[keys[i4]] = [a4[keys[i4]]];
} else {
target[keys[i4]] = a4[keys[i4]];
}
}
}
};
exports.getValue = function(v6) {
if (exports.isExist(v6)) {
return v6;
} 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 i4 = 0; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "<" && xmlData[i4 + 1] === "?") {
i4 += 2;
i4 = readPI(xmlData, i4);
if (i4.err)
return i4;
} else if (xmlData[i4] === "<") {
let tagStartPos = i4;
i4++;
if (xmlData[i4] === "!") {
i4 = readCommentAndCDATA(xmlData, i4);
continue;
} else {
let closingTag = false;
if (xmlData[i4] === "/") {
closingTag = true;
i4++;
}
let tagName = "";
for (; i4 < xmlData.length && xmlData[i4] !== ">" && xmlData[i4] !== " " && xmlData[i4] !== " " && xmlData[i4] !== "\n" && xmlData[i4] !== "\r"; i4++) {
tagName += xmlData[i4];
}
tagName = tagName.trim();
if (tagName[tagName.length - 1] === "/") {
tagName = tagName.substring(0, tagName.length - 1);
i4--;
}
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, i4));
}
const result = readAttributeStr(xmlData, i4);
if (result === false) {
return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i4));
}
let attrStr = result.value;
i4 = result.index;
if (attrStr[attrStr.length - 1] === "/") {
const attrStrStart = i4 - 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, i4));
} 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, i4 - attrStr.length + isValid2.err.line));
}
if (reachedRoot === true) {
return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i4));
} else if (options.unpairedTags.indexOf(tagName) !== -1) {
} else {
tags.push({ tagName, tagStartPos });
}
tagFound = true;
}
for (i4++; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "<") {
if (xmlData[i4 + 1] === "!") {
i4++;
i4 = readCommentAndCDATA(xmlData, i4);
continue;
} else if (xmlData[i4 + 1] === "?") {
i4 = readPI(xmlData, ++i4);
if (i4.err)
return i4;
} else {
break;
}
} else if (xmlData[i4] === "&") {
const afterAmp = validateAmpersand(xmlData, i4);
if (afterAmp == -1)
return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i4));
i4 = afterAmp;
} else {
if (reachedRoot === true && !isWhiteSpace(xmlData[i4])) {
return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i4));
}
}
}
if (xmlData[i4] === "<") {
i4--;
}
}
} else {
if (isWhiteSpace(xmlData[i4])) {
continue;
}
return getErrorObject("InvalidChar", "char '" + xmlData[i4] + "' is not expected.", getLineNumberForPosition(xmlData, i4));
}
}
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((t4) => t4.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, i4) {
const start = i4;
for (; i4 < xmlData.length; i4++) {
if (xmlData[i4] == "?" || xmlData[i4] == " ") {
const tagname = xmlData.substr(start, i4 - start);
if (i4 > 5 && tagname === "xml") {
return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i4));
} else if (xmlData[i4] == "?" && xmlData[i4 + 1] == ">") {
i4++;
break;
} else {
continue;
}
}
}
return i4;
}
function readCommentAndCDATA(xmlData, i4) {
if (xmlData.length > i4 + 5 && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === "-") {
for (i4 += 3; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "-" && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === ">") {
i4 += 2;
break;
}
}
} else if (xmlData.length > i4 + 8 && xmlData[i4 + 1] === "D" && xmlData[i4 + 2] === "O" && xmlData[i4 + 3] === "C" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "Y" && xmlData[i4 + 6] === "P" && xmlData[i4 + 7] === "E") {
let angleBracketsCount = 1;
for (i4 += 8; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "<") {
angleBracketsCount++;
} else if (xmlData[i4] === ">") {
angleBracketsCount--;
if (angleBracketsCount === 0) {
break;
}
}
}
} else if (xmlData.length > i4 + 9 && xmlData[i4 + 1] === "[" && xmlData[i4 + 2] === "C" && xmlData[i4 + 3] === "D" && xmlData[i4 + 4] === "A" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "A" && xmlData[i4 + 7] === "[") {
for (i4 += 8; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "]" && xmlData[i4 + 1] === "]" && xmlData[i4 + 2] === ">") {
i4 += 2;
break;
}
}
}
return i4;
}
var doubleQuote = '"';
var singleQuote = "'";
function readAttributeStr(xmlData, i4) {
let attrStr = "";
let startChar = "";
let tagClosed = false;
for (; i4 < xmlData.length; i4++) {
if (xmlData[i4] === doubleQuote || xmlData[i4] === singleQuote) {
if (startChar === "") {
startChar = xmlData[i4];
} else if (startChar !== xmlData[i4]) {
} else {
startChar = "";
}
} else if (xmlData[i4] === ">") {
if (startChar === "") {
tagClosed = true;
break;
}
}
attrStr += xmlData[i4];
}
if (startChar !== "") {
return false;
}
return {
value: attrStr,
index: i4,
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 i4 = 0; i4 < matches.length; i4++) {
if (matches[i4][1].length === 0) {
return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' has no space in starting.", getPositionFromMatch(matches[i4]));
} else if (matches[i4][3] !== void 0 && matches[i4][4] === void 0) {
return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' is without value.", getPositionFromMatch(matches[i4]));
} else if (matches[i4][3] === void 0 && !options.allowBooleanAttributes) {
return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i4][2] + "' is not allowed.", getPositionFromMatch(matches[i4]));
}
const attrName = matches[i4][2];
if (!validateAttrName(attrName)) {
return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i4]));
}
if (!attrNames.hasOwnProperty(attrName)) {
attrNames[attrName] = 1;
} else {
return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i4]));
}
}
return true;
}
function validateNumberAmpersand(xmlData, i4) {
let re = /\d/;
if (xmlData[i4] === "x") {
i4++;
re = /[\da-fA-F]/;
}
for (; i4 < xmlData.length; i4++) {
if (xmlData[i4] === ";")
return i4;
if (!xmlData[i4].match(re))
break;
}
return -1;
}
function validateAmpersand(xmlData, i4) {
i4++;
if (xmlData[i4] === ";")
return -1;
if (xmlData[i4] === "#") {
i4++;
return validateNumberAmpersand(xmlData, i4);
}
let count3 = 0;
for (; i4 < xmlData.length; i4++, count3++) {
if (xmlData[i4].match(/\w/) && count3 < 20)
continue;
if (xmlData[i4] === ";")
break;
return -1;
}
return i4;
}
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, index) {
const lines = xmlData.substring(0, index).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(match) {
return match.startIndex + match[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, i4) {
const entities = {};
if (xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "C" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "Y" && xmlData[i4 + 7] === "P" && xmlData[i4 + 8] === "E") {
i4 = i4 + 9;
let angleBracketsCount = 1;
let hasBody = false, comment = false;
let exp = "";
for (; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "<" && !comment) {
if (hasBody && isEntity(xmlData, i4)) {
i4 += 7;
[entityName, val, i4] = readEntityExp(xmlData, i4 + 1);
if (val.indexOf("&") === -1)
entities[validateEntityName(entityName)] = {
regx: RegExp(`&${entityName};`, "g"),
val
};
} else if (hasBody && isElement(xmlData, i4))
i4 += 8;
else if (hasBody && isAttlist(xmlData, i4))
i4 += 8;
else if (hasBody && isNotation(xmlData, i4))
i4 += 9;
else if (isComment)
comment = true;
else
throw new Error("Invalid DOCTYPE");
angleBracketsCount++;
exp = "";
} else if (xmlData[i4] === ">") {
if (comment) {
if (xmlData[i4 - 1] === "-" && xmlData[i4 - 2] === "-") {
comment = false;
angleBracketsCount--;
}
} else {
angleBracketsCount--;
}
if (angleBracketsCount === 0) {
break;
}
} else if (xmlData[i4] === "[") {
hasBody = true;
} else {
exp += xmlData[i4];
}
}
if (angleBracketsCount !== 0) {
throw new Error(`Unclosed DOCTYPE`);
}
} else {
throw new Error(`Invalid Tag instead of DOCTYPE`);
}
return { entities, i: i4 };
}
function readEntityExp(xmlData, i4) {
let entityName2 = "";
for (; i4 < xmlData.length && (xmlData[i4] !== "'" && xmlData[i4] !== '"'); i4++) {
entityName2 += xmlData[i4];
}
entityName2 = entityName2.trim();
if (entityName2.indexOf(" ") !== -1)
throw new Error("External entites are not supported");
const startChar = xmlData[i4++];
let val2 = "";
for (; i4 < xmlData.length && xmlData[i4] !== startChar; i4++) {
val2 += xmlData[i4];
}
return [entityName2, val2, i4];
}
function isComment(xmlData, i4) {
if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "-" && xmlData[i4 + 3] === "-")
return true;
return false;
}
function isEntity(xmlData, i4) {
if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "N" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "I" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "Y")
return true;
return false;
}
function isElement(xmlData, i4) {
if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "L" && xmlData[i4 + 4] === "E" && xmlData[i4 + 5] === "M" && xmlData[i4 + 6] === "E" && xmlData[i4 + 7] === "N" && xmlData[i4 + 8] === "T")
return true;
return false;
}
function isAttlist(xmlData, i4) {
if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "A" && xmlData[i4 + 3] === "T" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "L" && xmlData[i4 + 6] === "I" && xmlData[i4 + 7] === "S" && xmlData[i4 + 8] === "T")
return true;
return false;
}
function isNotation(xmlData, i4) {
if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "N" && xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "A" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "I" && xmlData[i4 + 8] === "O" && xmlData[i4 + 9] === "N")
return true;
return false;
}
function validateEntityName(name2) {
if (util2.isName(name2))
return name2;
else
throw new Error(`Invalid entity name ${name2}`);
}
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 match = numRegex.exec(trimmedStr);
if (match) {
const sign = match[1];
const leadingZeros = match[2];
let numTrimmedByZeros = trimZeros(match[3]);
const eNotation = match[4] || match[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 i4 = 0; i4 < entKeys.length; i4++) {
const ent = entKeys[i4];
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 i4 = 0; i4 < len; i4++) {
const attrName = this.resolveNameSpace(matches[i4][1]);
let oldVal = matches[i4][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 i4 = 0; i4 < xmlData.length; i4++) {
const ch = xmlData[i4];
if (ch === "<") {
if (xmlData[i4 + 1] === "/") {
const closeIndex = findClosingIndex(xmlData, ">", i4, "Closing Tag is not closed.");
let tagName = xmlData.substring(i4 + 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 = "";
i4 = closeIndex;
} else if (xmlData[i4 + 1] === "?") {
let tagData = readTagExp(xmlData, i4, 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);
}
i4 = tagData.closeIndex + 1;
} else if (xmlData.substr(i4 + 1, 3) === "!--") {
const endIndex = findClosingIndex(xmlData, "-->", i4 + 4, "Comment is not closed.");
if (this.options.commentPropName) {
const comment = xmlData.substring(i4 + 4, endIndex - 2);
textData = this.saveTextToParentTag(textData, currentNode, jPath);
currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
}
i4 = endIndex;
} else if (xmlData.substr(i4 + 1, 2) === "!D") {
const result = readDocType(xmlData, i4);
this.docTypeEntities = result.entities;
i4 = result.i;
} else if (xmlData.substr(i4 + 1, 2) === "![") {
const closeIndex = findClosingIndex(xmlData, "]]>", i4, "CDATA is not closed.") - 2;
const tagExp = xmlData.substring(i4 + 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);
}
i4 = closeIndex + 2;
} else {
let result = readTagExp(xmlData, i4, 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);
}
i4 = result.closeIndex;
} else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
i4 = result.closeIndex;
} else {
const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
if (!result2)
throw new Error(`Unexpected end of ${rawTagName}`);
i4 = 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 = "";
i4 = closeIndex;
}
}
} else {
textData += xmlData[i4];
}
}
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, i4, closingChar = ">") {
let attrBoundary;
let tagExp = "";
for (let index = i4; index < xmlData.length; index++) {
let ch = xmlData[index];
if (attrBoundary) {
if (ch === attrBoundary)
attrBoundary = "";
} else if (ch === '"' || ch === "'") {
attrBoundary = ch;
} else if (ch === closingChar[0]) {
if (closingChar[1]) {
if (xmlData[index + 1] === closingChar[1]) {
return {
data: tagExp,
index
};
}
} else {
return {
data: tagExp,
index
};
}
} else if (ch === " ") {
ch = " ";
}
tagExp += ch;
}
}
function findClosingIndex(xmlData, str2, i4, errMsg) {
const closingIndex = xmlData.indexOf(str2, i4);
if (closingIndex === -1) {
throw new Error(errMsg);
} else {
return closingIndex + str2.length - 1;
}
}
function readTagExp(xmlData, i4, removeNSPrefix, closingChar = ">") {
const result = tagExpWithClosingIndex(xmlData, i4 + 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, i4) {
const startIndex = i4;
let openTagCount = 1;
for (; i4 < xmlData.length; i4++) {
if (xmlData[i4] === "<") {
if (xmlData[i4 + 1] === "/") {
const closeIndex = findClosingIndex(xmlData, ">", i4, `${tagName} is not closed`);
let closeTagName = xmlData.substring(i4 + 2, closeIndex).trim();
if (closeTagName === tagName) {
openTagCount--;
if (openTagCount === 0) {
return {
tagContent: xmlData.substring(startIndex, i4),
i: closeIndex
};
}
}
i4 = closeIndex;
} else if (xmlData[i4 + 1] === "?") {
const closeIndex = findClosingIndex(xmlData, "?>", i4 + 1, "StopNode is not closed.");
i4 = closeIndex;
} else if (xmlData.substr(i4 + 1, 3) === "!--") {
const closeIndex = findClosingIndex(xmlData, "-->", i4 + 3, "StopNode is not closed.");
i4 = closeIndex;
} else if (xmlData.substr(i4 + 1, 2) === "![") {
const closeIndex = findClosingIndex(xmlData, "]]>", i4, "StopNode is not closed.") - 2;
i4 = closeIndex;
} else {
const tagData = readTagExp(xmlData, i4, ">");
if (tagData) {
const openTagName = tagData && tagData.tagName;
if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
openTagCount++;
}
i4 = 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 i4 = 0; i4 < arr2.length; i4++) {
const tagObj = arr2[i4];
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 i4 = 0; i4 < keys.length; i4++) {
const key = keys[i4];
if (key !== ":@")
return key;
}
}
function assignAttributes(obj, attrMap, jpath, options) {
if (attrMap) {
const keys = Object.keys(attrMap);
const len = keys.length;
for (let i4 = 0; i4 < len; i4++) {
const atrrName = keys[i4];
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 i4 = 0; i4 < arr2.length; i4++) {
const tagObj = arr2[i4];
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 i4 = 0; i4 < keys.length; i4++) {
const key = keys[i4];
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 index in options.stopNodes) {
if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName)
return true;
}
return false;
}
function replaceEntitiesValue(textValue, options) {
if (textValue && textValue.length > 0 && options.processEntities) {
for (let i4 = 0; i4 < options.entities.length; i4++) {
const entity = options.entities[i4];
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, a4) {
return a4;
},
attributeValueProcessor: function(attrName, a4) {
return a4;
},
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 i4 = 0; i4 < this.options.entities.length; i4++) {
const entity = this.options.entities[i4];
textValue = textValue.replace(entity.regex, entity.val);
}
}
return textValue;
};
function indentate(level) {
return this.options.indentBy.repeat(level);
}
function isAttribute(name2) {
if (name2.startsWith(this.options.attributeNamePrefix) && name2 !== this.options.textNodeName) {
return name2.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 (e4) {
if (e4 && typeof e4 === "object") {
Object.defineProperty(e4, "$responseBodyText", {
value: encoded
});
}
throw e4;
}
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_constants6 = __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_util5, Sha256;
var init_webCryptoSha256 = __esm({
"node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js"() {
import_util5 = __toESM(require_main());
init_constants6();
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_util5.isEmptyData)(data)) {
return;
}
var update2 = (0, import_util5.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_util5.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_util5.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_util6, 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_util6 = __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_util6.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(e4, t4) {
"object" == typeof exports && "object" == typeof module2 ? module2.exports = t4() : "function" == typeof define && define.amd ? define([], t4) : "object" == typeof exports ? exports.bowser = t4() : e4.bowser = t4();
}(exports, function() {
return function(e4) {
var t4 = {};
function r4(n4) {
if (t4[n4])
return t4[n4].exports;
var i4 = t4[n4] = { i: n4, l: false, exports: {} };
return e4[n4].call(i4.exports, i4, i4.exports, r4), i4.l = true, i4.exports;
}
return r4.m = e4, r4.c = t4, r4.d = function(e5, t5, n4) {
r4.o(e5, t5) || Object.defineProperty(e5, t5, { enumerable: true, get: n4 });
}, r4.r = function(e5) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e5, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e5, "__esModule", { value: true });
}, r4.t = function(e5, t5) {
if (1 & t5 && (e5 = r4(e5)), 8 & t5)
return e5;
if (4 & t5 && "object" == typeof e5 && e5 && e5.__esModule)
return e5;
var n4 = /* @__PURE__ */ Object.create(null);
if (r4.r(n4), Object.defineProperty(n4, "default", { enumerable: true, value: e5 }), 2 & t5 && "string" != typeof e5)
for (var i4 in e5)
r4.d(n4, i4, function(t6) {
return e5[t6];
}.bind(null, i4));
return n4;
}, r4.n = function(e5) {
var t5 = e5 && e5.__esModule ? function() {
return e5.default;
} : function() {
return e5;
};
return r4.d(t5, "a", t5), t5;
}, r4.o = function(e5, t5) {
return Object.prototype.hasOwnProperty.call(e5, t5);
}, r4.p = "", r4(r4.s = 90);
}({ 17: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4 = r4(18), i4 = function() {
function e5() {
}
return e5.getFirstMatch = function(e6, t5) {
var r5 = t5.match(e6);
return r5 && r5.length > 0 && r5[1] || "";
}, e5.getSecondMatch = function(e6, t5) {
var r5 = t5.match(e6);
return r5 && r5.length > 1 && r5[2] || "";
}, e5.matchAndReturnConst = function(e6, t5, r5) {
if (e6.test(t5))
return r5;
}, e5.getWindowsVersionName = function(e6) {
switch (e6) {
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;
}
}, e5.getMacOSVersionName = function(e6) {
var t5 = e6.split(".").splice(0, 2).map(function(e7) {
return parseInt(e7, 10) || 0;
});
if (t5.push(0), 10 === t5[0])
switch (t5[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;
}
}, e5.getAndroidVersionName = function(e6) {
var t5 = e6.split(".").splice(0, 2).map(function(e7) {
return parseInt(e7, 10) || 0;
});
if (t5.push(0), !(1 === t5[0] && t5[1] < 5))
return 1 === t5[0] && t5[1] < 6 ? "Cupcake" : 1 === t5[0] && t5[1] >= 6 ? "Donut" : 2 === t5[0] && t5[1] < 2 ? "Eclair" : 2 === t5[0] && 2 === t5[1] ? "Froyo" : 2 === t5[0] && t5[1] > 2 ? "Gingerbread" : 3 === t5[0] ? "Honeycomb" : 4 === t5[0] && t5[1] < 1 ? "Ice Cream Sandwich" : 4 === t5[0] && t5[1] < 4 ? "Jelly Bean" : 4 === t5[0] && t5[1] >= 4 ? "KitKat" : 5 === t5[0] ? "Lollipop" : 6 === t5[0] ? "Marshmallow" : 7 === t5[0] ? "Nougat" : 8 === t5[0] ? "Oreo" : 9 === t5[0] ? "Pie" : void 0;
}, e5.getVersionPrecision = function(e6) {
return e6.split(".").length;
}, e5.compareVersions = function(t5, r5, n5) {
void 0 === n5 && (n5 = false);
var i5 = e5.getVersionPrecision(t5), s4 = e5.getVersionPrecision(r5), a4 = Math.max(i5, s4), o4 = 0, u4 = e5.map([t5, r5], function(t6) {
var r6 = a4 - e5.getVersionPrecision(t6), n6 = t6 + new Array(r6 + 1).join(".0");
return e5.map(n6.split("."), function(e6) {
return new Array(20 - e6.length).join("0") + e6;
}).reverse();
});
for (n5 && (o4 = a4 - Math.min(i5, s4)), a4 -= 1; a4 >= o4; ) {
if (u4[0][a4] > u4[1][a4])
return 1;
if (u4[0][a4] === u4[1][a4]) {
if (a4 === o4)
return 0;
a4 -= 1;
} else if (u4[0][a4] < u4[1][a4])
return -1;
}
}, e5.map = function(e6, t5) {
var r5, n5 = [];
if (Array.prototype.map)
return Array.prototype.map.call(e6, t5);
for (r5 = 0; r5 < e6.length; r5 += 1)
n5.push(t5(e6[r5]));
return n5;
}, e5.find = function(e6, t5) {
var r5, n5;
if (Array.prototype.find)
return Array.prototype.find.call(e6, t5);
for (r5 = 0, n5 = e6.length; r5 < n5; r5 += 1) {
var i5 = e6[r5];
if (t5(i5, r5))
return i5;
}
}, e5.assign = function(e6) {
for (var t5, r5, n5 = e6, i5 = arguments.length, s4 = new Array(i5 > 1 ? i5 - 1 : 0), a4 = 1; a4 < i5; a4++)
s4[a4 - 1] = arguments[a4];
if (Object.assign)
return Object.assign.apply(Object, [e6].concat(s4));
var o4 = function() {
var e7 = s4[t5];
"object" == typeof e7 && null !== e7 && Object.keys(e7).forEach(function(t6) {
n5[t6] = e7[t6];
});
};
for (t5 = 0, r5 = s4.length; t5 < r5; t5 += 1)
o4();
return e6;
}, e5.getBrowserAlias = function(e6) {
return n4.BROWSER_ALIASES_MAP[e6];
}, e5.getBrowserTypeByAlias = function(e6) {
return n4.BROWSER_MAP[e6] || "";
}, e5;
}();
t4.default = i4, e4.exports = t4.default;
}, 18: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.ENGINE_MAP = t4.OS_MAP = t4.PLATFORMS_MAP = t4.BROWSER_MAP = t4.BROWSER_ALIASES_MAP = void 0;
t4.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" };
t4.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" };
t4.PLATFORMS_MAP = { tablet: "tablet", mobile: "mobile", desktop: "desktop", tv: "tv" };
t4.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" };
t4.ENGINE_MAP = { EdgeHTML: "EdgeHTML", Blink: "Blink", Trident: "Trident", Presto: "Presto", Gecko: "Gecko", WebKit: "WebKit" };
}, 90: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4, i4 = (n4 = r4(91)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
function a4(e5, t5) {
for (var r5 = 0; r5 < t5.length; r5++) {
var n5 = t5[r5];
n5.enumerable = n5.enumerable || false, n5.configurable = true, "value" in n5 && (n5.writable = true), Object.defineProperty(e5, n5.key, n5);
}
}
var o4 = function() {
function e5() {
}
var t5, r5, n5;
return e5.getParser = function(e6, t6) {
if (void 0 === t6 && (t6 = false), "string" != typeof e6)
throw new Error("UserAgent should be a string");
return new i4.default(e6, t6);
}, e5.parse = function(e6) {
return new i4.default(e6).getResult();
}, t5 = e5, 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) && a4(t5.prototype, r5), n5 && a4(t5, n5), e5;
}();
t4.default = o4, e4.exports = t4.default;
}, 91: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4 = u4(r4(92)), i4 = u4(r4(93)), s4 = u4(r4(94)), a4 = u4(r4(95)), o4 = u4(r4(17));
function u4(e5) {
return e5 && e5.__esModule ? e5 : { default: e5 };
}
var d3 = function() {
function e5(e6, t6) {
if (void 0 === t6 && (t6 = false), null == e6 || "" === e6)
throw new Error("UserAgent parameter can't be empty");
this._ua = e6, this.parsedResult = {}, true !== t6 && this.parse();
}
var t5 = e5.prototype;
return t5.getUA = function() {
return this._ua;
}, t5.test = function(e6) {
return e6.test(this._ua);
}, t5.parseBrowser = function() {
var e6 = this;
this.parsedResult.browser = {};
var t6 = o4.default.find(n4.default, function(t7) {
if ("function" == typeof t7.test)
return t7.test(e6);
if (t7.test instanceof Array)
return t7.test.some(function(t8) {
return e6.test(t8);
});
throw new Error("Browser's test function is not valid");
});
return t6 && (this.parsedResult.browser = t6.describe(this.getUA())), this.parsedResult.browser;
}, t5.getBrowser = function() {
return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser();
}, t5.getBrowserName = function(e6) {
return e6 ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || "";
}, t5.getBrowserVersion = function() {
return this.getBrowser().version;
}, t5.getOS = function() {
return this.parsedResult.os ? this.parsedResult.os : this.parseOS();
}, t5.parseOS = function() {
var e6 = this;
this.parsedResult.os = {};
var t6 = o4.default.find(i4.default, function(t7) {
if ("function" == typeof t7.test)
return t7.test(e6);
if (t7.test instanceof Array)
return t7.test.some(function(t8) {
return e6.test(t8);
});
throw new Error("Browser's test function is not valid");
});
return t6 && (this.parsedResult.os = t6.describe(this.getUA())), this.parsedResult.os;
}, t5.getOSName = function(e6) {
var t6 = this.getOS().name;
return e6 ? String(t6).toLowerCase() || "" : t6 || "";
}, t5.getOSVersion = function() {
return this.getOS().version;
}, t5.getPlatform = function() {
return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform();
}, t5.getPlatformType = function(e6) {
void 0 === e6 && (e6 = false);
var t6 = this.getPlatform().type;
return e6 ? String(t6).toLowerCase() || "" : t6 || "";
}, t5.parsePlatform = function() {
var e6 = this;
this.parsedResult.platform = {};
var t6 = o4.default.find(s4.default, function(t7) {
if ("function" == typeof t7.test)
return t7.test(e6);
if (t7.test instanceof Array)
return t7.test.some(function(t8) {
return e6.test(t8);
});
throw new Error("Browser's test function is not valid");
});
return t6 && (this.parsedResult.platform = t6.describe(this.getUA())), this.parsedResult.platform;
}, t5.getEngine = function() {
return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine();
}, t5.getEngineName = function(e6) {
return e6 ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || "";
}, t5.parseEngine = function() {
var e6 = this;
this.parsedResult.engine = {};
var t6 = o4.default.find(a4.default, function(t7) {
if ("function" == typeof t7.test)
return t7.test(e6);
if (t7.test instanceof Array)
return t7.test.some(function(t8) {
return e6.test(t8);
});
throw new Error("Browser's test function is not valid");
});
return t6 && (this.parsedResult.engine = t6.describe(this.getUA())), this.parsedResult.engine;
}, t5.parse = function() {
return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(), this;
}, t5.getResult = function() {
return o4.default.assign({}, this.parsedResult);
}, t5.satisfies = function(e6) {
var t6 = this, r5 = {}, n5 = 0, i5 = {}, s5 = 0;
if (Object.keys(e6).forEach(function(t7) {
var a6 = e6[t7];
"string" == typeof a6 ? (i5[t7] = a6, s5 += 1) : "object" == typeof a6 && (r5[t7] = a6, n5 += 1);
}), n5 > 0) {
var a5 = Object.keys(r5), u5 = o4.default.find(a5, function(e7) {
return t6.isOS(e7);
});
if (u5) {
var d4 = this.satisfies(r5[u5]);
if (void 0 !== d4)
return d4;
}
var c5 = o4.default.find(a5, function(e7) {
return t6.isPlatform(e7);
});
if (c5) {
var f4 = this.satisfies(r5[c5]);
if (void 0 !== f4)
return f4;
}
}
if (s5 > 0) {
var l4 = Object.keys(i5), h4 = o4.default.find(l4, function(e7) {
return t6.isBrowser(e7, true);
});
if (void 0 !== h4)
return this.compareVersion(i5[h4]);
}
}, t5.isBrowser = function(e6, t6) {
void 0 === t6 && (t6 = false);
var r5 = this.getBrowserName().toLowerCase(), n5 = e6.toLowerCase(), i5 = o4.default.getBrowserTypeByAlias(n5);
return t6 && i5 && (n5 = i5.toLowerCase()), n5 === r5;
}, t5.compareVersion = function(e6) {
var t6 = [0], r5 = e6, n5 = false, i5 = this.getBrowserVersion();
if ("string" == typeof i5)
return ">" === e6[0] || "<" === e6[0] ? (r5 = e6.substr(1), "=" === e6[1] ? (n5 = true, r5 = e6.substr(2)) : t6 = [], ">" === e6[0] ? t6.push(1) : t6.push(-1)) : "=" === e6[0] ? r5 = e6.substr(1) : "~" === e6[0] && (n5 = true, r5 = e6.substr(1)), t6.indexOf(o4.default.compareVersions(i5, r5, n5)) > -1;
}, t5.isOS = function(e6) {
return this.getOSName(true) === String(e6).toLowerCase();
}, t5.isPlatform = function(e6) {
return this.getPlatformType(true) === String(e6).toLowerCase();
}, t5.isEngine = function(e6) {
return this.getEngineName(true) === String(e6).toLowerCase();
}, t5.is = function(e6, t6) {
return void 0 === t6 && (t6 = false), this.isBrowser(e6, t6) || this.isOS(e6) || this.isPlatform(e6);
}, t5.some = function(e6) {
var t6 = this;
return void 0 === e6 && (e6 = []), e6.some(function(e7) {
return t6.is(e7);
});
}, e5;
}();
t4.default = d3, e4.exports = t4.default;
}, 92: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4, i4 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 };
var s4 = /version\/(\d+(\.?_?\d+)+)/i, a4 = [{ test: [/googlebot/i], describe: function(e5) {
var t5 = { name: "Googlebot" }, r5 = i4.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/opera/i], describe: function(e5) {
var t5 = { name: "Opera" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/opr\/|opios/i], describe: function(e5) {
var t5 = { name: "Opera" }, r5 = i4.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/SamsungBrowser/i], describe: function(e5) {
var t5 = { name: "Samsung Internet for Android" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/Whale/i], describe: function(e5) {
var t5 = { name: "NAVER Whale Browser" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/MZBrowser/i], describe: function(e5) {
var t5 = { name: "MZ Browser" }, r5 = i4.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/focus/i], describe: function(e5) {
var t5 = { name: "Focus" }, r5 = i4.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/swing/i], describe: function(e5) {
var t5 = { name: "Swing" }, r5 = i4.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/coast/i], describe: function(e5) {
var t5 = { name: "Opera Coast" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/opt\/\d+(?:.?_?\d+)+/i], describe: function(e5) {
var t5 = { name: "Opera Touch" }, r5 = i4.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/yabrowser/i], describe: function(e5) {
var t5 = { name: "Yandex Browser" }, r5 = i4.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/ucbrowser/i], describe: function(e5) {
var t5 = { name: "UC Browser" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/Maxthon|mxios/i], describe: function(e5) {
var t5 = { name: "Maxthon" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/epiphany/i], describe: function(e5) {
var t5 = { name: "Epiphany" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/puffin/i], describe: function(e5) {
var t5 = { name: "Puffin" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/sleipnir/i], describe: function(e5) {
var t5 = { name: "Sleipnir" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/k-meleon/i], describe: function(e5) {
var t5 = { name: "K-Meleon" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/micromessenger/i], describe: function(e5) {
var t5 = { name: "WeChat" }, r5 = i4.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/qqbrowser/i], describe: function(e5) {
var t5 = { name: /qqbrowserlite/i.test(e5) ? "QQ Browser Lite" : "QQ Browser" }, r5 = i4.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/msie|trident/i], describe: function(e5) {
var t5 = { name: "Internet Explorer" }, r5 = i4.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/\sedg\//i], describe: function(e5) {
var t5 = { name: "Microsoft Edge" }, r5 = i4.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/edg([ea]|ios)/i], describe: function(e5) {
var t5 = { name: "Microsoft Edge" }, r5 = i4.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/vivaldi/i], describe: function(e5) {
var t5 = { name: "Vivaldi" }, r5 = i4.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/seamonkey/i], describe: function(e5) {
var t5 = { name: "SeaMonkey" }, r5 = i4.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/sailfish/i], describe: function(e5) {
var t5 = { name: "Sailfish" }, r5 = i4.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/silk/i], describe: function(e5) {
var t5 = { name: "Amazon Silk" }, r5 = i4.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/phantom/i], describe: function(e5) {
var t5 = { name: "PhantomJS" }, r5 = i4.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/slimerjs/i], describe: function(e5) {
var t5 = { name: "SlimerJS" }, r5 = i4.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e5) {
var t5 = { name: "BlackBerry" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/(web|hpw)[o0]s/i], describe: function(e5) {
var t5 = { name: "WebOS Browser" }, r5 = i4.default.getFirstMatch(s4, e5) || i4.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/bada/i], describe: function(e5) {
var t5 = { name: "Bada" }, r5 = i4.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/tizen/i], describe: function(e5) {
var t5 = { name: "Tizen" }, r5 = i4.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/qupzilla/i], describe: function(e5) {
var t5 = { name: "QupZilla" }, r5 = i4.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/firefox|iceweasel|fxios/i], describe: function(e5) {
var t5 = { name: "Firefox" }, r5 = i4.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/electron/i], describe: function(e5) {
var t5 = { name: "Electron" }, r5 = i4.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/MiuiBrowser/i], describe: function(e5) {
var t5 = { name: "Miui" }, r5 = i4.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/chromium/i], describe: function(e5) {
var t5 = { name: "Chromium" }, r5 = i4.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, e5) || i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/chrome|crios|crmo/i], describe: function(e5) {
var t5 = { name: "Chrome" }, r5 = i4.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/GSA/i], describe: function(e5) {
var t5 = { name: "Google Search" }, r5 = i4.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: function(e5) {
var t5 = !e5.test(/like android/i), r5 = e5.test(/android/i);
return t5 && r5;
}, describe: function(e5) {
var t5 = { name: "Android Browser" }, r5 = i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/playstation 4/i], describe: function(e5) {
var t5 = { name: "PlayStation 4" }, r5 = i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/safari|applewebkit/i], describe: function(e5) {
var t5 = { name: "Safari" }, r5 = i4.default.getFirstMatch(s4, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/.*/i], describe: function(e5) {
var t5 = -1 !== e5.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /;
return { name: i4.default.getFirstMatch(t5, e5), version: i4.default.getSecondMatch(t5, e5) };
} }];
t4.default = a4, e4.exports = t4.default;
}, 93: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4, i4 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
var a4 = [{ test: [/Roku\/DVP/], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, e5);
return { name: s4.OS_MAP.Roku, version: t5 };
} }, { test: [/windows phone/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, e5);
return { name: s4.OS_MAP.WindowsPhone, version: t5 };
} }, { test: [/windows /i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, e5), r5 = i4.default.getWindowsVersionName(t5);
return { name: s4.OS_MAP.Windows, version: t5, versionName: r5 };
} }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function(e5) {
var t5 = { name: s4.OS_MAP.iOS }, r5 = i4.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/macintosh/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, e5).replace(/[_\s]/g, "."), r5 = i4.default.getMacOSVersionName(t5), n5 = { name: s4.OS_MAP.MacOS, version: t5 };
return r5 && (n5.versionName = r5), n5;
} }, { test: [/(ipod|iphone|ipad)/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, e5).replace(/[_\s]/g, ".");
return { name: s4.OS_MAP.iOS, version: t5 };
} }, { test: function(e5) {
var t5 = !e5.test(/like android/i), r5 = e5.test(/android/i);
return t5 && r5;
}, describe: function(e5) {
var t5 = i4.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, e5), r5 = i4.default.getAndroidVersionName(t5), n5 = { name: s4.OS_MAP.Android, version: t5 };
return r5 && (n5.versionName = r5), n5;
} }, { test: [/(web|hpw)[o0]s/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, e5), r5 = { name: s4.OS_MAP.WebOS };
return t5 && t5.length && (r5.version = t5), r5;
} }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, e5) || i4.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, e5) || i4.default.getFirstMatch(/\bbb(\d+)/i, e5);
return { name: s4.OS_MAP.BlackBerry, version: t5 };
} }, { test: [/bada/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, e5);
return { name: s4.OS_MAP.Bada, version: t5 };
} }, { test: [/tizen/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, e5);
return { name: s4.OS_MAP.Tizen, version: t5 };
} }, { 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(e5) {
var t5 = i4.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, e5);
return { name: s4.OS_MAP.PlayStation4, version: t5 };
} }];
t4.default = a4, e4.exports = t4.default;
}, 94: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4, i4 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
var a4 = [{ test: [/googlebot/i], describe: function() {
return { type: "bot", vendor: "Google" };
} }, { test: [/huawei/i], describe: function(e5) {
var t5 = i4.default.getFirstMatch(/(can-l01)/i, e5) && "Nova", r5 = { type: s4.PLATFORMS_MAP.mobile, vendor: "Huawei" };
return t5 && (r5.model = t5), 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(e5) {
var t5 = e5.test(/ipod|iphone/i), r5 = e5.test(/like (ipod|iphone)/i);
return t5 && !r5;
}, describe: function(e5) {
var t5 = i4.default.getFirstMatch(/(ipod|iphone)/i, e5);
return { type: s4.PLATFORMS_MAP.mobile, vendor: "Apple", model: t5 };
} }, { 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(e5) {
return "blackberry" === e5.getBrowserName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.mobile, vendor: "BlackBerry" };
} }, { test: function(e5) {
return "bada" === e5.getBrowserName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.mobile };
} }, { test: function(e5) {
return "windows phone" === e5.getBrowserName();
}, describe: function() {
return { type: s4.PLATFORMS_MAP.mobile, vendor: "Microsoft" };
} }, { test: function(e5) {
var t5 = Number(String(e5.getOSVersion()).split(".")[0]);
return "android" === e5.getOSName(true) && t5 >= 3;
}, describe: function() {
return { type: s4.PLATFORMS_MAP.tablet };
} }, { test: function(e5) {
return "android" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.mobile };
} }, { test: function(e5) {
return "macos" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.desktop, vendor: "Apple" };
} }, { test: function(e5) {
return "windows" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.desktop };
} }, { test: function(e5) {
return "linux" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.desktop };
} }, { test: function(e5) {
return "playstation 4" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.tv };
} }, { test: function(e5) {
return "roku" === e5.getOSName(true);
}, describe: function() {
return { type: s4.PLATFORMS_MAP.tv };
} }];
t4.default = a4, e4.exports = t4.default;
}, 95: function(e4, t4, r4) {
"use strict";
t4.__esModule = true, t4.default = void 0;
var n4, i4 = (n4 = r4(17)) && n4.__esModule ? n4 : { default: n4 }, s4 = r4(18);
var a4 = [{ test: function(e5) {
return "microsoft edge" === e5.getBrowserName(true);
}, describe: function(e5) {
if (/\sedg\//i.test(e5))
return { name: s4.ENGINE_MAP.Blink };
var t5 = i4.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, e5);
return { name: s4.ENGINE_MAP.EdgeHTML, version: t5 };
} }, { test: [/trident/i], describe: function(e5) {
var t5 = { name: s4.ENGINE_MAP.Trident }, r5 = i4.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: function(e5) {
return e5.test(/presto/i);
}, describe: function(e5) {
var t5 = { name: s4.ENGINE_MAP.Presto }, r5 = i4.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: function(e5) {
var t5 = e5.test(/gecko/i), r5 = e5.test(/like gecko/i);
return t5 && !r5;
}, describe: function(e5) {
var t5 = { name: s4.ENGINE_MAP.Gecko }, r5 = i4.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }, { test: [/(apple)?webkit\/537\.36/i], describe: function() {
return { name: s4.ENGINE_MAP.Blink };
} }, { test: [/(apple)?webkit/i], describe: function(e5) {
var t5 = { name: s4.ENGINE_MAP.WebKit }, r5 = i4.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, e5);
return r5 && (t5.version = r5), t5;
} }];
t4.default = a4, e4.exports = t4.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 i4 = len - 1; i4 >= 0; i4--) {
const code = body.charCodeAt(i4);
if (code > 127 && code <= 2047)
len++;
else if (code > 2047 && code <= 65535)
len += 2;
if (code >= 56320 && code <= 57343)
i4--;
}
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, r, _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];
r = [{ [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]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r, 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_constants7 = __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_constants7();
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 platform = parsedUA?.platform?.type;
return platform === "tablet" || platform === "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 index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 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 = (t4) => t4;
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(...[configuration]) {
const _config_0 = getRuntimeConfig2(configuration || {});
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, configuration?.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((e4) => e4 != 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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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, 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 = client ?? 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, v6]) => {
acc[k3] = v6;
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 (e4) {
}
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 i4 = 0; i4 < maxRetries; ++i4) {
try {
return await toRetry();
} catch (e4) {
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, r2, 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" };
r2 = { [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, r2, { [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: [r2], 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 index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
if (index === -1) {
_httpAuthSchemes.push(httpAuthScheme);
} else {
_httpAuthSchemes.splice(index, 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 = (t4) => t4;
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(...[configuration]) {
const _config_0 = getRuntimeConfig4(configuration || {});
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, configuration?.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, _a3, _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[_a3] != null) {
entries[_a3] = input[_a3];
}
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";
_a3 = "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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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 Command.classBuilder().ep({
...commonParams2
}).m(function(Command2, cs, config, o4) {
return [
getSerdePlugin(config, this.serialize, this.deserialize),
getEndpointPlugin(config, Command2.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: () => Command,
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 = (init2) => async () => {
init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2;
let { roleAssumerWithWebIdentity } = init2;
if (!roleAssumerWithWebIdentity) {
const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => (init_dist_es57(), dist_es_exports));
roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
...init2.clientConfig,
credentialProviderLogger: init2.logger,
parentClientConfig: init2.parentClientConfig
}, init2.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 = (init2) => fromWebToken({
...init2
});
}
});
// 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: () => __classPrivateFieldGet11,
__classPrivateFieldIn: () => __classPrivateFieldIn2,
__classPrivateFieldSet: () => __classPrivateFieldSet10,
__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, e4) {
var t4 = {};
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
t4[p4] = s4[p4];
if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) {
if (e4.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4]))
t4[p4[i4]] = s4[p4[i4]];
}
return t4;
}
function __decorate2(decorators, target, key, desc) {
var c5 = arguments.length, r4 = c5 < 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 i4 = decorators.length - 1; i4 >= 0; i4--)
if (d3 = decorators[i4])
r4 = (c5 < 3 ? d3(r4) : c5 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
return c5 > 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(f4) {
if (f4 !== void 0 && typeof f4 !== "function")
throw new TypeError("Function expected");
return f4;
}
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 i4 = decorators.length - 1; i4 >= 0; i4--) {
var context = {};
for (var p4 in contextIn)
context[p4] = p4 === "access" ? {} : contextIn[p4];
for (var p4 in contextIn.access)
context.access[p4] = contextIn.access[p4];
context.addInitializer = function(f4) {
if (done)
throw new TypeError("Cannot add initializers after decoration has completed");
extraInitializers.push(accept(f4 || null));
};
var result = (0, decorators[i4])(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 i4 = 0; i4 < initializers.length; i4++) {
value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg);
}
return useValue ? value : void 0;
}
function __propKey2(x2) {
return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName2(f4, name2, prefix) {
if (typeof name2 === "symbol")
name2 = name2.description ? "[".concat(name2.description, "]") : "";
return Object.defineProperty(f4, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name2) : name2 });
}
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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 (t4[0] & 1)
throw t4[1];
return t4[1];
}, trys: [], ops: [] }, f4, y3, t4, 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(v6) {
return step([n4, v6]);
};
}
function step(op) {
if (f4)
throw new TypeError("Generator is already executing.");
while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
try {
if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
return t4;
if (y3 = 0, t4)
op = [op[0] & 2, t4.value];
switch (op[0]) {
case 0:
case 1:
t4 = op;
break;
case 4:
_2.label++;
return { value: op[1], done: false };
case 5:
_2.label++;
y3 = op[1];
op = [0];
continue;
case 7:
op = _2.ops.pop();
_2.trys.pop();
continue;
default:
if (!(t4 = _2.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_2 = 0;
continue;
}
if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
_2.label = op[1];
break;
}
if (op[0] === 6 && _2.label < t4[1]) {
_2.label = t4[1];
t4 = op;
break;
}
if (t4 && _2.label < t4[2]) {
_2.label = t4[2];
_2.ops.push(op);
break;
}
if (t4[2])
_2.ops.pop();
_2.trys.pop();
continue;
}
op = body.call(thisArg, _2);
} catch (e4) {
op = [6, e4];
y3 = 0;
} finally {
f4 = t4 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar2(m3, o4) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(o4, p4))
__createBinding2(o4, m3, p4);
}
function __values3(o4) {
var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o4[s4], i4 = 0;
if (m3)
return m3.call(o4);
if (o4 && typeof o4.length === "number")
return {
next: function() {
if (o4 && i4 >= o4.length)
o4 = void 0;
return { value: o4 && o4[i4++], done: !o4 };
}
};
throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read2(o4, n4) {
var m3 = typeof Symbol === "function" && o4[Symbol.iterator];
if (!m3)
return o4;
var i4 = m3.call(o4), r4, ar = [], e4;
try {
while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done)
ar.push(r4.value);
} catch (error) {
e4 = { error };
} finally {
try {
if (r4 && !r4.done && (m3 = i4["return"]))
m3.call(i4);
} finally {
if (e4)
throw e4.error;
}
}
return ar;
}
function __spread2() {
for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
ar = ar.concat(__read2(arguments[i4]));
return ar;
}
function __spreadArrays2() {
for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++)
s4 += arguments[i4].length;
for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
for (var a4 = arguments[i4], j3 = 0, jl = a4.length; j3 < jl; j3++, k3++)
r4[k3] = a4[j3];
return r4;
}
function __spreadArray2(to, from, pack) {
if (pack || arguments.length === 2)
for (var i4 = 0, l4 = from.length, ar; i4 < l4; i4++) {
if (ar || !(i4 in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i4);
ar[i4] = from[i4];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await2(v6) {
return this instanceof __await2 ? (this.v = v6, this) : new __await2(v6);
}
function __asyncGenerator2(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function awaitReturn(f4) {
return function(v6) {
return Promise.resolve(v6).then(f4, reject);
};
}
function verb(n4, f4) {
if (g4[n4]) {
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
if (f4)
i4[n4] = f4(i4[n4]);
}
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), q3.shift(), q3.length)
resume(q3[0][0], q3[0][1]);
}
}
function __asyncDelegator2(o4) {
var i4, p4;
return i4 = {}, verb("next"), verb("throw", function(e4) {
throw e4;
}), verb("return"), i4[Symbol.iterator] = function() {
return this;
}, i4;
function verb(n4, f4) {
i4[n4] = o4[n4] ? function(v6) {
return (p4 = !p4) ? { value: __await2(o4[n4](v6)), done: false } : f4 ? f4(v6) : v6;
} : f4;
}
}
function __asyncValues2(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values3 === "function" ? __values3(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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 __classPrivateFieldGet11(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}
function __classPrivateFieldSet10(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.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 (e4) {
return Promise.reject(e4);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
}
function __disposeResources2(env) {
function fail(e4) {
env.error = env.hasError ? new _SuppressedError2(e4, env.error, "An error was suppressed during disposal.") : e4;
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(e4) {
fail(e4);
return next();
});
} else
s4 |= 1;
} catch (e4) {
fail(e4);
}
}
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 p4 in b4)
if (Object.prototype.hasOwnProperty.call(b4, p4))
d4[p4] = b4[p4];
};
return extendStatics2(d3, b3);
};
__assign2 = function() {
__assign2 = Object.assign || function __assign5(t4) {
for (var s4, i4 = 1, n4 = arguments.length; i4 < n4; i4++) {
s4 = arguments[i4];
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4))
t4[p4] = s4[p4];
}
return t4;
};
return __assign2.apply(this, arguments);
};
__createBinding2 = Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
};
__setModuleDefault2 = Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
};
_SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e4 = new Error(message);
return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
};
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: __classPrivateFieldGet11,
__classPrivateFieldSet: __classPrivateFieldSet10,
__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_client8 = __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_client8(), 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: name2, kind: kind4 = types_1.FieldPosition.HEADER, values = [] }) {
this.name = name2;
this.kind = kind4;
this.values = values;
}
add(value) {
this.values.push(value);
}
set(values) {
this.values = values;
}
remove(value) {
this.values = this.values.filter((v6) => v6 !== value);
}
toString() {
return this.values.map((v6) => v6.includes(",") || v6.includes(" ") ? `"${v6}"` : v6).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(name2) {
return this.entries[name2.toLowerCase()];
}
removeField(name2) {
delete this.entries[name2.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: () => __classPrivateFieldGet12,
__classPrivateFieldIn: () => __classPrivateFieldIn3,
__classPrivateFieldSet: () => __classPrivateFieldSet11,
__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, e4) {
var t4 = {};
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
t4[p4] = s4[p4];
if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) {
if (e4.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4]))
t4[p4[i4]] = s4[p4[i4]];
}
return t4;
}
function __decorate3(decorators, target, key, desc) {
var c5 = arguments.length, r4 = c5 < 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 i4 = decorators.length - 1; i4 >= 0; i4--)
if (d3 = decorators[i4])
r4 = (c5 < 3 ? d3(r4) : c5 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
return c5 > 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(f4) {
if (f4 !== void 0 && typeof f4 !== "function")
throw new TypeError("Function expected");
return f4;
}
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 i4 = decorators.length - 1; i4 >= 0; i4--) {
var context = {};
for (var p4 in contextIn)
context[p4] = p4 === "access" ? {} : contextIn[p4];
for (var p4 in contextIn.access)
context.access[p4] = contextIn.access[p4];
context.addInitializer = function(f4) {
if (done)
throw new TypeError("Cannot add initializers after decoration has completed");
extraInitializers.push(accept(f4 || null));
};
var result = (0, decorators[i4])(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 i4 = 0; i4 < initializers.length; i4++) {
value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg);
}
return useValue ? value : void 0;
}
function __propKey3(x2) {
return typeof x2 === "symbol" ? x2 : "".concat(x2);
}
function __setFunctionName3(f4, name2, prefix) {
if (typeof name2 === "symbol")
name2 = name2.description ? "[".concat(name2.description, "]") : "";
return Object.defineProperty(f4, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name2) : name2 });
}
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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 (t4[0] & 1)
throw t4[1];
return t4[1];
}, trys: [], ops: [] }, f4, y3, t4, 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(v6) {
return step([n4, v6]);
};
}
function step(op) {
if (f4)
throw new TypeError("Generator is already executing.");
while (g4 && (g4 = 0, op[0] && (_2 = 0)), _2)
try {
if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
return t4;
if (y3 = 0, t4)
op = [op[0] & 2, t4.value];
switch (op[0]) {
case 0:
case 1:
t4 = op;
break;
case 4:
_2.label++;
return { value: op[1], done: false };
case 5:
_2.label++;
y3 = op[1];
op = [0];
continue;
case 7:
op = _2.ops.pop();
_2.trys.pop();
continue;
default:
if (!(t4 = _2.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_2 = 0;
continue;
}
if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
_2.label = op[1];
break;
}
if (op[0] === 6 && _2.label < t4[1]) {
_2.label = t4[1];
t4 = op;
break;
}
if (t4 && _2.label < t4[2]) {
_2.label = t4[2];
_2.ops.push(op);
break;
}
if (t4[2])
_2.ops.pop();
_2.trys.pop();
continue;
}
op = body.call(thisArg, _2);
} catch (e4) {
op = [6, e4];
y3 = 0;
} finally {
f4 = t4 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar3(m3, o4) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(o4, p4))
__createBinding3(o4, m3, p4);
}
function __values4(o4) {
var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o4[s4], i4 = 0;
if (m3)
return m3.call(o4);
if (o4 && typeof o4.length === "number")
return {
next: function() {
if (o4 && i4 >= o4.length)
o4 = void 0;
return { value: o4 && o4[i4++], done: !o4 };
}
};
throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read3(o4, n4) {
var m3 = typeof Symbol === "function" && o4[Symbol.iterator];
if (!m3)
return o4;
var i4 = m3.call(o4), r4, ar = [], e4;
try {
while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done)
ar.push(r4.value);
} catch (error) {
e4 = { error };
} finally {
try {
if (r4 && !r4.done && (m3 = i4["return"]))
m3.call(i4);
} finally {
if (e4)
throw e4.error;
}
}
return ar;
}
function __spread3() {
for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
ar = ar.concat(__read3(arguments[i4]));
return ar;
}
function __spreadArrays3() {
for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++)
s4 += arguments[i4].length;
for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
for (var a4 = arguments[i4], j3 = 0, jl = a4.length; j3 < jl; j3++, k3++)
r4[k3] = a4[j3];
return r4;
}
function __spreadArray3(to, from, pack) {
if (pack || arguments.length === 2)
for (var i4 = 0, l4 = from.length, ar; i4 < l4; i4++) {
if (ar || !(i4 in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i4);
ar[i4] = from[i4];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await3(v6) {
return this instanceof __await3 ? (this.v = v6, this) : new __await3(v6);
}
function __asyncGenerator3(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function awaitReturn(f4) {
return function(v6) {
return Promise.resolve(v6).then(f4, reject);
};
}
function verb(n4, f4) {
if (g4[n4]) {
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
if (f4)
i4[n4] = f4(i4[n4]);
}
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), q3.shift(), q3.length)
resume(q3[0][0], q3[0][1]);
}
}
function __asyncDelegator3(o4) {
var i4, p4;
return i4 = {}, verb("next"), verb("throw", function(e4) {
throw e4;
}), verb("return"), i4[Symbol.iterator] = function() {
return this;
}, i4;
function verb(n4, f4) {
i4[n4] = o4[n4] ? function(v6) {
return (p4 = !p4) ? { value: __await3(o4[n4](v6)), done: false } : f4 ? f4(v6) : v6;
} : f4;
}
}
function __asyncValues3(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values4 === "function" ? __values4(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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 __classPrivateFieldGet12(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
}
function __classPrivateFieldSet11(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.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 (e4) {
return Promise.reject(e4);
}
};
env.stack.push({ value, dispose, async });
} else if (async) {
env.stack.push({ async: true });
}
return value;
}
function __disposeResources3(env) {
function fail(e4) {
env.error = env.hasError ? new _SuppressedError3(e4, env.error, "An error was suppressed during disposal.") : e4;
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(e4) {
fail(e4);
return next();
});
} else
s4 |= 1;
} catch (e4) {
fail(e4);
}
}
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 p4 in b4)
if (Object.prototype.hasOwnProperty.call(b4, p4))
d4[p4] = b4[p4];
};
return extendStatics3(d3, b3);
};
__assign3 = function() {
__assign3 = Object.assign || function __assign5(t4) {
for (var s4, i4 = 1, n4 = arguments.length; i4 < n4; i4++) {
s4 = arguments[i4];
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4))
t4[p4] = s4[p4];
}
return t4;
};
return __assign3.apply(this, arguments);
};
__createBinding3 = Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
};
__setModuleDefault3 = Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
};
_SuppressedError3 = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
var e4 = new Error(message);
return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
};
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: __classPrivateFieldGet12,
__classPrivateFieldSet: __classPrivateFieldSet11,
__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: () => __classPrivateFieldGet13,
__classPrivateFieldSet: () => __classPrivateFieldSet12,
__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, e4) {
var t4 = {};
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
t4[p4] = s4[p4];
if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) {
if (e4.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4]))
t4[p4[i4]] = s4[p4[i4]];
}
return t4;
}
function __decorate4(decorators, target, key, desc) {
var c5 = arguments.length, r4 = c5 < 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 i4 = decorators.length - 1; i4 >= 0; i4--)
if (d3 = decorators[i4])
r4 = (c5 < 3 ? d3(r4) : c5 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
return c5 > 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 (t4[0] & 1)
throw t4[1];
return t4[1];
}, trys: [], ops: [] }, f4, y3, t4, 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(v6) {
return step([n4, v6]);
};
}
function step(op) {
if (f4)
throw new TypeError("Generator is already executing.");
while (_2)
try {
if (f4 = 1, y3 && (t4 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t4 = y3["return"]) && t4.call(y3), 0) : y3.next) && !(t4 = t4.call(y3, op[1])).done)
return t4;
if (y3 = 0, t4)
op = [op[0] & 2, t4.value];
switch (op[0]) {
case 0:
case 1:
t4 = op;
break;
case 4:
_2.label++;
return { value: op[1], done: false };
case 5:
_2.label++;
y3 = op[1];
op = [0];
continue;
case 7:
op = _2.ops.pop();
_2.trys.pop();
continue;
default:
if (!(t4 = _2.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_2 = 0;
continue;
}
if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
_2.label = op[1];
break;
}
if (op[0] === 6 && _2.label < t4[1]) {
_2.label = t4[1];
t4 = op;
break;
}
if (t4 && _2.label < t4[2]) {
_2.label = t4[2];
_2.ops.push(op);
break;
}
if (t4[2])
_2.ops.pop();
_2.trys.pop();
continue;
}
op = body.call(thisArg, _2);
} catch (e4) {
op = [6, e4];
y3 = 0;
} finally {
f4 = t4 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding4(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
}
function __exportStar4(m3, exports) {
for (var p4 in m3)
if (p4 !== "default" && !exports.hasOwnProperty(p4))
exports[p4] = m3[p4];
}
function __values5(o4) {
var s4 = typeof Symbol === "function" && Symbol.iterator, m3 = s4 && o4[s4], i4 = 0;
if (m3)
return m3.call(o4);
if (o4 && typeof o4.length === "number")
return {
next: function() {
if (o4 && i4 >= o4.length)
o4 = void 0;
return { value: o4 && o4[i4++], done: !o4 };
}
};
throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read4(o4, n4) {
var m3 = typeof Symbol === "function" && o4[Symbol.iterator];
if (!m3)
return o4;
var i4 = m3.call(o4), r4, ar = [], e4;
try {
while ((n4 === void 0 || n4-- > 0) && !(r4 = i4.next()).done)
ar.push(r4.value);
} catch (error) {
e4 = { error };
} finally {
try {
if (r4 && !r4.done && (m3 = i4["return"]))
m3.call(i4);
} finally {
if (e4)
throw e4.error;
}
}
return ar;
}
function __spread4() {
for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
ar = ar.concat(__read4(arguments[i4]));
return ar;
}
function __spreadArrays4() {
for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++)
s4 += arguments[i4].length;
for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
for (var a4 = arguments[i4], j3 = 0, jl = a4.length; j3 < jl; j3++, k3++)
r4[k3] = a4[j3];
return r4;
}
function __await4(v6) {
return this instanceof __await4 ? (this.v = v6, this) : new __await4(v6);
}
function __asyncGenerator4(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function verb(n4) {
if (g4[n4])
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), q3.shift(), q3.length)
resume(q3[0][0], q3[0][1]);
}
}
function __asyncDelegator4(o4) {
var i4, p4;
return i4 = {}, verb("next"), verb("throw", function(e4) {
throw e4;
}), verb("return"), i4[Symbol.iterator] = function() {
return this;
}, i4;
function verb(n4, f4) {
i4[n4] = o4[n4] ? function(v6) {
return (p4 = !p4) ? { value: __await4(o4[n4](v6)), done: n4 === "return" } : f4 ? f4(v6) : v6;
} : f4;
}
}
function __asyncValues4(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values5 === "function" ? __values5(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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 __classPrivateFieldGet13(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet12(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 p4 in b4)
if (b4.hasOwnProperty(p4))
d4[p4] = b4[p4];
};
return extendStatics4(d3, b3);
};
__assign4 = function() {
__assign4 = Object.assign || function __assign5(t4) {
for (var s4, i4 = 1, n4 = arguments.length; i4 < n4; i4++) {
s4 = arguments[i4];
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4))
t4[p4] = s4[p4];
}
return t4;
};
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 i4 = 0, len = input.length; i4 < len; i4++) {
const value = input.charCodeAt(i4);
if (value < 128) {
bytes.push(value);
} else if (value < 2048) {
bytes.push(value >> 6 | 192, value & 63 | 128);
} else if (i4 + 1 < input.length && (value & 64512) === 55296 && (input.charCodeAt(i4 + 1) & 64512) === 56320) {
const surrogatePair = 65536 + ((value & 1023) << 10) + (input.charCodeAt(++i4) & 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 i4 = 0, len = input.length; i4 < len; i4++) {
const byte = input[i4];
if (byte < 128) {
decoded += String.fromCharCode(byte);
} else if (192 <= byte && byte < 224) {
const nextByte = input[++i4];
decoded += String.fromCharCode((byte & 31) << 6 | nextByte & 63);
} else if (240 <= byte && byte < 365) {
const surrogatePair = [byte, input[++i4], input[++i4], input[++i4]];
const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%");
decoded += decodeURIComponent(encoded);
} else {
decoded += String.fromCharCode((byte & 15) << 12 | (input[++i4] & 63) << 6 | input[++i4] & 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 i4 = 0; i4 < 256; i4++) {
let encodedByte = i4.toString(16).toLowerCase();
if (encodedByte.length === 1) {
encodedByte = `0${encodedByte}`;
}
SHORT_TO_HEX3[i4] = encodedByte;
HEX_TO_SHORT3[encodedByte] = i4;
}
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 i4 = 0; i4 < encoded.length; i4 += 2) {
const encodedByte = encoded.slice(i4, i4 + 2).toLowerCase();
if (encodedByte in HEX_TO_SHORT3) {
out[i4 / 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 i4 = 0; i4 < bytes.byteLength; i4++) {
out += SHORT_TO_HEX3[bytes[i4]];
}
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 i4 = 7, remaining = Math.abs(Math.round(number)); i4 > -1 && remaining > 0; i4--, remaining /= 256) {
bytes[i4] = 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 i4 = 0; i4 < 8; i4++) {
bytes[i4] ^= 255;
}
for (let i4 = 7; i4 > -1; i4--) {
bytes[i4]++;
if (bytes[i4] !== 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 name2 = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength));
position += nameLength;
switch (headers.getUint8(position++)) {
case 0:
out[name2] = {
type: BOOLEAN_TAG,
value: true
};
break;
case 1:
out[name2] = {
type: BOOLEAN_TAG,
value: false
};
break;
case 2:
out[name2] = {
type: BYTE_TAG,
value: headers.getInt8(position++)
};
break;
case 3:
out[name2] = {
type: SHORT_TAG,
value: headers.getInt16(position, false)
};
position += 2;
break;
case 4:
out[name2] = {
type: INT_TAG,
value: headers.getInt32(position, false)
};
position += 4;
break;
case 5:
out[name2] = {
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[name2] = {
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[name2] = {
type: STRING_TAG,
value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength))
};
position += stringLength;
break;
case 8:
out[name2] = {
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[name2] = {
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, offset = 0, length = input.byteLength - offset) => {
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, offset, 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 = (c5) => `%${c5.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 name2 of Object.keys(headers)) {
const lname = name2.toLowerCase();
if (lname.slice(0, 6) === "x-amz-" && !((_a5 = options.unhoistableHeaders) === null || _a5 === void 0 ? void 0 : _a5.has(lname))) {
query[name2] = headers[name2];
delete headers[name2];
}
}
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((name2) => `${name2}:${canonicalHeaders[name2]}`).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 = (now) => {
const longDate = (0, utilDate_1.iso8601)(now).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, name2, prop) {
return Object.defineProperty(self2, name2, prop);
},
ObjectGetOwnPropertyDescriptor(self2, name2) {
return Object.getOwnPropertyDescriptor(self2, name2);
},
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/@jspm/core/nodelibs/browser/chunk-4bd36a8f.js
function o3() {
o3.init.call(this);
}
function u3(e4) {
if ("function" != typeof e4)
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e4);
}
function f3(e4) {
return void 0 === e4._maxListeners ? o3.defaultMaxListeners : e4._maxListeners;
}
function v3(e4, t4, n4, r4) {
var i4, o4, s4, v6;
if (u3(n4), void 0 === (o4 = e4._events) ? (o4 = e4._events = /* @__PURE__ */ Object.create(null), e4._eventsCount = 0) : (void 0 !== o4.newListener && (e4.emit("newListener", t4, n4.listener ? n4.listener : n4), o4 = e4._events), s4 = o4[t4]), void 0 === s4)
s4 = o4[t4] = n4, ++e4._eventsCount;
else if ("function" == typeof s4 ? s4 = o4[t4] = r4 ? [n4, s4] : [s4, n4] : r4 ? s4.unshift(n4) : s4.push(n4), (i4 = f3(e4)) > 0 && s4.length > i4 && !s4.warned) {
s4.warned = true;
var a4 = new Error("Possible EventEmitter memory leak detected. " + s4.length + " " + String(t4) + " listeners added. Use emitter.setMaxListeners() to increase limit");
a4.name = "MaxListenersExceededWarning", a4.emitter = e4, a4.type = t4, a4.count = s4.length, v6 = a4, console && console.warn && console.warn(v6);
}
return e4;
}
function a3() {
if (!this.fired)
return this.target.removeListener(this.type, this.wrapFn), this.fired = true, 0 === arguments.length ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
}
function l3(e4, t4, n4) {
var r4 = { fired: false, wrapFn: void 0, target: e4, type: t4, listener: n4 }, i4 = a3.bind(r4);
return i4.listener = n4, r4.wrapFn = i4, i4;
}
function h3(e4, t4, n4) {
var r4 = e4._events;
if (void 0 === r4)
return [];
var i4 = r4[t4];
return void 0 === i4 ? [] : "function" == typeof i4 ? n4 ? [i4.listener || i4] : [i4] : n4 ? function(e5) {
for (var t5 = new Array(e5.length), n5 = 0; n5 < t5.length; ++n5)
t5[n5] = e5[n5].listener || e5[n5];
return t5;
}(i4) : c3(i4, i4.length);
}
function p3(e4) {
var t4 = this._events;
if (void 0 !== t4) {
var n4 = t4[e4];
if ("function" == typeof n4)
return 1;
if (void 0 !== n4)
return n4.length;
}
return 0;
}
function c3(e4, t4) {
for (var n4 = new Array(t4), r4 = 0; r4 < t4; ++r4)
n4[r4] = e4[r4];
return n4;
}
var e3, t3, n3, r3, i3, s3, y2;
var init_chunk_4bd36a8f = __esm({
"node_modules/@jspm/core/nodelibs/browser/chunk-4bd36a8f.js"() {
n3 = "object" == typeof Reflect ? Reflect : null;
r3 = n3 && "function" == typeof n3.apply ? n3.apply : function(e4, t4, n4) {
return Function.prototype.apply.call(e4, t4, n4);
};
t3 = n3 && "function" == typeof n3.ownKeys ? n3.ownKeys : Object.getOwnPropertySymbols ? function(e4) {
return Object.getOwnPropertyNames(e4).concat(Object.getOwnPropertySymbols(e4));
} : function(e4) {
return Object.getOwnPropertyNames(e4);
};
i3 = Number.isNaN || function(e4) {
return e4 != e4;
};
e3 = o3, o3.EventEmitter = o3, o3.prototype._events = void 0, o3.prototype._eventsCount = 0, o3.prototype._maxListeners = void 0;
s3 = 10;
Object.defineProperty(o3, "defaultMaxListeners", { enumerable: true, get: function() {
return s3;
}, set: function(e4) {
if ("number" != typeof e4 || e4 < 0 || i3(e4))
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e4 + ".");
s3 = e4;
} }), o3.init = function() {
void 0 !== this._events && this._events !== Object.getPrototypeOf(this)._events || (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
}, o3.prototype.setMaxListeners = function(e4) {
if ("number" != typeof e4 || e4 < 0 || i3(e4))
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e4 + ".");
return this._maxListeners = e4, this;
}, o3.prototype.getMaxListeners = function() {
return f3(this);
}, o3.prototype.emit = function(e4) {
for (var t4 = [], n4 = 1; n4 < arguments.length; n4++)
t4.push(arguments[n4]);
var i4 = "error" === e4, o4 = this._events;
if (void 0 !== o4)
i4 = i4 && void 0 === o4.error;
else if (!i4)
return false;
if (i4) {
var s4;
if (t4.length > 0 && (s4 = t4[0]), s4 instanceof Error)
throw s4;
var u4 = new Error("Unhandled error." + (s4 ? " (" + s4.message + ")" : ""));
throw u4.context = s4, u4;
}
var f4 = o4[e4];
if (void 0 === f4)
return false;
if ("function" == typeof f4)
r3(f4, this, t4);
else {
var v6 = f4.length, a4 = c3(f4, v6);
for (n4 = 0; n4 < v6; ++n4)
r3(a4[n4], this, t4);
}
return true;
}, o3.prototype.addListener = function(e4, t4) {
return v3(this, e4, t4, false);
}, o3.prototype.on = o3.prototype.addListener, o3.prototype.prependListener = function(e4, t4) {
return v3(this, e4, t4, true);
}, o3.prototype.once = function(e4, t4) {
return u3(t4), this.on(e4, l3(this, e4, t4)), this;
}, o3.prototype.prependOnceListener = function(e4, t4) {
return u3(t4), this.prependListener(e4, l3(this, e4, t4)), this;
}, o3.prototype.removeListener = function(e4, t4) {
var n4, r4, i4, o4, s4;
if (u3(t4), void 0 === (r4 = this._events))
return this;
if (void 0 === (n4 = r4[e4]))
return this;
if (n4 === t4 || n4.listener === t4)
0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : (delete r4[e4], r4.removeListener && this.emit("removeListener", e4, n4.listener || t4));
else if ("function" != typeof n4) {
for (i4 = -1, o4 = n4.length - 1; o4 >= 0; o4--)
if (n4[o4] === t4 || n4[o4].listener === t4) {
s4 = n4[o4].listener, i4 = o4;
break;
}
if (i4 < 0)
return this;
0 === i4 ? n4.shift() : !function(e5, t5) {
for (; t5 + 1 < e5.length; t5++)
e5[t5] = e5[t5 + 1];
e5.pop();
}(n4, i4), 1 === n4.length && (r4[e4] = n4[0]), void 0 !== r4.removeListener && this.emit("removeListener", e4, s4 || t4);
}
return this;
}, o3.prototype.off = o3.prototype.removeListener, o3.prototype.removeAllListeners = function(e4) {
var t4, n4, r4;
if (void 0 === (n4 = this._events))
return this;
if (void 0 === n4.removeListener)
return 0 === arguments.length ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : void 0 !== n4[e4] && (0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : delete n4[e4]), this;
if (0 === arguments.length) {
var i4, o4 = Object.keys(n4);
for (r4 = 0; r4 < o4.length; ++r4)
"removeListener" !== (i4 = o4[r4]) && this.removeAllListeners(i4);
return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
}
if ("function" == typeof (t4 = n4[e4]))
this.removeListener(e4, t4);
else if (void 0 !== t4)
for (r4 = t4.length - 1; r4 >= 0; r4--)
this.removeListener(e4, t4[r4]);
return this;
}, o3.prototype.listeners = function(e4) {
return h3(this, e4, true);
}, o3.prototype.rawListeners = function(e4) {
return h3(this, e4, false);
}, o3.listenerCount = function(e4, t4) {
return "function" == typeof e4.listenerCount ? e4.listenerCount(t4) : p3.call(e4, t4);
}, o3.prototype.listenerCount = p3, o3.prototype.eventNames = function() {
return this._eventsCount > 0 ? t3(this._events) : [];
};
y2 = e3;
y2.EventEmitter;
y2.defaultMaxListeners;
y2.init;
y2.listenerCount;
y2.EventEmitter;
y2.defaultMaxListeners;
y2.init;
y2.listenerCount;
}
});
// node-modules-polyfills:events
var EventEmitter, defaultMaxListeners, init, listenerCount, on, once;
var init_events = __esm({
"node-modules-polyfills:events"() {
init_chunk_4bd36a8f();
init_chunk_4bd36a8f();
y2.once = function(emitter, event) {
return new Promise((resolve, reject) => {
function eventListener(...args) {
if (errorListener !== void 0) {
emitter.removeListener("error", errorListener);
}
resolve(args);
}
let errorListener;
if (event !== "error") {
errorListener = (err) => {
emitter.removeListener(name, eventListener);
reject(err);
};
emitter.once("error", errorListener);
}
emitter.once(event, eventListener);
});
};
y2.on = function(emitter, event) {
const unconsumedEventValues = [];
const unconsumedPromises = [];
let error = null;
let finished = false;
const iterator = {
async next() {
const value = unconsumedEventValues.shift();
if (value) {
return createIterResult(value, false);
}
if (error) {
const p4 = Promise.reject(error);
error = null;
return p4;
}
if (finished) {
return createIterResult(void 0, true);
}
return new Promise((resolve, reject) => unconsumedPromises.push({ resolve, reject }));
},
async return() {
emitter.removeListener(event, eventHandler);
emitter.removeListener("error", errorHandler);
finished = true;
for (const promise of unconsumedPromises) {
promise.resolve(createIterResult(void 0, true));
}
return createIterResult(void 0, true);
},
throw(err) {
error = err;
emitter.removeListener(event, eventHandler);
emitter.removeListener("error", errorHandler);
},
[Symbol.asyncIterator]() {
return this;
}
};
emitter.on(event, eventHandler);
emitter.on("error", errorHandler);
return iterator;
function eventHandler(...args) {
const promise = unconsumedPromises.shift();
if (promise) {
promise.resolve(createIterResult(args, false));
} else {
unconsumedEventValues.push(args);
}
}
function errorHandler(err) {
finished = true;
const toError = unconsumedPromises.shift();
if (toError) {
toError.reject(err);
} else {
error = err;
}
iterator.return();
}
};
({
EventEmitter,
defaultMaxListeners,
init,
listenerCount,
on,
once
} = y2);
}
});
// node-modules-polyfills-commonjs:events
var events_exports = {};
__export(events_exports, {
EventEmitter: () => EventEmitter,
defaultMaxListeners: () => defaultMaxListeners,
init: () => init,
listenerCount: () => listenerCount,
on: () => on,
once: () => once
});
var init_events2 = __esm({
"node-modules-polyfills-commonjs:events"() {
init_events();
}
});
// 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, name2) => {
if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
throw new ERR_INVALID_ARG_TYPE(name2, "AbortSignal", signal);
}
};
var validateFunction = (value, name2) => {
if (typeof value !== "function")
throw new ERR_INVALID_ARG_TYPE(name2, "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 i4 = 0; i4 < errors2.length; i4++) {
message += ` ${errors2[i4].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: (init_events2(), __toCommonJS(events_exports)).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 i4 = val2.length;
const start = val2[0] === "-" ? 1 : 0;
for (; i4 >= start + 4; i4 -= 3) {
res = `_${val2.slice(i4 - 3, i4)}${res}`;
}
return `${val2.slice(0, i4)}${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",
(name2, expected, actual) => {
assert(typeof name2 === "string", "'name' must be a string");
if (!Array.isArray(expected)) {
expected = [expected];
}
let msg = "The ";
if (name2.endsWith(" argument")) {
msg += `${name2} `;
} else {
msg += `"${name2}" ${name2.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",
(name2, value, reason = "is invalid") => {
let inspected = inspect(value);
if (inspected.length > 128) {
inspected = inspected.slice(0, 128) + "...";
}
const type = name2.includes(".") ? "property" : "argument";
return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
},
TypeError
);
E2(
"ERR_INVALID_RETURN_VALUE",
(input, name2, 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 "${name2}" 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((a4) => `"${a4}"`).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, name2, def) {
if (typeof value === "undefined") {
value = def;
}
if (typeof value === "string") {
if (RegExpPrototypeExec(octalReg, value) === null) {
throw new ERR_INVALID_ARG_VALUE(name2, value, modeDesc);
}
value = NumberParseInt(value, 8);
}
validateUint32(value, name2);
return value;
}
var validateInteger = hideStackFrames((value, name2, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {
if (typeof value !== "number")
throw new ERR_INVALID_ARG_TYPE2(name2, "number", value);
if (!NumberIsInteger(value))
throw new ERR_OUT_OF_RANGE(name2, "an integer", value);
if (value < min || value > max)
throw new ERR_OUT_OF_RANGE(name2, `>= ${min} && <= ${max}`, value);
});
var validateInt32 = hideStackFrames((value, name2, min = -2147483648, max = 2147483647) => {
if (typeof value !== "number") {
throw new ERR_INVALID_ARG_TYPE2(name2, "number", value);
}
if (!NumberIsInteger(value)) {
throw new ERR_OUT_OF_RANGE(name2, "an integer", value);
}
if (value < min || value > max) {
throw new ERR_OUT_OF_RANGE(name2, `>= ${min} && <= ${max}`, value);
}
});
var validateUint32 = hideStackFrames((value, name2, positive = false) => {
if (typeof value !== "number") {
throw new ERR_INVALID_ARG_TYPE2(name2, "number", value);
}
if (!NumberIsInteger(value)) {
throw new ERR_OUT_OF_RANGE(name2, "an integer", value);
}
const min = positive ? 1 : 0;
const max = 4294967295;
if (value < min || value > max) {
throw new ERR_OUT_OF_RANGE(name2, `>= ${min} && <= ${max}`, value);
}
});
function validateString(value, name2) {
if (typeof value !== "string")
throw new ERR_INVALID_ARG_TYPE2(name2, "string", value);
}
function validateNumber(value, name2, min = void 0, max) {
if (typeof value !== "number")
throw new ERR_INVALID_ARG_TYPE2(name2, "number", value);
if (min != null && value < min || max != null && value > max || (min != null || max != null) && NumberIsNaN(value)) {
throw new ERR_OUT_OF_RANGE(
name2,
`${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`,
value
);
}
}
var validateOneOf = hideStackFrames((value, name2, oneOf) => {
if (!ArrayPrototypeIncludes(oneOf, value)) {
const allowed = ArrayPrototypeJoin(
ArrayPrototypeMap(oneOf, (v6) => typeof v6 === "string" ? `'${v6}'` : String2(v6)),
", "
);
const reason = "must be one of: " + allowed;
throw new ERR_INVALID_ARG_VALUE(name2, value, reason);
}
});
function validateBoolean(value, name2) {
if (typeof value !== "boolean")
throw new ERR_INVALID_ARG_TYPE2(name2, "boolean", value);
}
function getOwnPropertyValueOrDefault(options, key, defaultValue) {
return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key];
}
var validateObject = hideStackFrames((value, name2, 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(name2, "Object", value);
}
});
var validateDictionary = hideStackFrames((value, name2) => {
if (value != null && typeof value !== "object" && typeof value !== "function") {
throw new ERR_INVALID_ARG_TYPE2(name2, "a dictionary", value);
}
});
var validateArray = hideStackFrames((value, name2, minLength = 0) => {
if (!ArrayIsArray(value)) {
throw new ERR_INVALID_ARG_TYPE2(name2, "Array", value);
}
if (value.length < minLength) {
const reason = `must be longer than ${minLength}`;
throw new ERR_INVALID_ARG_VALUE(name2, value, reason);
}
});
function validateStringArray(value, name2) {
validateArray(value, name2);
for (let i4 = 0; i4 < value.length; i4++) {
validateString(value[i4], `${name2}[${i4}]`);
}
}
function validateBooleanArray(value, name2) {
validateArray(value, name2);
for (let i4 = 0; i4 < value.length; i4++) {
validateBoolean(value[i4], `${name2}[${i4}]`);
}
}
function validateAbortSignalArray(value, name2) {
validateArray(value, name2);
for (let i4 = 0; i4 < value.length; i4++) {
const signal = value[i4];
const indexedName = `${name2}[${i4}]`;
if (signal == null) {
throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal);
}
validateAbortSignal(signal, indexedName);
}
}
function validateSignalName(signal, name2 = "signal") {
validateString(signal, name2);
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, name2 = "buffer") => {
if (!isArrayBufferView(buffer)) {
throw new ERR_INVALID_ARG_TYPE2(name2, ["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, name2 = "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(name2, port, allowZero);
}
return port | 0;
}
var validateAbortSignal = hideStackFrames((signal, name2) => {
if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
throw new ERR_INVALID_ARG_TYPE2(name2, "AbortSignal", signal);
}
});
var validateFunction = hideStackFrames((value, name2) => {
if (typeof value !== "function")
throw new ERR_INVALID_ARG_TYPE2(name2, "Function", value);
});
var validatePlainFunction = hideStackFrames((value, name2) => {
if (typeof value !== "function" || isAsyncFunction2(value))
throw new ERR_INVALID_ARG_TYPE2(name2, "Function", value);
});
var validateUndefined = hideStackFrames((value, name2) => {
if (value !== void 0)
throw new ERR_INVALID_ARG_TYPE2(name2, "undefined", value);
});
function validateUnion(value, name2, union) {
if (!ArrayPrototypeIncludes(union, value)) {
throw new ERR_INVALID_ARG_TYPE2(name2, `('${ArrayPrototypeJoin(union, "|")}')`, value);
}
}
var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
function validateLinkHeaderFormat(value, name2) {
if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) {
throw new ERR_INVALID_ARG_VALUE(
name2,
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 i4 = 0; i4 < hintsLength; i4++) {
const link = hints[i4];
validateLinkHeaderFormat(link, "hints");
result += link;
if (i4 !== 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 (e4) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === "function") {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e4) {
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 (e4) {
try {
return cachedSetTimeout.call(null, fun, 0);
} catch (e5) {
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 (e4) {
try {
return cachedClearTimeout.call(null, marker);
} catch (e5) {
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 i4 = 1; i4 < arguments.length; i4++) {
args[i4 - 1] = arguments[i4];
}
}
queue2.push(new Item(fun, args));
if (queue2.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function() {
this.fun.apply(null, this.array);
};
process2.title = "browser";
process2.browser = true;
process2.env = {};
process2.argv = [];
process2.version = "";
process2.versions = {};
function noop() {
}
process2.on = noop;
process2.addListener = noop;
process2.once = noop;
process2.off = noop;
process2.removeListener = noop;
process2.removeAllListeners = noop;
process2.emit = noop;
process2.prependListener = noop;
process2.prependOnceListener = noop;
process2.listeners = function(name2) {
return [];
};
process2.binding = function(name2) {
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, strict = false) {
var _obj$_readableState;
return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || 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, strict) {
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 || strict === 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, strict) {
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 || strict === 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: once2 } = 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 = once2(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 = once2((...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 = once2((...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 } = (init_events2(), __toCommonJS(events_exports));
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, name2) => {
if (typeof signal !== "object" || !("aborted" in signal)) {
throw new ERR_INVALID_ARG_TYPE2(name2, "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(v6) {
const entry = {
data: v6,
next: null
};
if (this.length > 0)
this.tail.next = entry;
else
this.head = entry;
this.tail = entry;
++this.length;
}
unshift(v6) {
const entry = {
data: v6,
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 p4 = this.head;
let ret = "" + p4.data;
while ((p4 = p4.next) !== null)
ret += s4 + p4.data;
return ret;
}
concat(n4) {
if (this.length === 0)
return Buffer2.alloc(0);
const ret = Buffer2.allocUnsafe(n4 >>> 0);
let p4 = this.head;
let i4 = 0;
while (p4) {
TypedArrayPrototypeSet(ret, p4.data, i4);
i4 += p4.data.length;
p4 = p4.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 p4 = this.head; p4; p4 = p4.next) {
yield p4.data;
}
}
// Consumes a specified amount of characters from the buffered data.
_getString(n4) {
let ret = "";
let p4 = this.head;
let c5 = 0;
do {
const str2 = p4.data;
if (n4 > str2.length) {
ret += str2;
n4 -= str2.length;
} else {
if (n4 === str2.length) {
ret += str2;
++c5;
if (p4.next)
this.head = p4.next;
else
this.head = this.tail = null;
} else {
ret += StringPrototypeSlice(str2, 0, n4);
this.head = p4;
p4.data = StringPrototypeSlice(str2, n4);
}
break;
}
++c5;
} while ((p4 = p4.next) !== null);
this.length -= c5;
return ret;
}
// Consumes a specified amount of bytes from the buffered data.
_getBuffer(n4) {
const ret = Buffer2.allocUnsafe(n4);
const retLen = n4;
let p4 = this.head;
let c5 = 0;
do {
const buf = p4.data;
if (n4 > buf.length) {
TypedArrayPrototypeSet(ret, buf, retLen - n4);
n4 -= buf.length;
} else {
if (n4 === buf.length) {
TypedArrayPrototypeSet(ret, buf, retLen - n4);
++c5;
if (p4.next)
this.head = p4.next;
else
this.head = this.tail = null;
} else {
TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n4), retLen - n4);
this.head = p4;
p4.data = buf.slice(n4);
}
break;
}
++c5;
} while ((p4 = p4.next) !== null);
this.length -= c5;
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 name2 = isDuplex ? `options.${duplexKey}` : "options.highWaterMark";
throw new ERR_INVALID_ARG_VALUE(name2, 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(size, fill, encoding) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
var buf = Buffer2(size);
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(size) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
return Buffer2(size);
};
SafeBuffer.allocUnsafeSlow = function(size) {
if (typeof size !== "number") {
throw new TypeError("Argument must be a number");
}
return buffer.SlowBuffer(size);
};
}
});
// 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 i4;
if (this.lastNeed) {
r4 = this.fillLast(buf);
if (r4 === void 0)
return "";
i4 = this.lastNeed;
this.lastNeed = 0;
} else {
i4 = 0;
}
if (i4 < buf.length)
return r4 ? r4 + this.text(buf, i4) : this.text(buf, i4);
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, i4) {
var j3 = buf.length - 1;
if (j3 < i4)
return 0;
var nb = utf8CheckByte(buf[j3]);
if (nb >= 0) {
if (nb > 0)
self2.lastNeed = nb - 1;
return nb;
}
if (--j3 < i4 || nb === -2)
return 0;
nb = utf8CheckByte(buf[j3]);
if (nb >= 0) {
if (nb > 0)
self2.lastNeed = nb - 2;
return nb;
}
if (--j3 < i4 || 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, p4) {
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 p4 = this.lastTotal - this.lastNeed;
var r4 = utf8CheckExtraBytes(this, buf, p4);
if (r4 !== void 0)
return r4;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p4, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p4, 0, buf.length);
this.lastNeed -= buf.length;
}
function utf8Text(buf, i4) {
var total = utf8CheckIncomplete(this, buf, i4);
if (!this.lastNeed)
return buf.toString("utf8", i4);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString("utf8", i4, end);
}
function utf8End(buf) {
var r4 = buf && buf.length ? this.write(buf) : "";
if (this.lastNeed)
return r4 + "\uFFFD";
return r4;
}
function utf16Text(buf, i4) {
if ((buf.length - i4) % 2 === 0) {
var r4 = buf.toString("utf16le", i4);
if (r4) {
var c5 = r4.charCodeAt(r4.length - 1);
if (c5 >= 55296 && c5 <= 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", i4, 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, i4) {
var n4 = (buf.length - i4) % 3;
if (n4 === 0)
return buf.toString("base64", i4);
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", i4, 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
(e4) => process2.nextTick(cb, e4 || 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 } = (init_events2(), __toCommonJS(events_exports));
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 = fromList(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 i4 = 0; i4 < dests.length; i4++)
dests[i4].emit("unpipe", this, {
hasUnpiped: false
});
return this;
}
const index = ArrayPrototypeIndexOf(state.pipes, dest);
if (index === -1)
return this;
state.pipes.splice(index, 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 i4 = streamKeys[j3];
if (this[i4] === void 0 && typeof stream[i4] === "function") {
this[i4] = stream[i4].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 = fromList;
function fromList(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 } = (init_events2(), __toCommonJS(events_exports));
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: count3, cb }) {
state.afterWriteTickInfo = null;
return afterWrite(stream, state, count3, cb);
}
function afterWrite(stream, state, count3, cb) {
const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain;
if (needDrain) {
state.needDrain = false;
stream.emit("drain");
}
while (count3-- > 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 i4 = 0; i4 < onfinishCallbacks.length; i4++) {
var _state$errored2;
onfinishCallbacks[i4](
(_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 i4 = bufferedIndex;
state.bufferProcessing = true;
if (bufferedLength > 1 && stream._writev) {
state.pendingcb -= bufferedLength - 1;
const callback = state.allNoop ? nop : (err) => {
for (let n4 = i4; n4 < buffered.length; ++n4) {
buffered[n4].callback(err);
}
};
const chunks = state.allNoop && i4 === 0 ? buffered : ArrayPrototypeSlice(buffered, i4);
chunks.allBuffers = state.allBuffers;
doWrite(stream, state, true, state.length, chunks, "", callback);
resetBuffer(state);
} else {
do {
const { chunk, encoding, callback } = buffered[i4];
buffered[i4++] = null;
const len = objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, callback);
} while (i4 < buffered.length && !state.writing);
if (i4 === buffered.length) {
resetBuffer(state);
} else if (i4 > 256) {
buffered.splice(0, i4);
state.bufferedIndex = 0;
} else {
state.bufferedIndex = i4;
}
}
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 i4 = 0; i4 < onfinishCallbacks.length; i4++) {
onfinishCallbacks[i4](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 i4 = 0; i4 < onfinishCallbacks.length; i4++) {
onfinishCallbacks[i4]();
}
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, name2) {
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", name2, 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(
name2,
[
"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 i4 = 0; i4 < keys.length; i4++) {
const method = keys[i4];
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: once2 } = 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, once2(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 i4 = 0; i4 < streams.length; i4++) {
const stream = streams[i4];
const reading = i4 < streams.length - 1;
const writing = i4 > 0;
const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false;
const isLastStream = i4 === 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 (i4 === 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[${i4 - 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 index = 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 [index++, 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(reducer, initialValue, options) {
var _options$signal2;
if (typeof reducer !== "function") {
throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer);
}
if (options != null) {
validateObject(options, "options");
}
if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
validateAbortSignal(options.signal, "options.signal");
}
let hasInitialValue = 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 (!hasInitialValue) {
initialValue = value;
hasInitialValue = true;
} else {
initialValue = await reducer(initialValue, value, {
signal
});
}
}
if (!gotAnyItemFromStream && !hasInitialValue) {
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/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 (sym 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 = 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/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 max = Math.max;
var funcType = "[object Function]";
var concatty = function concatty2(a4, b3) {
var arr2 = [];
for (var i4 = 0; i4 < a4.length; i4 += 1) {
arr2[i4] = a4[i4];
}
for (var j3 = 0; j3 < b3.length; j3 += 1) {
arr2[j3 + a4.length] = b3[j3];
}
return arr2;
};
var slicy = function slicy2(arrLike, offset) {
var arr2 = [];
for (var i4 = offset || 0, j3 = 0; i4 < arrLike.length; i4 += 1, j3 += 1) {
arr2[j3] = arrLike[i4];
}
return arr2;
};
var joiny = function(arr2, joiner) {
var str2 = "";
for (var i4 = 0; i4 < arr2.length; i4 += 1) {
str2 += arr2[i4];
if (i4 + 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 = max(0, target.length - args.length);
var boundArgs = [];
for (var i4 = 0; i4 < boundLength; i4++) {
boundArgs[i4] = "$" + i4;
}
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/has/src/index.js
var require_src = __commonJS({
"node_modules/has/src/index.js"(exports, module2) {
"use strict";
var bind2 = require_function_bind();
module2.exports = bind2.call(Function.call, Object.prototype.hasOwnProperty);
}
});
// node_modules/get-intrinsic/index.js
var require_get_intrinsic = __commonJS({
"node_modules/get-intrinsic/index.js"(exports, module2) {
"use strict";
var undefined2;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
var getEvalledConstructor = function(expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
} catch (e4) {
}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, "");
} catch (e4) {
$gOPD = null;
}
}
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 = Object.getPrototypeOf || function(x2) {
return x2.__proto__;
};
var needsEval = {};
var TypedArray = typeof Uint8Array === "undefined" ? undefined2 : getProto(Uint8Array);
var INTRINSICS = {
"%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
"%Array%": Array,
"%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
"%ArrayIteratorPrototype%": hasSymbols ? 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([][Symbol.iterator]())) : undefined2,
"%JSON%": typeof JSON === "object" ? JSON : undefined2,
"%Map%": typeof Map === "undefined" ? undefined2 : Map,
"%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
"%Math%": Math,
"%Number%": Number,
"%Object%": Object,
"%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 ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
"%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
"%String%": String,
"%StringIteratorPrototype%": hasSymbols ? 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
};
try {
null.error;
} catch (e4) {
errorProto = getProto(getProto(e4));
INTRINSICS["%Error.prototype%"] = errorProto;
}
var errorProto;
var doEval = function doEval2(name2) {
var value;
if (name2 === "%AsyncFunction%") {
value = getEvalledConstructor("async function () {}");
} else if (name2 === "%GeneratorFunction%") {
value = getEvalledConstructor("function* () {}");
} else if (name2 === "%AsyncGeneratorFunction%") {
value = getEvalledConstructor("async function* () {}");
} else if (name2 === "%AsyncGenerator%") {
var fn = doEval2("%AsyncGeneratorFunction%");
if (fn) {
value = fn.prototype;
}
} else if (name2 === "%AsyncIteratorPrototype%") {
var gen = doEval2("%AsyncGenerator%");
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name2] = value;
return value;
};
var LEGACY_ALIASES = {
"%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_src();
var $concat = bind2.call(Function.call, Array.prototype.concat);
var $spliceApply = bind2.call(Function.apply, Array.prototype.splice);
var $replace = bind2.call(Function.call, String.prototype.replace);
var $strSlice = bind2.call(Function.call, String.prototype.slice);
var $exec = bind2.call(Function.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(match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
});
return result;
};
var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) {
var intrinsicName = name2;
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 " + name2 + " exists, but is not available. Please file an issue!");
}
return {
alias,
name: intrinsicName,
value
};
}
throw new $SyntaxError("intrinsic " + name2 + " does not exist!");
};
module2.exports = function GetIntrinsic(name2, allowMissing) {
if (typeof name2 !== "string" || name2.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(/^%?[^%]*%?$/, name2) === null) {
throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
}
var parts = stringToPath(name2);
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 i4 = 1, isOwn = true; i4 < parts.length; i4 += 1) {
var part = parts[i4];
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 " + name2 + " exists, but the property is not available.");
}
return void 0;
}
if ($gOPD && i4 + 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-bind/index.js
var require_call_bind = __commonJS({
"node_modules/call-bind/index.js"(exports, module2) {
"use strict";
var bind2 = require_function_bind();
var GetIntrinsic = require_get_intrinsic();
var $apply = GetIntrinsic("%Function.prototype.apply%");
var $call = GetIntrinsic("%Function.prototype.call%");
var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind2.call($call, $apply);
var $gOPD = GetIntrinsic("%Object.getOwnPropertyDescriptor%", true);
var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
var $max = GetIntrinsic("%Math.max%");
if ($defineProperty) {
try {
$defineProperty({}, "a", { value: 1 });
} catch (e4) {
$defineProperty = null;
}
}
module2.exports = function callBind(originalFunction) {
var func = $reflectApply(bind2, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, "length");
if (desc.configurable) {
$defineProperty(
func,
"length",
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind2() {
return $reflectApply(bind2, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module2.exports, "apply", { value: applyBind });
} else {
module2.exports.apply = applyBind;
}
}
});
// node_modules/call-bind/callBound.js
var require_callBound = __commonJS({
"node_modules/call-bind/callBound.js"(exports, module2) {
"use strict";
var GetIntrinsic = require_get_intrinsic();
var callBind = require_call_bind();
var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf"));
module2.exports = function callBoundIntrinsic(name2, allowMissing) {
var intrinsic = GetIntrinsic(name2, !!allowMissing);
if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
}
});
// (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 int = num < 0 ? -$floor(-num) : $floor(num);
if (int !== num) {
var intStr = String(int);
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;
module2.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has2(opts, "quoteStyle") && (opts.quoteStyle !== "single" && opts.quoteStyle !== "double")) {
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 name2 = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return "[Function" + (name2 ? ": " + name2 : " (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 (isElement(obj)) {
var s4 = "<" + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i4 = 0; i4 < attrs.length; i4++) {
s4 += " " + attrs[i4].name + "=" + wrapQuotes(quote(attrs[i4].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 (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(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 quoteChar = (opts.quoteStyle || defaultStyle) === "double" ? '"' : "'";
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 isDate(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 isString(obj) {
return toStr(obj) === "[object String]" && (!toStringTag || !(typeof obj === "object" && toStringTag in obj));
}
function isNumber(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 (e4) {
}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== "object" || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e4) {
}
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(f4) {
if (f4.name) {
return f4.name;
}
var m3 = $match.call(functionToString.call(f4), /^function\s*([\w$]+)/);
if (m3) {
return m3[1];
}
return null;
}
function indexOf(xs, x2) {
if (xs.indexOf) {
return xs.indexOf(x2);
}
for (var i4 = 0, l4 = xs.length; i4 < l4; i4++) {
if (xs[i4] === x2) {
return i4;
}
}
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 (e4) {
}
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 (e4) {
}
return false;
}
function isWeakRef(x2) {
if (!weakRefDeref || !x2 || typeof x2 !== "object") {
return false;
}
try {
weakRefDeref.call(x2);
return true;
} catch (e4) {
}
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 (e4) {
}
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 (e4) {
}
return false;
}
function isElement(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 s4 = $replace.call($replace.call(str2, /(['\\])/g, "\\$1"), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s4, "single", opts);
}
function lowbyte(c5) {
var n4 = c5.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, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
return type + " (" + size + ") {" + joinedEntries + "}";
}
function singleLineValues(xs) {
for (var i4 = 0; i4 < xs.length; i4++) {
if (indexOf(xs[i4], "\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 i4 = 0; i4 < obj.length; i4++) {
xs[i4] = has2(obj, i4) ? inspect(obj[i4], 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/index.js
var require_side_channel = __commonJS({
"node_modules/side-channel/index.js"(exports, module2) {
"use strict";
var GetIntrinsic = require_get_intrinsic();
var callBound = require_callBound();
var inspect = require_object_inspect();
var $TypeError = GetIntrinsic("%TypeError%");
var $WeakMap = GetIntrinsic("%WeakMap%", true);
var $Map = GetIntrinsic("%Map%", true);
var $weakMapGet = callBound("WeakMap.prototype.get", true);
var $weakMapSet = callBound("WeakMap.prototype.set", true);
var $weakMapHas = callBound("WeakMap.prototype.has", true);
var $mapGet = callBound("Map.prototype.get", true);
var $mapSet = callBound("Map.prototype.set", true);
var $mapHas = callBound("Map.prototype.has", true);
var listGetNode = function(list, key) {
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
curr.next = list.next;
list.next = curr;
return curr;
}
}
};
var listGet = function(objects, key) {
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 = {
// eslint-disable-line no-param-reassign
key,
next: objects.next,
value
};
}
};
var listHas = function(objects, key) {
return !!listGetNode(objects, key);
};
module2.exports = function getSideChannel() {
var $wm;
var $m;
var $o;
var channel = {
assert: function(key) {
if (!channel.has(key)) {
throw new $TypeError("Side channel does not contain " + inspect(key));
}
},
get: function(key) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if ($wm) {
return $weakMapGet($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapGet($m, key);
}
} else {
if ($o) {
return listGet($o, key);
}
}
},
has: function(key) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if ($wm) {
return $weakMapHas($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapHas($m, key);
}
} else {
if ($o) {
return listHas($o, key);
}
}
return false;
},
set: function(key, value) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if (!$wm) {
$wm = new $WeakMap();
}
$weakMapSet($wm, key, value);
} else if ($Map) {
if (!$m) {
$m = new $Map();
}
$mapSet($m, key, value);
} else {
if (!$o) {
$o = { key: {}, next: null };
}
listSet($o, 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 i4 = 0; i4 < 256; ++i4) {
array.push("%" + ((i4 < 16 ? "0" : "") + i4.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 i4 = 0; i4 < source.length; ++i4) {
if (typeof source[i4] !== "undefined") {
obj[i4] = source[i4];
}
}
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, i4) {
if (has2.call(target, i4)) {
var targetItem = target[i4];
if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
target[i4] = merge2(targetItem, item, options);
} else {
target.push(item);
}
} else {
target[i4] = 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 (e4) {
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 i4 = 0; i4 < string.length; ++i4) {
var c5 = string.charCodeAt(i4);
if (c5 === 45 || c5 === 46 || c5 === 95 || c5 === 126 || c5 >= 48 && c5 <= 57 || c5 >= 65 && c5 <= 90 || c5 >= 97 && c5 <= 122 || format === formats.RFC1738 && (c5 === 40 || c5 === 41)) {
out += string.charAt(i4);
continue;
}
if (c5 < 128) {
out = out + hexTable[c5];
continue;
}
if (c5 < 2048) {
out = out + (hexTable[192 | c5 >> 6] + hexTable[128 | c5 & 63]);
continue;
}
if (c5 < 55296 || c5 >= 57344) {
out = out + (hexTable[224 | c5 >> 12] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63]);
continue;
}
i4 += 1;
c5 = 65536 + ((c5 & 1023) << 10 | string.charCodeAt(i4) & 1023);
out += hexTable[240 | c5 >> 18] + hexTable[128 | c5 >> 12 & 63] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63];
}
return out;
};
var compact = function compact2(value) {
var queue2 = [{ obj: { o: value }, prop: "o" }];
var refs = [];
for (var i4 = 0; i4 < queue2.length; ++i4) {
var item = queue2[i4];
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(a4, b3) {
return [].concat(a4, b3);
};
var maybeMap = function maybeMap2(val2, fn) {
if (isArray2(val2)) {
var mapped = [];
for (var i4 = 0; i4 < val2.length; i4 += 1) {
mapped.push(fn(val2[i4]));
}
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(v6) {
return typeof v6 === "string" || typeof v6 === "number" || typeof v6 === "boolean" || typeof v6 === "symbol" || typeof v6 === "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 i4 = 0; i4 < objKeys.length; ++i4) {
var key = objKeys[i4];
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 i4;
var charset = options.charset;
if (options.charsetSentinel) {
for (i4 = 0; i4 < parts.length; ++i4) {
if (parts[i4].indexOf("utf8=") === 0) {
if (parts[i4] === charsetSentinel) {
charset = "utf-8";
} else if (parts[i4] === isoSentinel) {
charset = "iso-8859-1";
}
skipIndex = i4;
i4 = parts.length;
}
}
}
for (i4 = 0; i4 < parts.length; ++i4) {
if (i4 === skipIndex) {
continue;
}
var part = parts[i4];
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 i4 = chain.length - 1; i4 >= 0; --i4) {
var obj;
var root2 = chain[i4];
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 index = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === "") {
obj = { 0: leaf };
} else if (!isNaN(index) && root2 !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) {
obj = [];
obj[index] = 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 i4 = 0;
while (options.depth > 0 && (segment = child.exec(key)) !== null && i4 < options.depth) {
i4 += 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 i4 = 0; i4 < keys.length; ++i4) {
var key = keys[i4];
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 parse3 = require_parse2();
var formats = require_formats();
module2.exports = {
formats,
parse: parse3,
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 isNode3 = 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 (isNode3) {
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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) => __awaiter5(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", () => __awaiter5(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) => __awaiter5(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) => __awaiter5(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", () => __awaiter5(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) => __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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: () => __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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: () => __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values === "function" ? __values(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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) => __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(this, void 0, void 0, function* () {
let response = yield requestFn();
for (let i4 = 0; i4 < maxRetries; ++i4) {
if ([408, 409, 429].includes(response.status) || response.status >= 500) {
const delay = Math.min(INITIAL_RETRY_DELAY * Math.pow(2, i4), 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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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)(() => __awaiter5(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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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) => __awaiter5(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(a4) {
var tab = {};
a4.forEach(function(c5, i4) {
return tab[c5] = i4;
});
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 i4 = 0; i4 < bin.length; ) {
if ((c0 = bin.charCodeAt(i4++)) > 255 || (c1 = bin.charCodeAt(i4++)) > 255 || (c22 = bin.charCodeAt(i4++)) > 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 i4 = 0, l4 = u8a.length; i4 < l4; i4 += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i4, i4 + 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(c5) {
if (c5.length < 2) {
var cc = c5.charCodeAt(0);
return cc < 128 ? c5 : 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 + (c5.charCodeAt(0) - 55296) * 1024 + (c5.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(u4) {
return u4.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), offset = cp - 65536;
return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 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 i4 = 0; i4 < asc.length; ) {
u24 = b64tab[asc.charAt(i4++)] << 18 | b64tab[asc.charAt(i4++)] << 12 | (r1 = b64tab[asc.charAt(i4++)]) << 6 | (r22 = b64tab[asc.charAt(i4++)]);
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(a4) {
return _U8Afrom(Buffer.from(a4, "base64"));
} : function(a4) {
return _U8Afrom(_atob(a4), function(c5) {
return c5.charCodeAt(0);
});
};
var toUint8Array2 = function(a4) {
return _toUint8Array(_unURI(a4));
};
var _decode = _hasBuffer ? function(a4) {
return Buffer.from(a4, "base64").toString("utf8");
} : _TD ? function(a4) {
return _TD.decode(_toUint8Array(a4));
} : function(a4) {
return btou(_atob(a4));
};
var _unURI = function(a4) {
return _tidyB64(a4.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(v6) {
return {
value: v6,
enumerable: false,
writable: true,
configurable: true
};
};
var extendString = function() {
var _add = function(name2, body) {
return Object.defineProperty(String.prototype, name2, _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(name2, body) {
return Object.defineProperty(Uint8Array.prototype, name2, _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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values === "function" ? __values(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, done: d3 });
}, reject);
}
};
var __await6 = exports && exports.__await || function(v6) {
return this instanceof __await6 ? (this.v = v6, this) : new __await6(v6);
};
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 || []), i4, q3 = [];
return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function verb(n4) {
if (g4[n4])
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), 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: parse3, eventShape, signal }) {
this.controller = new AbortController();
this.stream = stream;
this.parse = parse3;
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 __awaiter5(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 (e4) {
reader.releaseLock();
throw e4;
}
});
},
return() {
return __awaiter5(this, void 0, void 0, function* () {
const cancelPromise = reader.cancel();
reader.releaseLock();
yield cancelPromise;
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 __defProp5 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __export2 = (target, all) => {
for (var name2 in all)
__defProp5(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps2 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp3.call(to, key) && key !== except)
__defProp5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps2(__defProp5({}, "__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 __defProp5 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
var __export2 = (target, all) => {
for (var name2 in all)
__defProp5(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps2 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames2(from))
if (!__hasOwnProp3.call(to, key) && key !== except)
__defProp5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS2 = (mod) => __copyProps2(__defProp5({}, "__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 offset = 0;
while (offset < value.byteLength) {
const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE);
const buffer = value.buffer.slice(offset, offset + size);
offset += 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 size = 16;
let res = "";
while (size--) {
res += alphabet[Math.random() * alphabet.length << 0];
}
return res;
}
var normalizeValue2 = (value) => String(value).replace(/\r|\n/g, (match, i4, str2) => {
if (match === "\r" && str2[i4 + 1] !== "\n" || match === "\n" && str2[i4 - 1] !== "\r") {
return "\r\n";
}
return match;
});
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 [name2, value] of Object.entries(target)) {
if (prop.toLowerCase() === name2.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 = (name2) => String(name2).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 [name2, raw] of __privateGet(this, _form)) {
const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode(
normalizeValue2(raw)
);
yield __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name2, 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(name2, value) {
let header = "";
header += `${__privateGet(this, _DASHES)}${this.boundary}${__privateGet(this, _CRLF)}`;
header += `Content-Disposition: form-data; name="${escapeName(name2)}"`;
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 size = isFile(value) ? value.size : value.byteLength;
if (size != null && !isNaN(size)) {
header += `${__privateGet(this, _CRLF)}Content-Length: ${size}`;
}
}
return __privateGet(this, _encoder).encode(`${header}${__privateGet(this, _CRLF).repeat(2)}`);
};
_getContentLength = /* @__PURE__ */ new WeakSet();
getContentLength_fn = function() {
let length = 0;
for (const [name2, raw] of __privateGet(this, _form)) {
const value = isFile(raw) ? raw : __privateGet(this, _encoder).encode(
normalizeValue2(raw)
);
const size = isFile(value) ? value.size : value.byteLength;
if (size == null || isNaN(size)) {
return void 0;
}
length += __privateMethod(this, _getFieldHeader, getFieldHeader_fn).call(this, name2, value).byteLength;
length += size;
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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, index) => {
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 : [], `[${index}]`] }));
}),
json: (parsed, opts) => validateAndTransformArray(parsed, (item, index) => {
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 : [], `[${index}]`] }));
}),
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, index) => transformItem(item, index));
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 [index, 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 ${index}] ${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 __rest5 = exports && exports.__rest || function(s4, e4) {
var t4 = {};
for (var p4 in s4)
if (Object.prototype.hasOwnProperty.call(s4, p4) && e4.indexOf(p4) < 0)
t4[p4] = s4[p4];
if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
for (var i4 = 0, p4 = Object.getOwnPropertySymbols(s4); i4 < p4.length; i4++) {
if (e4.indexOf(p4[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p4[i4]))
t4[p4[i4]] = s4[p4[i4]];
}
return t4;
};
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 = __rest5(_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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values === "function" ? __values(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, done: d3 });
}, reject);
}
};
var __await6 = exports && exports.__await || function(v6) {
return this instanceof __await6 ? (this.v = v6, this) : new __await6(v6);
};
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 || []), i4, q3 = [];
return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function verb(n4) {
if (g4[n4])
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), 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 (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
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 (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
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 (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return yield __await6(void 0);
throw e4;
} 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 (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return yield __await6(void 0);
throw e4;
} 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 __awaiter5(this, void 0, void 0, function* () {
iter = self2[Symbol.asyncIterator]();
});
},
pull(ctrl) {
return __awaiter5(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 __awaiter5(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 i4 = 0; i4 < buffer.length - 2; i4++) {
if (buffer[i4] === newline && buffer[i4 + 1] === newline) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === carriage) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === newline && i4 + 3 < buffer.length && buffer[i4 + 2] === carriage && buffer[i4 + 3] === newline) {
return i4 + 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 index = str2.indexOf(delimiter);
if (index !== -1) {
return [str2.substring(0, index), delimiter, str2.substring(index + delimiter.length)];
}
return [str2, "", ""];
}
function readableStreamAsyncIterable4(stream) {
if (stream[Symbol.asyncIterator])
return stream;
const reader = stream.getReader();
return {
next() {
return __awaiter5(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 (e4) {
reader.releaseLock();
throw e4;
}
});
},
return() {
return __awaiter5(this, void 0, void 0, function* () {
const cancelPromise = reader.cancel();
reader.releaseLock();
yield cancelPromise;
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client9 = __commonJS({
"node_modules/cohere-ai/serialization/resources/v2/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types7(), exports);
__exportStar5(require_client9(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client10 = __commonJS({
"node_modules/cohere-ai/serialization/resources/embedJobs/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types8(), exports);
__exportStar5(require_client10(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client11 = __commonJS({
"node_modules/cohere-ai/serialization/resources/datasets/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_types9(), exports);
__exportStar5(require_client11(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client12 = __commonJS({
"node_modules/cohere-ai/serialization/resources/finetuning/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_resources3(), exports);
__exportStar5(require_client12(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client13 = __commonJS({
"node_modules/cohere-ai/serialization/resources/connectors/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_client13(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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_client14 = __commonJS({
"node_modules/cohere-ai/serialization/client/index.js"(exports) {
"use strict";
var __createBinding5 = exports && exports.__createBinding || (Object.create ? function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __exportStar5 = exports && exports.__exportStar || function(m3, exports2) {
for (var p4 in m3)
if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4))
__createBinding5(exports2, m3, p4);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar5(require_resources4(), exports);
__exportStar5(require_types11(), exports);
__exportStar5(require_client14(), 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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(o4) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m3 = o4[Symbol.asyncIterator], i4;
return m3 ? m3.call(o4) : (o4 = typeof __values === "function" ? __values(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4);
function verb(n4) {
i4[n4] = o4[n4] && function(v6) {
return new Promise(function(resolve, reject) {
v6 = o4[n4](v6), settle(resolve, reject, v6.done, v6.value);
});
};
}
function settle(resolve, reject, d3, v6) {
Promise.resolve(v6).then(function(v7) {
resolve({ value: v7, 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) => __awaiter5(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) => __awaiter5(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 = (platform, awsRegion, model, stream) => {
const endpoint = {
"bedrock": stream ? "invoke-with-response-stream" : "invoke",
"sagemaker": stream ? "invocations-response-stream" : "invocations"
}[platform];
return {
"bedrock": `https://${platform}-runtime.${awsRegion}.amazonaws.com/model/${model}/${endpoint}`,
"sagemaker": `https://runtime.sagemaker.${awsRegion}.amazonaws.com/endpoints/${model}/${endpoint}`
}[platform];
};
exports.getUrl = getUrl;
var getAuthHeaders = (url, method, headers, body, service, props) => __awaiter5(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 match = line.match(regex2);
if (match === null || match === void 0 ? void 0 : match[0]) {
const obj = JSON.parse(match[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 = (platform, { awsRegion, awsAccessKey, awsSecretKey, awsSessionToken }) => (fetcherArgs) => __awaiter5(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)(platform, 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), platform, {
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 (e4) {
throw e4;
}
});
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(name2, context, definition) {
if (typeof module2 !== "undefined" && module2.exports)
module2.exports = definition();
else if (typeof define === "function" && define.amd)
define(definition);
else
context[name2] = 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 i4 = 0; i4 < strArray.length; i4++) {
var component = strArray[i4];
if (typeof component !== "string") {
throw new TypeError("Url must be a string. Received " + component);
}
if (component === "") {
continue;
}
if (i4 > 0) {
component = component.replace(/^[\/]+/, "");
}
if (i4 < 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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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) => __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(this, void 0, void 0, function* () {
const { datasetType, before, after, limit: limit2, offset, 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 (offset != null) {
_queryParams["offset"] = offset.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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(this, void 0, void 0, function* () {
const { limit: limit2, offset } = request;
const _queryParams = {};
if (limit2 != null) {
_queryParams["limit"] = limit2.toString();
}
if (offset != null) {
_queryParams["offset"] = offset.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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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 __awaiter5 = 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 (e4) {
reject(e4);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e4) {
reject(e4);
}
}
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 __awaiter5(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) => __awaiter5(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 __awaiter5(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 __awaiter5(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) => __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 __awaiter5(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 match = /\/v1\/?$/;
const fixed = (_a5 = _options.environment) === null || _a5 === void 0 ? void 0 : _a5.toString().replace(match, "");
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(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
var desc = Object.getOwnPropertyDescriptor(m3, k3);
if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m3[k3];
} };
}
Object.defineProperty(o4, k22, desc);
} : function(o4, m3, k3, k22) {
if (k22 === void 0)
k22 = k3;
o4[k22] = m3[k3];
});
var __setModuleDefault4 = exports && exports.__setModuleDefault || (Object.create ? function(o4, v6) {
Object.defineProperty(o4, "default", { enumerable: true, value: v6 });
} : function(o4, v6) {
o4["default"] = v6;
});
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;
} });
}
});
// (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 i4 = 0; i4 < thatSigBytes; i4++) {
var thatByte = thatWords[i4 >>> 2] >>> 24 - i4 % 4 * 8 & 255;
thisWords[thisSigBytes + i4 >>> 2] |= thatByte << 24 - (thisSigBytes + i4) % 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 clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* 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 i4 = 0; i4 < nBytes; i4 += 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 i4 = 0; i4 < sigBytes; i4++) {
var bite = words[i4 >>> 2] >>> 24 - i4 % 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 i4 = 0; i4 < hexStrLength; i4 += 2) {
words[i4 >>> 3] |= parseInt(hexStr.substr(i4, 2), 16) << 24 - i4 % 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 i4 = 0; i4 < sigBytes; i4++) {
var bite = words[i4 >>> 2] >>> 24 - i4 % 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 i4 = 0; i4 < latin1StrLength; i4++) {
words[i4 >>> 2] |= (latin1Str.charCodeAt(i4) & 255) << 24 - i4 % 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 (e4) {
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 offset = 0; offset < nWordsReady; offset += blockSize) {
this._doProcessBlock(dataWords, offset);
}
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 clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_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 i4 = 0; i4 < x64WordsLength; i4++) {
var x64Word = x64Words[i4];
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 clone = Base.clone.call(this);
var words = clone.words = this.words.slice(0);
var wordsLength = words.length;
for (var i4 = 0; i4 < wordsLength; i4++) {
words[i4] = words[i4].clone();
}
return clone;
}
});
})();
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 i4 = 0; i4 < typedArrayByteLength; i4++) {
words[i4 >>> 2] |= typedArray[i4] << 24 - i4 % 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 i4 = 0; i4 < sigBytes; i4 += 2) {
var codePoint = words[i4 >>> 2] >>> 16 - i4 % 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 i4 = 0; i4 < utf16StrLength; i4++) {
words[i4 >>> 1] |= utf16Str.charCodeAt(i4) << 16 - i4 % 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 i4 = 0; i4 < sigBytes; i4 += 2) {
var codePoint = swapEndian(words[i4 >>> 2] >>> 16 - i4 % 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 i4 = 0; i4 < utf16StrLength; i4++) {
words[i4 >>> 1] |= swapEndian(utf16Str.charCodeAt(i4) << 16 - i4 % 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 i4 = 0; i4 < sigBytes; i4 += 3) {
var byte1 = words[i4 >>> 2] >>> 24 - i4 % 4 * 8 & 255;
var byte2 = words[i4 + 1 >>> 2] >>> 24 - (i4 + 1) % 4 * 8 & 255;
var byte3 = words[i4 + 2 >>> 2] >>> 24 - (i4 + 2) % 4 * 8 & 255;
var triplet = byte1 << 16 | byte2 << 8 | byte3;
for (var j3 = 0; j3 < 4 && i4 + 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 i4 = 0; i4 < base64StrLength; i4++) {
if (i4 % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i4 - 1)] << i4 % 4 * 2;
var bits2 = reverseMap[base64Str.charCodeAt(i4)] >>> 6 - i4 % 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 i4 = 0; i4 < sigBytes; i4 += 3) {
var byte1 = words[i4 >>> 2] >>> 24 - i4 % 4 * 8 & 255;
var byte2 = words[i4 + 1 >>> 2] >>> 24 - (i4 + 1) % 4 * 8 & 255;
var byte3 = words[i4 + 2 >>> 2] >>> 24 - (i4 + 2) % 4 * 8 & 255;
var triplet = byte1 << 16 | byte2 << 8 | byte3;
for (var j3 = 0; j3 < 4 && i4 + 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 i4 = 0; i4 < base64StrLength; i4++) {
if (i4 % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i4 - 1)] << i4 % 4 * 2;
var bits2 = reverseMap[base64Str.charCodeAt(i4)] >>> 6 - i4 % 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 i4 = 0; i4 < 64; i4++) {
T[i4] = Math2.abs(Math2.sin(i4 + 1)) * 4294967296 | 0;
}
})();
var MD53 = C_algo.MD5 = Hasher.extend({
_doReset: function() {
this._hash = new WordArray.init([
1732584193,
4023233417,
2562383102,
271733878
]);
},
_doProcessBlock: function(M, offset) {
for (var i4 = 0; i4 < 16; i4++) {
var offset_i = offset + i4;
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[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
var a4 = H2[0];
var b3 = H2[1];
var c5 = H2[2];
var d3 = H2[3];
a4 = FF(a4, b3, c5, d3, M_offset_0, 7, T[0]);
d3 = FF(d3, a4, b3, c5, M_offset_1, 12, T[1]);
c5 = FF(c5, d3, a4, b3, M_offset_2, 17, T[2]);
b3 = FF(b3, c5, d3, a4, M_offset_3, 22, T[3]);
a4 = FF(a4, b3, c5, d3, M_offset_4, 7, T[4]);
d3 = FF(d3, a4, b3, c5, M_offset_5, 12, T[5]);
c5 = FF(c5, d3, a4, b3, M_offset_6, 17, T[6]);
b3 = FF(b3, c5, d3, a4, M_offset_7, 22, T[7]);
a4 = FF(a4, b3, c5, d3, M_offset_8, 7, T[8]);
d3 = FF(d3, a4, b3, c5, M_offset_9, 12, T[9]);
c5 = FF(c5, d3, a4, b3, M_offset_10, 17, T[10]);
b3 = FF(b3, c5, d3, a4, M_offset_11, 22, T[11]);
a4 = FF(a4, b3, c5, d3, M_offset_12, 7, T[12]);
d3 = FF(d3, a4, b3, c5, M_offset_13, 12, T[13]);
c5 = FF(c5, d3, a4, b3, M_offset_14, 17, T[14]);
b3 = FF(b3, c5, d3, a4, M_offset_15, 22, T[15]);
a4 = GG(a4, b3, c5, d3, M_offset_1, 5, T[16]);
d3 = GG(d3, a4, b3, c5, M_offset_6, 9, T[17]);
c5 = GG(c5, d3, a4, b3, M_offset_11, 14, T[18]);
b3 = GG(b3, c5, d3, a4, M_offset_0, 20, T[19]);
a4 = GG(a4, b3, c5, d3, M_offset_5, 5, T[20]);
d3 = GG(d3, a4, b3, c5, M_offset_10, 9, T[21]);
c5 = GG(c5, d3, a4, b3, M_offset_15, 14, T[22]);
b3 = GG(b3, c5, d3, a4, M_offset_4, 20, T[23]);
a4 = GG(a4, b3, c5, d3, M_offset_9, 5, T[24]);
d3 = GG(d3, a4, b3, c5, M_offset_14, 9, T[25]);
c5 = GG(c5, d3, a4, b3, M_offset_3, 14, T[26]);
b3 = GG(b3, c5, d3, a4, M_offset_8, 20, T[27]);
a4 = GG(a4, b3, c5, d3, M_offset_13, 5, T[28]);
d3 = GG(d3, a4, b3, c5, M_offset_2, 9, T[29]);
c5 = GG(c5, d3, a4, b3, M_offset_7, 14, T[30]);
b3 = GG(b3, c5, d3, a4, M_offset_12, 20, T[31]);
a4 = HH(a4, b3, c5, d3, M_offset_5, 4, T[32]);
d3 = HH(d3, a4, b3, c5, M_offset_8, 11, T[33]);
c5 = HH(c5, d3, a4, b3, M_offset_11, 16, T[34]);
b3 = HH(b3, c5, d3, a4, M_offset_14, 23, T[35]);
a4 = HH(a4, b3, c5, d3, M_offset_1, 4, T[36]);
d3 = HH(d3, a4, b3, c5, M_offset_4, 11, T[37]);
c5 = HH(c5, d3, a4, b3, M_offset_7, 16, T[38]);
b3 = HH(b3, c5, d3, a4, M_offset_10, 23, T[39]);
a4 = HH(a4, b3, c5, d3, M_offset_13, 4, T[40]);
d3 = HH(d3, a4, b3, c5, M_offset_0, 11, T[41]);
c5 = HH(c5, d3, a4, b3, M_offset_3, 16, T[42]);
b3 = HH(b3, c5, d3, a4, M_offset_6, 23, T[43]);
a4 = HH(a4, b3, c5, d3, M_offset_9, 4, T[44]);
d3 = HH(d3, a4, b3, c5, M_offset_12, 11, T[45]);
c5 = HH(c5, d3, a4, b3, M_offset_15, 16, T[46]);
b3 = HH(b3, c5, d3, a4, M_offset_2, 23, T[47]);
a4 = II(a4, b3, c5, d3, M_offset_0, 6, T[48]);
d3 = II(d3, a4, b3, c5, M_offset_7, 10, T[49]);
c5 = II(c5, d3, a4, b3, M_offset_14, 15, T[50]);
b3 = II(b3, c5, d3, a4, M_offset_5, 21, T[51]);
a4 = II(a4, b3, c5, d3, M_offset_12, 6, T[52]);
d3 = II(d3, a4, b3, c5, M_offset_3, 10, T[53]);
c5 = II(c5, d3, a4, b3, M_offset_10, 15, T[54]);
b3 = II(b3, c5, d3, a4, M_offset_1, 21, T[55]);
a4 = II(a4, b3, c5, d3, M_offset_8, 6, T[56]);
d3 = II(d3, a4, b3, c5, M_offset_15, 10, T[57]);
c5 = II(c5, d3, a4, b3, M_offset_6, 15, T[58]);
b3 = II(b3, c5, d3, a4, M_offset_13, 21, T[59]);
a4 = II(a4, b3, c5, d3, M_offset_4, 6, T[60]);
d3 = II(d3, a4, b3, c5, M_offset_11, 10, T[61]);
c5 = II(c5, d3, a4, b3, M_offset_2, 15, T[62]);
b3 = II(b3, c5, d3, a4, M_offset_9, 21, T[63]);
H2[0] = H2[0] + a4 | 0;
H2[1] = H2[1] + b3 | 0;
H2[2] = H2[2] + c5 | 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 i4 = 0; i4 < 4; i4++) {
var H_i = H2[i4];
H2[i4] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
}
return hash;
},
clone: function() {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a4, b3, c5, d3, x2, s4, t4) {
var n4 = a4 + (b3 & c5 | ~b3 & d3) + x2 + t4;
return (n4 << s4 | n4 >>> 32 - s4) + b3;
}
function GG(a4, b3, c5, d3, x2, s4, t4) {
var n4 = a4 + (b3 & d3 | c5 & ~d3) + x2 + t4;
return (n4 << s4 | n4 >>> 32 - s4) + b3;
}
function HH(a4, b3, c5, d3, x2, s4, t4) {
var n4 = a4 + (b3 ^ c5 ^ d3) + x2 + t4;
return (n4 << s4 | n4 >>> 32 - s4) + b3;
}
function II(a4, b3, c5, d3, x2, s4, t4) {
var n4 = a4 + (c5 ^ (b3 | ~d3)) + x2 + t4;
return (n4 << s4 | n4 >>> 32 - s4) + b3;
}
C3.MD5 = Hasher._createHelper(MD53);
C3.HmacMD5 = Hasher._createHmacHelper(MD53);
})(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, offset) {
var H2 = this._hash.words;
var a4 = H2[0];
var b3 = H2[1];
var c5 = H2[2];
var d3 = H2[3];
var e4 = H2[4];
for (var i4 = 0; i4 < 80; i4++) {
if (i4 < 16) {
W[i4] = M[offset + i4] | 0;
} else {
var n4 = W[i4 - 3] ^ W[i4 - 8] ^ W[i4 - 14] ^ W[i4 - 16];
W[i4] = n4 << 1 | n4 >>> 31;
}
var t4 = (a4 << 5 | a4 >>> 27) + e4 + W[i4];
if (i4 < 20) {
t4 += (b3 & c5 | ~b3 & d3) + 1518500249;
} else if (i4 < 40) {
t4 += (b3 ^ c5 ^ d3) + 1859775393;
} else if (i4 < 60) {
t4 += (b3 & c5 | b3 & d3 | c5 & d3) - 1894007588;
} else {
t4 += (b3 ^ c5 ^ d3) - 899497514;
}
e4 = d3;
d3 = c5;
c5 = b3 << 30 | b3 >>> 2;
b3 = a4;
a4 = t4;
}
H2[0] = H2[0] + a4 | 0;
H2[1] = H2[1] + b3 | 0;
H2[2] = H2[2] + c5 | 0;
H2[3] = H2[3] + d3 | 0;
H2[4] = H2[4] + e4 | 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 clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
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, offset) {
var H3 = this._hash.words;
var a4 = H3[0];
var b3 = H3[1];
var c5 = H3[2];
var d3 = H3[3];
var e4 = H3[4];
var f4 = H3[5];
var g4 = H3[6];
var h4 = H3[7];
for (var i4 = 0; i4 < 64; i4++) {
if (i4 < 16) {
W[i4] = M[offset + i4] | 0;
} else {
var gamma0x = W[i4 - 15];
var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
var gamma1x = W[i4 - 2];
var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
W[i4] = gamma0 + W[i4 - 7] + gamma1 + W[i4 - 16];
}
var ch = e4 & f4 ^ ~e4 & g4;
var maj = a4 & b3 ^ a4 & c5 ^ b3 & c5;
var sigma0 = (a4 << 30 | a4 >>> 2) ^ (a4 << 19 | a4 >>> 13) ^ (a4 << 10 | a4 >>> 22);
var sigma1 = (e4 << 26 | e4 >>> 6) ^ (e4 << 21 | e4 >>> 11) ^ (e4 << 7 | e4 >>> 25);
var t1 = h4 + sigma1 + ch + K2[i4] + W[i4];
var t22 = sigma0 + maj;
h4 = g4;
g4 = f4;
f4 = e4;
e4 = d3 + t1 | 0;
d3 = c5;
c5 = b3;
b3 = a4;
a4 = t1 + t22 | 0;
}
H3[0] = H3[0] + a4 | 0;
H3[1] = H3[1] + b3 | 0;
H3[2] = H3[2] + c5 | 0;
H3[3] = H3[3] + d3 | 0;
H3[4] = H3[4] + e4 | 0;
H3[5] = H3[5] + f4 | 0;
H3[6] = H3[6] + g4 | 0;
H3[7] = H3[7] + h4 | 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 clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
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 i4 = 0; i4 < 80; i4++) {
W[i4] = 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, offset) {
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 i4 = 0; i4 < 80; i4++) {
var Wil;
var Wih;
var Wi = W[i4];
if (i4 < 16) {
Wih = Wi.high = M[offset + i4 * 2] | 0;
Wil = Wi.low = M[offset + i4 * 2 + 1] | 0;
} else {
var gamma0x = W[i4 - 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[i4 - 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[i4 - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i4 - 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[i4];
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 clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
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, y3 = 0;
for (var t4 = 0; t4 < 24; t4++) {
RHO_OFFSETS[x2 + 5 * y3] = (t4 + 1) * (t4 + 2) / 2 % 64;
var newX = y3 % 5;
var newY = (2 * x2 + 3 * y3) % 5;
x2 = newX;
y3 = newY;
}
for (var x2 = 0; x2 < 5; x2++) {
for (var y3 = 0; y3 < 5; y3++) {
PI_INDEXES[x2 + 5 * y3] = y3 + (2 * x2 + 3 * y3) % 5 * 5;
}
}
var LFSR = 1;
for (var i4 = 0; i4 < 24; i4++) {
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[i4] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
})();
var T = [];
(function() {
for (var i4 = 0; i4 < 25; i4++) {
T[i4] = 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 i4 = 0; i4 < 25; i4++) {
state[i4] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function(M, offset) {
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
for (var i4 = 0; i4 < nBlockSizeLanes; i4++) {
var M2i = M[offset + 2 * i4];
var M2i1 = M[offset + 2 * i4 + 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[i4];
lane.high ^= M2i1;
lane.low ^= M2i;
}
for (var round = 0; round < 24; round++) {
for (var x2 = 0; x2 < 5; x2++) {
var tMsw = 0, tLsw = 0;
for (var y3 = 0; y3 < 5; y3++) {
var lane = state[x2 + 5 * y3];
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 y3 = 0; y3 < 5; y3++) {
var lane = state[x2 + 5 * y3];
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 y3 = 0; y3 < 5; y3++) {
var laneIndex = x2 + 5 * y3;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[(x2 + 1) % 5 + 5 * y3];
var Tx2Lane = T[(x2 + 2) % 5 + 5 * y3];
lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
}
}
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
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 i4 = 0; i4 < outputLengthLanes; i4++) {
var lane = state[i4];
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 clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i4 = 0; i4 < 25; i4++) {
state[i4] = state[i4].clone();
}
return clone;
}
});
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, offset) {
for (var i4 = 0; i4 < 16; i4++) {
var offset_i = offset + i4;
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 t4;
for (var i4 = 0; i4 < 80; i4 += 1) {
t4 = al + M[offset + zl[i4]] | 0;
if (i4 < 16) {
t4 += f1(bl, cl, dl) + hl[0];
} else if (i4 < 32) {
t4 += f22(bl, cl, dl) + hl[1];
} else if (i4 < 48) {
t4 += f32(bl, cl, dl) + hl[2];
} else if (i4 < 64) {
t4 += f4(bl, cl, dl) + hl[3];
} else {
t4 += f5(bl, cl, dl) + hl[4];
}
t4 = t4 | 0;
t4 = rotl(t4, sl[i4]);
t4 = t4 + el | 0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t4;
t4 = ar + M[offset + zr[i4]] | 0;
if (i4 < 16) {
t4 += f5(br, cr, dr) + hr[0];
} else if (i4 < 32) {
t4 += f4(br, cr, dr) + hr[1];
} else if (i4 < 48) {
t4 += f32(br, cr, dr) + hr[2];
} else if (i4 < 64) {
t4 += f22(br, cr, dr) + hr[3];
} else {
t4 += f1(br, cr, dr) + hr[4];
}
t4 = t4 | 0;
t4 = rotl(t4, sr[i4]);
t4 = t4 + er | 0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t4;
}
t4 = 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] = t4;
},
_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 i4 = 0; i4 < 5; i4++) {
var H_i = H2[i4];
H2[i4] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
}
return hash;
},
clone: function() {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x2, y3, z3) {
return x2 ^ y3 ^ z3;
}
function f22(x2, y3, z3) {
return x2 & y3 | ~x2 & z3;
}
function f32(x2, y3, z3) {
return (x2 | ~y3) ^ z3;
}
function f4(x2, y3, z3) {
return x2 & z3 | y3 & ~z3;
}
function f5(x2, y3, z3) {
return x2 ^ (y3 | ~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 i4 = 0; i4 < hasherBlockSize; i4++) {
oKeyWords[i4] ^= 1549556828;
iKeyWords[i4] ^= 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 i4 = 1; i4 < iterations; i4++) {
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 MD53 = 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: MD53,
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 i4 = 1; i4 < iterations; i4++) {
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, offset) {
var cipher = this._cipher;
var blockSize = cipher.blockSize;
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
this._prevBlock = words.slice(offset, offset + 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, offset) {
var cipher = this._cipher;
var blockSize = cipher.blockSize;
var thisBlock = words.slice(offset, offset + blockSize);
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
var block;
var iv = this._iv;
if (iv) {
block = iv;
this._iv = undefined2;
} else {
block = this._prevBlock;
}
for (var i4 = 0; i4 < blockSize; i4++) {
words[offset + i4] ^= block[i4];
}
}
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 i4 = 0; i4 < nPaddingBytes; i4 += 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, offset) {
this._mode.processBlock(words, offset);
},
_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, offset) {
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function(words, offset) {
var cipher = this._cipher;
var blockSize = cipher.blockSize;
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, 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 i4 = 0; i4 < blockSize; i4++) {
words[offset + i4] ^= keystream[i4];
}
}
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, offset) {
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 i4 = 0; i4 < blockSize; i4++) {
words[offset + i4] ^= keystream[i4];
}
}
});
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, offset) {
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 i4 = 0; i4 < blockSize; i4++) {
words[offset + i4] ^= keystream[i4];
}
}
});
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, offset) {
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 i4 = 0; i4 < blockSize; i4++) {
words[offset + i4] ^= keystream[i4];
}
}
});
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, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function(words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
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 i4 = data.sigBytes - 1;
for (var i4 = data.sigBytes - 1; i4 >= 0; i4--) {
if (dataWords[i4 >>> 2] >>> 24 - i4 % 4 * 8 & 255) {
data.sigBytes = i4 + 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 i4 = 0; i4 < 256; i4++) {
if (i4 < 128) {
d3[i4] = i4 << 1;
} else {
d3[i4] = i4 << 1 ^ 283;
}
}
var x2 = 0;
var xi = 0;
for (var i4 = 0; i4 < 256; i4++) {
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 t4 = d3[sx] * 257 ^ sx * 16843008;
SUB_MIX_0[x2] = t4 << 24 | t4 >>> 8;
SUB_MIX_1[x2] = t4 << 16 | t4 >>> 16;
SUB_MIX_2[x2] = t4 << 8 | t4 >>> 24;
SUB_MIX_3[x2] = t4;
var t4 = x8 * 16843009 ^ x4 * 65537 ^ x22 * 257 ^ x2 * 16843008;
INV_SUB_MIX_0[sx] = t4 << 24 | t4 >>> 8;
INV_SUB_MIX_1[sx] = t4 << 16 | t4 >>> 16;
INV_SUB_MIX_2[sx] = t4 << 8 | t4 >>> 24;
INV_SUB_MIX_3[sx] = t4;
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 t4;
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 {
t4 = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
t4 = t4 << 8 | t4 >>> 24;
t4 = SBOX[t4 >>> 24] << 24 | SBOX[t4 >>> 16 & 255] << 16 | SBOX[t4 >>> 8 & 255] << 8 | SBOX[t4 & 255];
t4 ^= RCON[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
t4 = SBOX[t4 >>> 24] << 24 | SBOX[t4 >>> 16 & 255] << 16 | SBOX[t4 >>> 8 & 255] << 8 | SBOX[t4 & 255];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t4;
}
}
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t4 = keySchedule[ksRow];
} else {
var t4 = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t4;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t4 >>> 24]] ^ INV_SUB_MIX_1[SBOX[t4 >>> 16 & 255]] ^ INV_SUB_MIX_2[SBOX[t4 >>> 8 & 255]] ^ INV_SUB_MIX_3[SBOX[t4 & 255]];
}
}
},
encryptBlock: function(M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function(M, offset) {
var t4 = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t4;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
var t4 = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t4;
},
_doCryptBlock: function(M, offset, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) {
var nRounds = this._nRounds;
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s22 = M[offset + 2] ^ keySchedule[2];
var s32 = M[offset + 3] ^ keySchedule[3];
var ksRow = 4;
for (var round = 1; round < nRounds; round++) {
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 t32 = 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 = t32;
}
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 t32 = (SBOX2[s32 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s22 & 255]) ^ keySchedule[ksRow++];
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t22;
M[offset + 3] = t32;
},
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 i4 = 0; i4 < 56; i4++) {
var keyBitPos = PC1[i4] - 1;
keyBits[i4] = 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 i4 = 0; i4 < 24; i4++) {
subKey[i4 / 6 | 0] |= keyBits[(PC2[i4] - 1 + bitShift) % 28] << 31 - i4 % 6;
subKey[4 + (i4 / 6 | 0)] |= keyBits[28 + (PC2[i4 + 24] - 1 + bitShift) % 28] << 31 - i4 % 6;
}
subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
for (var i4 = 1; i4 < 7; i4++) {
subKey[i4] = subKey[i4] >>> (i4 - 1) * 4 + 3;
}
subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
}
var invSubKeys = this._invSubKeys = [];
for (var i4 = 0; i4 < 16; i4++) {
invSubKeys[i4] = subKeys[15 - i4];
}
},
encryptBlock: function(M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function(M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function(M, offset, subKeys) {
this._lBlock = M[offset];
this._rBlock = M[offset + 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 round = 0; round < 16; round++) {
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
var f4 = 0;
for (var i4 = 0; i4 < 8; i4++) {
f4 |= SBOX_P[i4][((rBlock ^ subKey[i4]) & SBOX_MASK[i4]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f4;
}
var t4 = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t4;
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[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64 / 32,
ivSize: 64 / 32,
blockSize: 64 / 32
});
function exchangeLR(offset, mask) {
var t4 = (this._lBlock >>> offset ^ this._rBlock) & mask;
this._rBlock ^= t4;
this._lBlock ^= t4 << offset;
}
function exchangeRL(offset, mask) {
var t4 = (this._rBlock >>> offset ^ this._lBlock) & mask;
this._lBlock ^= t4;
this._rBlock ^= t4 << offset;
}
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, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function(M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
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 i4 = 0; i4 < 256; i4++) {
S[i4] = i4;
}
for (var i4 = 0, j3 = 0; i4 < 256; i4++) {
var keyByteIndex = i4 % keySigBytes;
var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255;
j3 = (j3 + S[i4] + keyByte) % 256;
var t4 = S[i4];
S[i4] = S[j3];
S[j3] = t4;
}
this._i = this._j = 0;
},
_doProcessBlock: function(M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256 / 32,
ivSize: 0
});
function generateKeystreamWord() {
var S = this._S;
var i4 = this._i;
var j3 = this._j;
var keystreamWord = 0;
for (var n4 = 0; n4 < 4; n4++) {
i4 = (i4 + 1) % 256;
j3 = (j3 + S[i4]) % 256;
var t4 = S[i4];
S[i4] = S[j3];
S[j3] = t4;
keystreamWord |= S[(S[i4] + S[j3]) % 256] << 24 - n4 * 8;
}
this._i = i4;
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 i4 = this.cfg.drop; i4 > 0; i4--) {
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 i4 = 0; i4 < 4; i4++) {
K2[i4] = (K2[i4] << 8 | K2[i4] >>> 24) & 16711935 | (K2[i4] << 24 | K2[i4] >>> 8) & 4278255360;
}
var X = 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 i4 = 0; i4 < 4; i4++) {
nextState.call(this);
}
for (var i4 = 0; i4 < 8; i4++) {
C4[i4] ^= X[i4 + 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 i4 = 0; i4 < 4; i4++) {
nextState.call(this);
}
}
},
_doProcessBlock: function(M, offset) {
var X = this._X;
nextState.call(this);
S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
for (var i4 = 0; i4 < 4; i4++) {
S[i4] = (S[i4] << 8 | S[i4] >>> 24) & 16711935 | (S[i4] << 24 | S[i4] >>> 8) & 4278255360;
M[offset + i4] ^= S[i4];
}
},
blockSize: 128 / 32,
ivSize: 64 / 32
});
function nextState() {
var X = this._X;
var C4 = this._C;
for (var i4 = 0; i4 < 8; i4++) {
C_[i4] = C4[i4];
}
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 i4 = 0; i4 < 8; i4++) {
var gx = X[i4] + C4[i4];
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[i4] = gh ^ gl;
}
X[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
X[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
X[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
X[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
X[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
X[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
X[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
X[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 X = 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 i4 = 0; i4 < 4; i4++) {
nextState.call(this);
}
for (var i4 = 0; i4 < 8; i4++) {
C4[i4] ^= X[i4 + 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 i4 = 0; i4 < 4; i4++) {
nextState.call(this);
}
}
},
_doProcessBlock: function(M, offset) {
var X = this._X;
nextState.call(this);
S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
for (var i4 = 0; i4 < 4; i4++) {
S[i4] = (S[i4] << 8 | S[i4] >>> 24) & 16711935 | (S[i4] << 24 | S[i4] >>> 8) & 4278255360;
M[offset + i4] ^= S[i4];
}
},
blockSize: 128 / 32,
ivSize: 64 / 32
});
function nextState() {
var X = this._X;
var C4 = this._C;
for (var i4 = 0; i4 < 8; i4++) {
C_[i4] = C4[i4];
}
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 i4 = 0; i4 < 8; i4++) {
var gx = X[i4] + C4[i4];
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[i4] = gh ^ gl;
}
X[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
X[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
X[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
X[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
X[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
X[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
X[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
X[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 a4 = x2 >> 24 & 255;
let b3 = x2 >> 16 & 255;
let c5 = x2 >> 8 & 255;
let d3 = x2 & 255;
let y3 = ctx.sbox[0][a4] + ctx.sbox[1][b3];
y3 = y3 ^ ctx.sbox[2][c5];
y3 = y3 + ctx.sbox[3][d3];
return y3;
}
function BlowFish_Encrypt(ctx, left, right) {
let Xl = left;
let Xr = right;
let temp;
for (let i4 = 0; i4 < N; ++i4) {
Xl = Xl ^ ctx.pbox[i4];
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 i4 = N + 1; i4 > 1; --i4) {
Xl = Xl ^ ctx.pbox[i4];
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 index = 0; index < N + 2; index++) {
ctx.pbox[index] = ORIG_P[index] ^ key[keyIndex];
keyIndex++;
if (keyIndex >= keysize) {
keyIndex = 0;
}
}
let Data1 = 0;
let Data2 = 0;
let res = 0;
for (let i4 = 0; i4 < N + 2; i4 += 2) {
res = BlowFish_Encrypt(ctx, Data1, Data2);
Data1 = res.left;
Data2 = res.right;
ctx.pbox[i4] = Data1;
ctx.pbox[i4 + 1] = Data2;
}
for (let i4 = 0; i4 < 4; i4++) {
for (let j3 = 0; j3 < 256; j3 += 2) {
res = BlowFish_Encrypt(ctx, Data1, Data2);
Data1 = res.left;
Data2 = res.right;
ctx.sbox[i4][j3] = Data1;
ctx.sbox[i4][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, offset) {
var res = BlowFish_Encrypt(BLOWFISH_CTX, M[offset], M[offset + 1]);
M[offset] = res.left;
M[offset + 1] = res.right;
},
decryptBlock: function(M, offset) {
var res = BlowFish_Decrypt(BLOWFISH_CTX, M[offset], M[offset + 1]);
M[offset] = res.left;
M[offset + 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/@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/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(a4) {
return isArrayImpl(a4);
}
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 (e4) {
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 init2 = lazyComponent._init;
try {
return getComponentNameFromType(init2(payload));
} catch (x2) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty2 = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty2.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 (hasOwnProperty2.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 createElement3(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 (hasOwnProperty2.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 i4 = 0; i4 < childrenLength; i4++) {
childArray[i4] = arguments[i4 + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[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 cloneElement(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 defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty2.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === void 0 && defaultProps !== void 0) {
props[propName] = defaultProps[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 i4 = 0; i4 < childrenLength; i4++) {
childArray[i4] = arguments[i4 + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self2, source, owner, props);
}
function isValidElement(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(match) {
return escaperLookup[match];
});
return "$" + escapedString;
}
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, "$&/");
}
function getElementKey(element, index) {
if (typeof element === "object" && element !== null && element.key != null) {
{
checkKeyStringCoercion(element.key);
}
return escape2("" + element.key);
}
return index.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(c5) {
return c5;
});
} else if (mappedChild != null) {
if (isValidElement(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 i4 = 0; i4 < children.length; i4++) {
child = children[i4];
nextName = nextNamePrefix + getElementKey(child, i4);
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 count3 = 0;
mapIntoArray(children, result, "", "", function(child) {
return func.call(context, child, count3++);
});
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 (!isValidElement(children)) {
throw new Error("React.Children.only expected to receive a single React element child.");
}
return children;
}
function createContext3(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 defaultProps;
var propTypes;
Object.defineProperties(lazyType2, {
defaultProps: {
configurable: true,
get: function() {
return defaultProps;
},
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.");
defaultProps = 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 forwardRef2(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(name2) {
ownName = name2;
if (!render3.name && !render3.displayName) {
render3.displayName = name2;
}
}
});
}
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 memo(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(name2) {
ownName = name2;
if (!type.name && !type.displayName) {
type.displayName = name2;
}
}
});
}
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 useContext3(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 useState12(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init2) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init2);
}
function useRef3(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect7(create9, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create9, deps);
}
function useInsertionEffect(create9, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useInsertionEffect(create9, deps);
}
function useLayoutEffect(create9, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create9, deps);
}
function useCallback2(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create9, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create9, deps);
}
function useImperativeHandle(ref, create9, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create9, deps);
}
function useDebugValue(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 useId() {
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(name2, source, ownerFn) {
{
if (prefix === void 0) {
try {
throw Error();
} catch (x2) {
var match = x2.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || "";
}
}
return "\n" + prefix + name2;
}
}
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 c5 = controlLines.length - 1;
while (s4 >= 1 && c5 >= 0 && sampleLines[s4] !== controlLines[c5]) {
c5--;
}
for (; s4 >= 1 && c5 >= 0; s4--, c5--) {
if (sampleLines[s4] !== controlLines[c5]) {
if (s4 !== 1 || c5 !== 1) {
do {
s4--;
c5--;
if (c5 < 0 || sampleLines[s4] !== controlLines[c5]) {
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 && c5 >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
var name2 = fn ? fn.displayName || fn.name : "";
var syntheticFrame = name2 ? describeBuiltInComponentFrame(name2) : "";
{
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 init2 = lazyComponent._init;
try {
return describeUnknownElementTypeFrameInDEV(init2(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(hasOwnProperty2);
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 name2 = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name2) {
return "\n\nCheck the render method of `" + name2 + "`.";
}
}
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 i4 = 0; i4 < node.length; i4++) {
var child = node[i4];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(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 (isValidElement(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 name2 = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, "prop", name2, 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 i4 = 0; i4 < keys.length; i4++) {
var key = keys[i4];
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 = createElement3.apply(this, arguments);
if (element == null) {
return element;
}
if (validType) {
for (var i4 = 2; i4 < arguments.length; i4++) {
validateChildKeys(arguments[i4], 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 = cloneElement.apply(this, arguments);
for (var i4 = 2; i4 < arguments.length; i4++) {
validateChildKeys(arguments[i4], 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 i4 = 0;
try {
for (; i4 < queue2.length; i4++) {
var callback = queue2[i4];
do {
callback = callback(true);
} while (callback !== null);
}
queue2.length = 0;
} catch (error2) {
queue2 = queue2.slice(i4 + 1);
throw error2;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation;
var cloneElement$1 = cloneElementWithValidation;
var createFactory = createFactoryWithValidation;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray2,
only: onlyChild
};
exports.Children = Children;
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 = createContext3;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef2;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.useCallback = useCallback2;
exports.useContext = useContext3;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect7;
exports.useId = useId;
exports.useImperativeHandle = useImperativeHandle;
exports.useInsertionEffect = useInsertionEffect;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef3;
exports.useState = useState12;
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/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 Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = 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 isElement(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 = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode2;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
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 hasOwnProperty2 = 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 i4 = 0; i4 < 10; i4++) {
test2["_" + String.fromCharCode(i4)] = i4;
}
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 (hasOwnProperty2.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i4 = 0; i4 < symbols.length; i4++) {
if (propIsEnumerable.call(from, symbols[i4])) {
to[symbols[i4]] = from[symbols[i4]];
}
}
}
}
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(isValidElement, 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, y3) {
if (x2 === y3) {
return x2 !== 0 || 1 / x2 === 1 / y3;
} else {
return x2 !== x2 && y3 !== y3;
}
}
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 i4 = 0; i4 < propValue.length; i4++) {
var error = typeChecker(propValue, i4, componentName, location2, propFullName + "[" + i4 + "]", 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 (!isValidElement(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 i4 = 0; i4 < expectedValues.length; i4++) {
if (is(propValue, expectedValues[i4])) {
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 i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) {
var checker = arrayOfTypeCheckers[i4];
if (typeof checker !== "function") {
printWarning(
"Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i4 + "."
);
return emptyFunctionThatReturnsNull;
}
}
function validate5(props, propName, componentName, location2, propFullName) {
var expectedTypes = [];
for (var i5 = 0; i5 < arrayOfTypeCheckers.length; i5++) {
var checker2 = arrayOfTypeCheckers[i5];
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 (!isNode3(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 isNode3(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(isNode3);
}
if (propValue === null || isValidElement(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 (!isNode3(step.value)) {
return false;
}
}
} else {
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode3(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/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 index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
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, i4) {
var index = i4;
while (index > 0) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (compare2(parent, node) > 0) {
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
return;
}
}
}
function siftDown(heap, node, i4) {
var index = i4;
var length = heap.length;
var halfLength = length >>> 1;
while (index < halfLength) {
var leftIndex = (index + 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[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (rightIndex < length && compare2(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
return;
}
}
}
function compare2(a4, b3) {
var diff = a4.sortIndex - b3.sortIndex;
return diff !== 0 ? diff : a4.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 React21 = require_react();
var Scheduler = require_scheduler();
var ReactSharedInternals = React21.__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 Fragment = 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 i4 = 0; i4 < dependencies.length; i4++) {
allNativeEvents.add(dependencies[i4]);
}
}
var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var hasOwnProperty2 = 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 (e4) {
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 (hasOwnProperty2.call(validatedAttributeNameCache, attributeName)) {
return true;
}
if (hasOwnProperty2.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(name2, propertyInfo, isCustomComponentTag) {
if (propertyInfo !== null) {
return propertyInfo.type === RESERVED;
}
if (isCustomComponentTag) {
return false;
}
if (name2.length > 2 && (name2[0] === "o" || name2[0] === "O") && (name2[1] === "n" || name2[1] === "N")) {
return true;
}
return false;
}
function shouldRemoveAttributeWithWarning(name2, 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 = name2.toLowerCase().slice(0, 5);
return prefix2 !== "data-" && prefix2 !== "aria-";
}
}
default:
return false;
}
}
function shouldRemoveAttribute(name2, value, propertyInfo, isCustomComponentTag) {
if (value === null || typeof value === "undefined") {
return true;
}
if (shouldRemoveAttributeWithWarning(name2, 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(name2) {
return properties.hasOwnProperty(name2) ? properties[name2] : null;
}
function PropertyInfoRecord(name2, 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 = name2;
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(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
RESERVED,
false,
// mustUseProperty
name2,
// attributeName
null,
// attributeNamespace
false,
// sanitizeURL
false
);
});
[["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) {
var name2 = _ref[0], attributeName = _ref[1];
properties[name2] = new PropertyInfoRecord(
name2,
STRING,
false,
// mustUseProperty
attributeName,
// attributeName
null,
// attributeNamespace
false,
// sanitizeURL
false
);
});
["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
BOOLEANISH_STRING,
false,
// mustUseProperty
name2.toLowerCase(),
// attributeName
null,
// attributeNamespace
false,
// sanitizeURL
false
);
});
["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
BOOLEANISH_STRING,
false,
// mustUseProperty
name2,
// 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(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
BOOLEAN,
false,
// mustUseProperty
name2.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(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
BOOLEAN,
true,
// mustUseProperty
name2,
// 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(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
OVERLOADED_BOOLEAN,
false,
// mustUseProperty
name2,
// 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(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
POSITIVE_NUMERIC,
false,
// mustUseProperty
name2,
// attributeName
null,
// attributeNamespace
false,
// sanitizeURL
false
);
});
["rowSpan", "start"].forEach(function(name2) {
properties[name2] = new PropertyInfoRecord(
name2,
NUMERIC,
false,
// mustUseProperty
name2.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 name2 = attributeName.replace(CAMELIZE, capitalize);
properties[name2] = new PropertyInfoRecord(
name2,
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 name2 = attributeName.replace(CAMELIZE, capitalize);
properties[name2] = new PropertyInfoRecord(
name2,
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 name2 = attributeName.replace(CAMELIZE, capitalize);
properties[name2] = new PropertyInfoRecord(
name2,
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, name2, expected, propertyInfo) {
{
if (propertyInfo.mustUseProperty) {
var propertyName = propertyInfo.propertyName;
return node[propertyName];
} else {
{
checkAttributeStringCoercion(expected, name2);
}
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(name2, expected, propertyInfo, false)) {
return value;
}
if (value === "" + expected) {
return expected;
}
return value;
}
} else if (node.hasAttribute(attributeName)) {
if (shouldRemoveAttribute(name2, expected, propertyInfo, false)) {
return node.getAttribute(attributeName);
}
if (propertyInfo.type === BOOLEAN) {
return expected;
}
stringValue = node.getAttribute(attributeName);
}
if (shouldRemoveAttribute(name2, expected, propertyInfo, false)) {
return stringValue === null ? expected : stringValue;
} else if (stringValue === "" + expected) {
return expected;
} else {
return stringValue;
}
}
}
}
function getValueForAttribute(node, name2, expected, isCustomComponentTag) {
{
if (!isAttributeNameSafe(name2)) {
return;
}
if (!node.hasAttribute(name2)) {
return expected === void 0 ? void 0 : null;
}
var value = node.getAttribute(name2);
{
checkAttributeStringCoercion(expected, name2);
}
if (value === "" + expected) {
return expected;
}
return value;
}
}
function setValueForProperty(node, name2, value, isCustomComponentTag) {
var propertyInfo = getPropertyInfo(name2);
if (shouldIgnoreAttribute(name2, propertyInfo, isCustomComponentTag)) {
return;
}
if (shouldRemoveAttribute(name2, value, propertyInfo, isCustomComponentTag)) {
value = null;
}
if (isCustomComponentTag || propertyInfo === null) {
if (isAttributeNameSafe(name2)) {
var _attributeName = name2;
if (value === null) {
node.removeAttribute(_attributeName);
} else {
{
checkAttributeStringCoercion(value, name2);
}
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(name2, source, ownerFn) {
{
if (prefix === void 0) {
try {
throw Error();
} catch (x2) {
var match = x2.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || "";
}
}
return "\n" + prefix + name2;
}
}
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 c5 = controlLines.length - 1;
while (s4 >= 1 && c5 >= 0 && sampleLines[s4] !== controlLines[c5]) {
c5--;
}
for (; s4 >= 1 && c5 >= 0; s4--, c5--) {
if (sampleLines[s4] !== controlLines[c5]) {
if (s4 !== 1 || c5 !== 1) {
do {
s4--;
c5--;
if (c5 < 0 || sampleLines[s4] !== controlLines[c5]) {
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 && c5 >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
var name2 = fn ? fn.displayName || fn.name : "";
var syntheticFrame = name2 ? describeBuiltInComponentFrame(name2) : "";
{
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 init2 = lazyComponent._init;
try {
return describeUnknownElementTypeFrameInDEV(init2(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 init2 = lazyComponent._init;
try {
return getComponentNameFromType(init2(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 Fragment:
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 (e4) {
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 name2 = node.name;
if (name2 !== "") {
node.name = "";
}
{
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !!node._wrapperState.initialChecked;
}
if (name2 !== "") {
node.name = name2;
}
}
function restoreControlledState(element, props) {
var node = element;
updateWrapper(node, props);
updateNamedCousins(node, props);
}
function updateNamedCousins(rootNode, props) {
var name2 = props.name;
if (props.type === "radio" && name2 != null) {
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
{
checkAttributeStringCoercion(name2, "name");
}
var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name2) + '][type="radio"]');
for (var i4 = 0; i4 < group.length; i4++) {
var otherNode = group[i4];
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) {
React21.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(a4) {
return isArrayImpl(a4);
}
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 i4 = 0; i4 < valuePropNames.length; i4++) {
var propName = valuePropNames[i4];
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 i4 = 0; i4 < selectedValues.length; i4++) {
selectedValue["$" + selectedValues[i4]] = 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(name2, value, isCustomProperty) {
var isEmpty = value == null || typeof value === "boolean" || value === "";
if (isEmpty) {
return "";
}
if (!isCustomProperty && typeof value === "number" && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name2) && isUnitlessNumber[name2])) {
return value + "px";
}
{
checkCSSPropertyStringCoercion(value, name2);
}
return ("" + value).trim();
}
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
function hyphenateStyleName(name2) {
return name2.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(name2) {
if (warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2]) {
return;
}
warnedStyleNames[name2] = true;
error(
"Unsupported style property %s. Did you mean %s?",
name2,
// As Andi Smith suggests
// (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
// is converted to lowercase `ms`.
camelize(name2.replace(msPattern$1, "ms-"))
);
};
var warnBadVendoredStyleName = function(name2) {
if (warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2]) {
return;
}
warnedStyleNames[name2] = true;
error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name2, name2.charAt(0).toUpperCase() + name2.slice(1));
};
var warnStyleValueWithSemicolon = function(name2, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name2, value.replace(badStyleValueWithSemicolonPattern, ""));
};
var warnStyleValueIsNaN = function(name2, value) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
error("`NaN` is an invalid value for the `%s` css style property.", name2);
};
var warnStyleValueIsInfinity = function(name2, value) {
if (warnedForInfinityValue) {
return;
}
warnedForInfinityValue = true;
error("`Infinity` is an invalid value for the `%s` css style property.", name2);
};
warnValidStyle = function(name2, value) {
if (name2.indexOf("-") > -1) {
warnHyphenatedStyleName(name2);
} else if (badVendoredStyleNamePattern.test(name2)) {
warnBadVendoredStyleName(name2);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name2, value);
}
if (typeof value === "number") {
if (isNaN(value)) {
warnStyleValueIsNaN(name2, value);
} else if (!isFinite(value)) {
warnStyleValueIsInfinity(name2, 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 i4 = 0; i4 < longhands.length; i4++) {
expanded[longhands[i4]] = 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, name2) {
{
if (hasOwnProperty2.call(warnedProperties, name2) && warnedProperties[name2]) {
return true;
}
if (rARIACamel.test(name2)) {
var ariaName = "aria-" + name2.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.", name2);
warnedProperties[name2] = true;
return true;
}
if (name2 !== correctName) {
error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name2, correctName);
warnedProperties[name2] = true;
return true;
}
}
if (rARIA.test(name2)) {
var lowerCasedName = name2.toLowerCase();
var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
if (standardName == null) {
warnedProperties[name2] = true;
return false;
}
if (name2 !== standardName) {
error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name2, standardName);
warnedProperties[name2] = 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, name2, value, eventRegistry) {
if (hasOwnProperty2.call(warnedProperties$1, name2) && warnedProperties$1[name2]) {
return true;
}
var lowerCasedName = name2.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[name2] = true;
return true;
}
if (eventRegistry != null) {
var registrationNameDependencies2 = eventRegistry.registrationNameDependencies, possibleRegistrationNames2 = eventRegistry.possibleRegistrationNames;
if (registrationNameDependencies2.hasOwnProperty(name2)) {
return true;
}
var registrationName = possibleRegistrationNames2.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames2[lowerCasedName] : null;
if (registrationName != null) {
error("Invalid event handler property `%s`. Did you mean `%s`?", name2, registrationName);
warnedProperties$1[name2] = true;
return true;
}
if (EVENT_NAME_REGEX.test(name2)) {
error("Unknown event handler property `%s`. It will be ignored.", name2);
warnedProperties$1[name2] = true;
return true;
}
} else if (EVENT_NAME_REGEX.test(name2)) {
if (INVALID_EVENT_NAME_REGEX.test(name2)) {
error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name2);
}
warnedProperties$1[name2] = true;
return true;
}
if (rARIA$1.test(name2) || rARIACamel$1.test(name2)) {
return true;
}
if (lowerCasedName === "innerhtml") {
error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.");
warnedProperties$1[name2] = true;
return true;
}
if (lowerCasedName === "aria") {
error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead.");
warnedProperties$1[name2] = 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[name2] = 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.", name2);
warnedProperties$1[name2] = true;
return true;
}
var propertyInfo = getPropertyInfo(name2);
var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
var standardName = possibleStandardNames[lowerCasedName];
if (standardName !== name2) {
error("Invalid DOM property `%s`. Did you mean `%s`?", name2, standardName);
warnedProperties$1[name2] = true;
return true;
}
} else if (!isReserved && name2 !== 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.", name2, lowerCasedName);
warnedProperties$1[name2] = true;
return true;
}
if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name2, 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, name2, name2, value, name2);
} 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, name2, name2, value, name2, name2, name2);
}
warnedProperties$1[name2] = true;
return true;
}
if (isReserved) {
return true;
}
if (shouldRemoveAttributeWithWarning(name2, value, propertyInfo, false)) {
warnedProperties$1[name2] = 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, name2, 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".', name2, value);
warnedProperties$1[name2] = 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 i4 = 0; i4 < queuedTargets.length; i4++) {
restoreStateOfTarget(queuedTargets[i4]);
}
}
}
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, a4, b3) {
if (isInsideEventHandler) {
return fn(a4, b3);
}
isInsideEventHandler = true;
try {
return batchedUpdatesImpl(fn, a4, 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(name2, type, props) {
switch (name2) {
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 (e4) {
passiveBrowserEventsSupported = false;
}
}
function invokeGuardedCallbackProd(name2, func, context, a4, b3, c5, d3, e4, f4) {
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(name2, func, context, a4, b3, c5, d3, e4, f4) {
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-" + (name2 ? name2 : "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(name2, func, context, a4, b3, c5, d3, e4, f4) {
hasError = false;
caughtError = null;
invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}
function invokeGuardedCallbackAndCatchFirstError(name2, func, context, a4, b3, c5, d3, e4, f4) {
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 a4 = fiber;
var b3 = alternate;
while (true) {
var parentA = a4.return;
if (parentA === null) {
break;
}
var parentB = parentA.alternate;
if (parentB === null) {
var nextParent = parentA.return;
if (nextParent !== null) {
a4 = b3 = nextParent;
continue;
}
break;
}
if (parentA.child === parentB.child) {
var child = parentA.child;
while (child) {
if (child === a4) {
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 (a4.return !== b3.return) {
a4 = parentA;
b3 = parentB;
} else {
var didFindChild = false;
var _child = parentA.child;
while (_child) {
if (_child === a4) {
didFindChild = true;
a4 = parentA;
b3 = parentB;
break;
}
if (_child === b3) {
didFindChild = true;
b3 = parentA;
a4 = parentB;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
_child = parentB.child;
while (_child) {
if (_child === a4) {
didFindChild = true;
a4 = parentB;
b3 = parentA;
break;
}
if (_child === b3) {
didFindChild = true;
b3 = parentB;
a4 = 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 (a4.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 (a4.tag !== HostRoot) {
throw new Error("Unable to find node on an unmounted component.");
}
if (a4.stateNode.current === a4) {
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 match = findCurrentHostFiberImpl(child);
if (match !== null) {
return match;
}
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 match = findCurrentHostFiberWithNoPortalsImpl(child);
if (match !== null) {
return match;
}
}
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 now = 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 index2 = 0; index2 < TotalLanes; index2++) {
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 index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
nextLanes |= entanglements[index2];
lanes &= ~lane;
}
}
return nextLanes;
}
function getMostRecentEventTime(root3, lanes) {
var eventTimes = root3.eventTimes;
var mostRecentEventTime = NoTimestamp;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
var eventTime = eventTimes[index2];
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 index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
var expirationTime = expirationTimes[index2];
if (expirationTime === NoTimestamp) {
if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
expirationTimes[index2] = 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(a4, b3) {
return (a4 & b3) !== NoLanes;
}
function isSubsetOfLanes(set2, subset) {
return (set2 & subset) === subset;
}
function mergeLanes(a4, b3) {
return a4 | b3;
}
function removeLanes(set2, subset) {
return set2 & ~subset;
}
function intersectLanes(a4, b3) {
return a4 & b3;
}
function laneToLanes(lane) {
return lane;
}
function higherPriorityLane(a4, b3) {
return a4 !== NoLane && a4 < b3 ? a4 : b3;
}
function createLaneMap(initial) {
var laneMap = [];
for (var i4 = 0; i4 < TotalLanes; i4++) {
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 index2 = laneToIndex(updateLane);
eventTimes[index2] = eventTime;
}
function markRootSuspended(root3, suspendedLanes) {
root3.suspendedLanes |= suspendedLanes;
root3.pingedLanes &= ~suspendedLanes;
var expirationTimes = root3.expirationTimes;
var lanes = suspendedLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
expirationTimes[index2] = 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 index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
entanglements[index2] = NoLanes;
eventTimes[index2] = NoTimestamp;
expirationTimes[index2] = NoTimestamp;
lanes &= ~lane;
}
}
function markRootEntangled(root3, entangledLanes) {
var rootEntangledLanes = root3.entangledLanes |= entangledLanes;
var entanglements = root3.entanglements;
var lanes = rootEntangledLanes;
while (lanes) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
if (
// Is this one of the newly entangled lanes?
lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
entanglements[index2] & entangledLanes
) {
entanglements[index2] |= 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 index2 = laneToIndex(lanes);
var lane = 1 << index2;
var updaters = pendingUpdatersLaneMap[index2];
updaters.add(fiber);
lanes &= ~lane;
}
}
function movePendingFibersToMemoized(root3, lanes) {
if (!isDevToolsPresent) {
return;
}
var pendingUpdatersLaneMap = root3.pendingUpdatersLaneMap;
var memoizedUpdaters = root3.memoizedUpdaters;
while (lanes > 0) {
var index2 = laneToIndex(lanes);
var lane = 1 << index2;
var updaters = pendingUpdatersLaneMap[index2];
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(a4, b3) {
return a4 !== 0 && a4 < b3 ? a4 : b3;
}
function lowerEventPriority(a4, b3) {
return a4 === 0 || a4 > b3 ? a4 : b3;
}
function isHigherEventPriority(a4, b3) {
return a4 !== 0 && a4 < 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 i4 = 0;
for (; i4 < queuedExplicitHydrationTargets.length; i4++) {
if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i4].priority)) {
break;
}
}
queuedExplicitHydrationTargets.splice(i4, 0, queuedTarget);
if (i4 === 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 i4 = 1; i4 < queuedDiscreteEvents.length; i4++) {
var queuedEvent = queuedDiscreteEvents[i4];
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, y3) {
return x2 === y3 && (x2 !== 0 || 1 / x2 === 1 / y3) || x2 !== x2 && y3 !== y3;
}
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 i4 = 0; i4 < keysA.length; i4++) {
var currentKey = keysA[i4];
if (!hasOwnProperty2.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, offset) {
var node = getLeafNode(root3);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === TEXT_NODE) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node,
offset: offset - 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 (e4) {
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 i4 = 0; i4 < ancestors.length; i4++) {
var info = ancestors[i4];
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 i4 = 0; i4 < simpleEventPluginEvents.length; i4++) {
var eventName = simpleEventPluginEvents[i4];
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 i4 = dispatchListeners.length - 1; i4 >= 0; i4--) {
var _dispatchListeners$i = dispatchListeners[i4], 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 i4 = 0; i4 < dispatchQueue.length; i4++) {
var _dispatchQueue$i = dispatchQueue[i4], 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(name2) {
names.push(name2);
});
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 noop() {
}
function trapClickOnNonInteractiveElement(node) {
node.onclick = noop;
}
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 i4 = 0; i4 < updatePayload.length; i4 += 2) {
var propKey = updatePayload[i4];
var propValue = updatePayload[i4 + 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 createElement3(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]" && !hasOwnProperty2.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 i4 = 0; i4 < mediaEventTypes.length; i4++) {
listenToNonDelegatedEvent(mediaEventTypes[i4], 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 i4 = 0; i4 < mediaEventTypes.length; i4++) {
listenToNonDelegatedEvent(mediaEventTypes[i4], 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 name2 = attributes[_i].name.toLowerCase();
switch (name2) {
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 = createElement3(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(hasOwnProperty2);
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 index = -1;
function createCursor(defaultValue) {
return {
current: defaultValue
};
}
function pop(cursor, fiber) {
if (index < 0) {
{
error("Unexpected pop.");
}
return;
}
{
if (fiber !== fiberStack[index]) {
error("Unexpected Fiber popped.");
}
}
cursor.current = valueStack[index];
valueStack[index] = null;
{
fiberStack[index] = null;
}
index--;
}
function push3(cursor, value, fiber) {
index++;
valueStack[index] = cursor.current;
{
fiberStack[index] = 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 name2 = getComponentNameFromFiber(workInProgress2) || "Unknown";
checkPropTypes(contextTypes, context, "context", name2);
}
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 name2 = getComponentNameFromFiber(fiber) || "Unknown";
checkPropTypes(childContextTypes, childContext, "child context", name2);
}
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 i4 = 0;
var previousUpdatePriority = getCurrentUpdatePriority();
try {
var isSync = true;
var queue2 = syncQueue;
setCurrentUpdatePriority(DiscreteEventPriority);
for (; i4 < queue2.length; i4++) {
var callback = queue2[i4];
do {
callback = callback(isSync);
} while (callback !== null);
}
syncQueue = null;
includesLegacySyncCallbacks = false;
} catch (error2) {
if (syncQueue !== null) {
syncQueue = syncQueue.slice(i4 + 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, index2) {
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 = index2 + 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 defaultProps = Component2.defaultProps;
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[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 i4 = 0; i4 < concurrentQueues.length; i4++) {
var queue2 = concurrentQueues[i4];
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 clone = {
baseState: currentQueue.baseState,
firstBaseUpdate: currentQueue.firstBaseUpdate,
lastBaseUpdate: currentQueue.lastBaseUpdate,
shared: currentQueue.shared,
effects: currentQueue.effects
};
workInProgress2.updateQueue = clone;
}
}
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 clone = {
eventTime: update2.eventTime,
lane: update2.lane,
tag: update2.tag,
payload: update2.payload,
callback: update2.callback,
next: null
};
if (newLast === null) {
newFirst = newLast = clone;
} else {
newLast.next = clone;
newLast = clone;
}
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 clone = {
eventTime: updateEventTime,
lane: updateLane,
tag: update2.tag,
payload: update2.payload,
callback: update2.callback,
next: null
};
if (newLastBaseUpdate === null) {
newFirstBaseUpdate = newLastBaseUpdate = clone;
newBaseState = newState;
} else {
newLastBaseUpdate = newLastBaseUpdate.next = clone;
}
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 i4 = 0; i4 < effects.length; i4++) {
var effect = effects[i4];
var callback = effect.callback;
if (callback !== null) {
effect.callback = null;
callCallback(callback, instance);
}
}
}
}
var fakeInternalInstance = {};
var emptyRefsObject = new React21.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 name2 = 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?", name2);
} else {
error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name2);
}
}
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?", name2);
}
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.", name2);
}
if (instance.propTypes) {
error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name2);
}
if (instance.contextType) {
error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name2);
}
{
if (instance.contextTypes) {
error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name2);
}
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.", name2);
}
}
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.", name2);
}
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()?", name2);
}
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().", name2);
}
if (typeof instance.componentWillRecieveProps === "function") {
error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name2);
}
if (typeof instance.UNSAFE_componentWillRecieveProps === "function") {
error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name2);
}
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.", name2, name2);
}
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.", name2, name2);
}
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.", name2);
}
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.", name2);
}
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.", name2);
}
var _state = instance.state;
if (_state && (typeof _state !== "object" || isArray2(_state))) {
error("%s.state: must be set to an object or null", name2);
}
if (typeof instance.getChildContext === "function" && typeof ctor.childContextTypes !== "object") {
error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name2);
}
}
}
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 init2 = lazyType2._init;
return init2(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 clone = createWorkInProgress(fiber, pendingProps);
clone.index = 0;
clone.sibling = null;
return clone;
}
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 !== Fragment) {
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 init2 = newChild._init;
return createChild(returnFiber, init2(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 init2 = newChild._init;
return updateSlot(returnFiber, oldFiber, init2(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 init2 = newChild._init;
return updateFromMap(existingChildren, returnFiber, newIdx, init2(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 init2 = child._init;
warnOnInvalidKey(init2(payload), knownKeys, returnFiber);
break;
}
}
return knownKeys;
}
function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
{
var knownKeys = null;
for (var i4 = 0; i4 < newChildren.length; i4++) {
var child = newChildren[i4];
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 === Fragment) {
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 init2 = newChild._init;
return reconcileChildFibers2(returnFiber, currentFirstChild, init2(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(c5) {
if (c5 === 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 c5;
}
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 i4 = 0; i4 < workInProgressSources.length; i4++) {
var mutableSource = workInProgressSources[i4];
{
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 i4 = 0; i4 <= hookTypesUpdateIndexDev; i4++) {
var oldHookName = hookTypesDev[i4];
var newHookName = i4 === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
var row = i4 + 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 i4 = 0; i4 < prevDeps.length && i4 < nextDeps.length; i4++) {
if (objectIs(nextDeps[i4], prevDeps[i4])) {
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(reducer, initialArg, init2) {
var hook = mountWorkInProgressHook();
var initialState;
if (init2 !== void 0) {
initialState = init2(initialArg);
} else {
initialState = initialArg;
}
hook.memoizedState = hook.baseState = initialState;
var queue2 = {
pending: null,
interleaved: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: reducer,
lastRenderedState: initialState
};
hook.queue = queue2;
var dispatch = queue2.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue2);
return [hook.memoizedState, dispatch];
}
function updateReducer(reducer, initialArg, init2) {
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 = reducer;
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 clone = {
lane: updateLane,
action: update2.action,
hasEagerState: update2.hasEagerState,
eagerState: update2.eagerState,
next: null
};
if (newBaseQueueLast === null) {
newBaseQueueFirst = newBaseQueueLast = clone;
newBaseState = newState;
} else {
newBaseQueueLast = newBaseQueueLast.next = clone;
}
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 = reducer(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(reducer, initialArg, init2) {
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 = reducer;
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 = reducer(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(initialState) {
var hook = mountWorkInProgressHook();
if (typeof initialState === "function") {
initialState = initialState();
}
hook.memoizedState = hook.baseState = initialState;
var queue2 = {
pending: null,
interleaved: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: initialState
};
hook.queue = queue2;
var dispatch = queue2.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue2);
return [hook.memoizedState, dispatch];
}
function updateState(initialState) {
return updateReducer(basicStateReducer);
}
function rerenderState(initialState) {
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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} 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(reducer, initialArg, init2) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderReducer(reducer, initialArg, init2);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderState(initialState);
} 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 logError = showErrorDialog(boundary, errorInfo);
if (logError === 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 (e4) {
setTimeout(function() {
throw e4;
});
}
}
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 init2 = lazyComponent._init;
try {
outerMemoType = init2(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 init2 = lazyComponent._init;
var Component2 = init2(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, index2) {
{
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, index2, 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 i4 = 0; i4 < children.length; i4++) {
if (!validateSuspenseListNestedChild(children[i4], i4)) {
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 Fragment:
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, isHidden) {
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 Fragment:
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 && now() > 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.
now() * 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 = now();
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, isHidden) {
var hostSubtreeRoot = null;
{
var node = finishedWork;
while (true) {
if (node.tag === HostComponent) {
if (hostSubtreeRoot === null) {
hostSubtreeRoot = node;
try {
var instance = node.stateNode;
if (isHidden) {
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 (isHidden) {
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 i4 = 0; i4 < deletions.length; i4++) {
var childToDelete = deletions[i4];
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 isHidden = newState !== null;
offscreenInstance.isHidden = isHidden;
if (isHidden) {
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 isHidden = fiber.memoizedState !== null;
var newOffscreenSubtreeIsHidden = isHidden || 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 isHidden = fiber.memoizedState !== null;
if (isHidden) {
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 isHidden = fiber.memoizedState !== null;
if (isHidden) {
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 i4 = 0; i4 < deletions.length; i4++) {
var fiberToDelete = deletions[i4];
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 = now() + 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 now();
}
if (currentEventTime !== NoTimestamp) {
return currentEventTime;
}
currentEventTime = now();
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, now());
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, now());
throw _fatalError;
}
}
root3.finishedWork = finishedWork;
root3.finishedLanes = lanes;
finishConcurrentRender(root3, exitStatus, lanes);
}
}
ensureRootIsScheduled(root3, now());
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 - now();
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 = now() - 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 i4 = 0; i4 < checks.length; i4++) {
var check = checks[i4];
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, now());
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, now());
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, now());
return null;
}
function flushRoot(root3, lanes) {
if (lanes !== NoLanes) {
markRootEntangled(root3, mergeLanes(lanes, SyncLane));
ensureRootIsScheduled(root3, now());
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
resetRenderTimer();
flushSyncCallbacks();
}
}
}
function batchedUpdates$1(fn, a4) {
var prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a4);
} 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, a4, b3, c5, d3) {
var previousPriority = getCurrentUpdatePriority();
var prevTransition = ReactCurrentBatchConfig$3.transition;
try {
ReactCurrentBatchConfig$3.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
return fn(a4, b3, c5, d3);
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$3.transition = prevTransition;
if (executionContext === NoContext) {
resetRenderTimer();
}
}
}
function flushSync(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 = now();
}
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, now());
if (recoverableErrors !== null) {
var onRecoverableError = root3.onRecoverableError;
for (var i4 = 0; i4 < recoverableErrors.length; i4++) {
var recoverableError = recoverableErrors[i4];
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 i4 = 0; i4 < profilerEffects.length; i4++) {
var _fiber = profilerEffects[i4];
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) && now() - 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();
flushSync(function() {
scheduleFibersWithFamiliesRecursively(root3.current, updatedFamilies, staleFamilies);
});
}
};
var scheduleRoot = function(root3, element) {
{
if (root3.context !== emptyContextObject) {
return;
}
flushPassiveEffects();
flushSync(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 (e4) {
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(Fragment, 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 createPortal(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: {
flushSync(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, index2) {
var key = path[index2];
var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
if (index2 + 1 === path.length) {
if (isArray2(updated)) {
updated.splice(key, 1);
} else {
delete updated[key];
}
return updated;
}
updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1);
return updated;
};
var copyWithDelete = function(obj, path) {
return copyWithDeleteImpl(obj, path, 0);
};
var copyWithRenameImpl = function(obj, oldPath, newPath, index2) {
var oldKey = oldPath[index2];
var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
if (index2 + 1 === oldPath.length) {
var newKey = newPath[index2];
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,
index2 + 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 i4 = 0; i4 < newPath.length - 1; i4++) {
if (oldPath[i4] !== newPath[i4]) {
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, index2, value) {
if (index2 >= path.length) {
return value;
}
var key = path[index2];
var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
updated[key] = copyWithSetImpl(obj[key], path, index2 + 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.");
}
}
flushSync(function() {
updateContainer(null, root3, null, null);
});
unmarkContainerAsRoot(container);
}
};
function createRoot3(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 i4 = 0; i4 < mutableSources.length; i4++) {
var mutableSource = mutableSources[i4];
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);
flushSync();
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);
flushSync(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.");
}
}
flushSync(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, flushSync);
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 createPortal(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 createRoot3(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 flushSync(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_client15 = __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 {
i4 = m3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
exports.createRoot = function(c5, o4) {
i4.usingClientEntryPoint = true;
try {
return m3.createRoot(c5, o4);
} finally {
i4.usingClientEntryPoint = false;
}
};
exports.hydrateRoot = function(c5, h4, o4) {
i4.usingClientEntryPoint = true;
try {
return m3.hydrateRoot(c5, h4, o4);
} finally {
i4.usingClientEntryPoint = false;
}
};
}
var i4;
}
});
// 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 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.";
var CHUNK_SIZE = 5e3;
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)";
return ChatModelProviders2;
})(ChatModelProviders || {});
var BUILTIN_CHAT_MODELS = [
{
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-20240620" /* CLAUDE_3_5_SONNET */,
provider: "anthropic" /* ANTHROPIC */,
enabled: true,
isBuiltIn: true
},
{
name: "claude-3-haiku-20240307" /* CLAUDE_3_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["OPENAI_FORMAT"] = "3rd party (openai-format)";
return EmbeddingModelProviders2;
})(EmbeddingModelProviders || {});
var BUILTIN_EMBEDDING_MODELS = [
{
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 VAULT_VECTOR_STORE_STRATEGIES = [
"NEVER" /* NEVER */,
"ON STARTUP" /* ON_STARTUP */,
"ON MODE SWITCH" /* ON_MODE_SWITCH */
];
var COMMAND_IDS = {
FIX_GRAMMAR: "fix-grammar-prompt",
SUMMARIZE: "summarize-prompt",
GENERATE_TOC: "generate-toc-prompt",
GENERATE_GLOSSARY: "generate-glossary-prompt",
SIMPLIFY: "simplify-prompt",
EMOJIFY: "emojify-prompt",
REMOVE_URLS: "remove-urls-prompt",
REWRITE_TWEET: "rewrite-tweet-prompt",
REWRITE_TWEET_THREAD: "rewrite-tweet-thread-prompt",
MAKE_SHORTER: "make-shorter-prompt",
MAKE_LONGER: "make-longer-prompt",
ELI5: "eli5-prompt",
PRESS_RELEASE: "press-release-prompt",
TRANSLATE: "translate-selection-prompt",
CHANGE_TONE: "change-tone-prompt",
COUNT_TOKENS: "count-tokens",
COUNT_TOTAL_VAULT_TOKENS: "count-total-vault-tokens"
};
var DEFAULT_SETTINGS = {
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: true,
customPromptsFolder: "copilot-custom-prompts",
indexVaultToVectorStore: "ON MODE SWITCH" /* ON_MODE_SWITCH */,
qaExclusions: "",
chatNoteContextPath: "",
chatNoteContextTags: [],
debug: false,
enableEncryption: false,
maxSourceChunks: 3,
groqApiKey: "",
activeModels: BUILTIN_CHAT_MODELS,
activeEmbeddingModels: BUILTIN_EMBEDDING_MODELS,
embeddingRequestsPerSecond: 10,
enabledCommands: {
[COMMAND_IDS.FIX_GRAMMAR]: {
enabled: true,
name: "Fix grammar and spelling of selection"
},
[COMMAND_IDS.SUMMARIZE]: {
enabled: true,
name: "Summarize selection"
},
[COMMAND_IDS.GENERATE_TOC]: {
enabled: true,
name: "Generate table of contents for selection"
},
[COMMAND_IDS.GENERATE_GLOSSARY]: {
enabled: true,
name: "Generate glossary for selection"
},
[COMMAND_IDS.SIMPLIFY]: {
enabled: true,
name: "Simplify selection"
},
[COMMAND_IDS.EMOJIFY]: {
enabled: true,
name: "Emojify selection"
},
[COMMAND_IDS.REMOVE_URLS]: {
enabled: true,
name: "Remove URLs from selection"
},
[COMMAND_IDS.REWRITE_TWEET]: {
enabled: true,
name: "Rewrite selection to a tweet"
},
[COMMAND_IDS.REWRITE_TWEET_THREAD]: {
enabled: true,
name: "Rewrite selection to a tweet thread"
},
[COMMAND_IDS.MAKE_SHORTER]: {
enabled: true,
name: "Make selection shorter"
},
[COMMAND_IDS.MAKE_LONGER]: {
enabled: true,
name: "Make selection longer"
},
[COMMAND_IDS.ELI5]: {
enabled: true,
name: "Explain selection like I'm 5"
},
[COMMAND_IDS.PRESS_RELEASE]: {
enabled: true,
name: "Rewrite selection to a press release"
},
[COMMAND_IDS.TRANSLATE]: {
enabled: true,
name: "Translate selection"
},
[COMMAND_IDS.CHANGE_TONE]: {
enabled: true,
name: "Change tone of selection"
}
},
promptUsageTimestamps: {}
};
var EVENT_NAMES = {
CHAT_IS_VISIBLE: "chat-is-visible"
};
// src/utils.ts
var import_moment = __toESM(require_moment());
var import_obsidian = require("obsidian");
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 = async (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;
});
};
async function getTagsFromNote(file, vault) {
const fileContent = await vault.cachedRead(file);
if (fileContent.startsWith("---")) {
const frontMatterBlock = fileContent.split("---", 3);
if (frontMatterBlock.length >= 3) {
const frontMatterContent = frontMatterBlock[1];
try {
const frontMatter = (0, import_obsidian.parseYaml)(frontMatterContent) || {};
const tags = frontMatter.tags || [];
return tags.map((tag) => tag.replace("#", "")).map((tag) => tag.toLowerCase());
} catch (error) {
console.error("Error parsing YAML frontmatter:", error);
return [];
}
}
}
return [];
}
async function getNotesFromTags(vault, tags, noteFiles) {
if (tags.length === 0) {
return [];
}
tags = tags.map((tag) => tag.replace("#", ""));
const files = noteFiles && noteFiles.length > 0 ? noteFiles : await getNotesFromPath(vault, "/");
const filesWithTag = [];
for (const file of files) {
const noteTags = await getTagsFromNote(file, vault);
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 stringToChainType = (chain) => {
switch (chain) {
case "llm_chain":
return "llm_chain" /* LLM_CHAIN */;
case "vault_qa":
return "vault_qa" /* VAULT_QA_CHAIN */;
case "copilot_plus":
return "copilot_plus" /* COPILOT_PLUS */;
default:
throw new Error(`Unknown chain type: ${chain}`);
}
};
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 = (now, timezone = "local") => {
const formattedDateTime = (0, import_moment.default)(now);
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;
}
async function getAllNotesContent(vault) {
let allContent = "";
const markdownFiles = vault.getMarkdownFiles();
for (const file of markdownFiles) {
const fileContent = await vault.cachedRead(file);
allContent += fileContent + " ";
}
return allContent;
}
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 sanitizeSettings(settings) {
const sanitizedSettings = { ...settings };
const temperature = Number(settings.temperature);
sanitizedSettings.temperature = isNaN(temperature) ? DEFAULT_SETTINGS.temperature : temperature;
const maxTokens = Number(settings.maxTokens);
sanitizedSettings.maxTokens = isNaN(maxTokens) ? DEFAULT_SETTINGS.maxTokens : maxTokens;
const contextTurns = Number(settings.contextTurns);
sanitizedSettings.contextTurns = isNaN(contextTurns) ? DEFAULT_SETTINGS.contextTurns : contextTurns;
return sanitizedSettings;
}
function fixGrammarSpellingSelectionPrompt(selectedText) {
return `Please fix the grammar and spelling of the following text and return it without any other changes:
${selectedText}`;
}
function summarizePrompt(selectedText) {
return `Summarize the following text into bullet points and return it without any other changes. Identify the input language, and return the summary in the same language. If the input is English, return the summary in English. Otherwise, return in the same language as the input. Return ONLY the summary, DO NOT return the name of the language:
${selectedText}`;
}
function tocPrompt(selectedText) {
return `Please generate a table of contents for the following text and return it without any other changes. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function glossaryPrompt(selectedText) {
return `Please generate a glossary for the following text and return it without any other changes. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function simplifyPrompt(selectedText) {
return `Please simplify the following text so that a 6th-grader can understand. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function emojifyPrompt(selectedText) {
return `Please insert emojis to the following content without changing the text.Insert at as many places as possible, but don't have any 2 emojis together. The original text must be returned.
Content: ${selectedText}`;
}
function removeUrlsFromSelectionPrompt(selectedText) {
return `Please remove all URLs from the following text and return it without any other changes:
${selectedText}`;
}
function rewriteTweetSelectionPrompt(selectedText) {
return `Please rewrite the following content to under 280 characters using simple sentences. Output in the same language as the source, do not output English if it is not English. Please follow the instruction strictly. Content:
+ ${selectedText}`;
}
function rewriteTweetThreadSelectionPrompt(selectedText) {
return `Please follow the instructions closely step by step and rewrite the content to a thread. 1. Each paragraph must be under 240 characters. 2. The starting line is \`THREAD START
\`, and the ending line is \`
THREAD END\`. 3. You must use \`
---
\` to separate each paragraph! Then return it without any other changes. 4. Make it as engaging as possible.5. Output in the same language as the source, do not output English if it is not English.
The original content:
${selectedText}`;
}
function rewriteShorterSelectionPrompt(selectedText) {
return `Please rewrite the following text to make it half as long while keeping the meaning as much as possible. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function rewriteLongerSelectionPrompt(selectedText) {
return `Please rewrite the following text to make it twice as long while keeping the meaning as much as possible. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function eli5SelectionPrompt(selectedText) {
return `Please explain the following text like I'm 5 years old. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function rewritePressReleaseSelectionPrompt(selectedText) {
return `Please rewrite the following text to make it sound like a press release. Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
}
function createTranslateSelectionPrompt(language) {
return (selectedText) => {
return `Please translate the following text to ${language}:
${selectedText}`;
};
}
function createChangeToneSelectionPrompt(tone) {
return (selectedText) => {
return `Please change the tone of the following text to ${tone}. Identify the language first, then Output in the same language as the source, do not output English if it is not English:
${selectedText}`;
};
}
function extractChatHistory(memoryVariables) {
const chatHistory = [];
const { history } = memoryVariables;
for (let i4 = 0; i4 < history.length; i4 += 2) {
const userMessage = history[i4]?.content || "";
const aiMessage = history[i4 + 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((match) => match.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);
}
// src/error.ts
var CustomError = class extends Error {
constructor(msg) {
super(msg);
this.msg = msg;
}
};
// node_modules/@anthropic-ai/sdk/error.mjs
var error_exports = {};
__export(error_exports, {
APIConnectionError: () => APIConnectionError,
APIConnectionTimeoutError: () => APIConnectionTimeoutError,
APIError: () => APIError,
APIUserAbortError: () => APIUserAbortError,
AnthropicError: () => AnthropicError,
AuthenticationError: () => AuthenticationError,
BadRequestError: () => BadRequestError,
ConflictError: () => ConflictError,
InternalServerError: () => InternalServerError,
NotFoundError: () => NotFoundError,
PermissionDeniedError: () => PermissionDeniedError,
RateLimitError: () => RateLimitError,
UnprocessableEntityError: () => UnprocessableEntityError
});
// node_modules/@anthropic-ai/sdk/version.mjs
var VERSION = "0.27.3";
// node_modules/@anthropic-ai/sdk/_shims/registry.mjs
var auto = false;
var kind = void 0;
var fetch2 = void 0;
var Request2 = void 0;
var Response2 = void 0;
var Headers2 = 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 '@anthropic-ai/sdk/shims/${shims.kind}'\` before importing anything else from @anthropic-ai/sdk`);
}
if (kind) {
throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${shims.kind}'\` after \`import '@anthropic-ai/sdk/shims/${kind}'\``);
}
auto = options.auto;
kind = shims.kind;
fetch2 = shims.fetch;
Request2 = shims.Request;
Response2 = shims.Response;
Headers2 = 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/@anthropic-ai/sdk/_shims/MultipartBody.mjs
var MultipartBody = class {
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return "MultipartBody";
}
};
// node_modules/@anthropic-ai/sdk/_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 '@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 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/anthropics/anthropic-sdk-typescript#file-uploads");
},
isFsReadStream: (value) => false
};
}
// node_modules/@anthropic-ai/sdk/_shims/index.mjs
if (!kind)
setShims(getRuntime(), { auto: true });
// node_modules/@anthropic-ai/sdk/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 (sse.event === "completion") {
try {
yield JSON.parse(sse.data);
} catch (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
}
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 (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
}
if (sse.event === "ping") {
continue;
}
if (sse.event === "error") {
throw APIError.generate(void 0, `SSE Error: ${sse.data}`, sse.data, createResponseHeaders(response.headers));
}
}
done = true;
} catch (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 AnthropicError(`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 i4 = 0; i4 < buffer.length - 2; i4++) {
if (buffer[i4] === newline && buffer[i4 + 1] === newline) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === carriage) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === newline && i4 + 3 < buffer.length && buffer[i4 + 2] === carriage && buffer[i4 + 3] === newline) {
return i4 + 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] = partition(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 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 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;
}
};
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function partition(str2, delimiter) {
const index = str2.indexOf(delimiter);
if (index !== -1) {
return [str2.substring(0, index), delimiter, str2.substring(index + 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 (e4) {
reader.releaseLock();
throw e4;
}
},
async return() {
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
return { done: true, value: void 0 };
},
[Symbol.asyncIterator]() {
return this;
}
};
}
// node_modules/@anthropic-ai/sdk/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";
async function toFile(value, name2, options) {
value = await value;
if (isFileLike(value)) {
return value;
}
if (isResponseLike(value)) {
const blob = await value.blob();
name2 || (name2 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
const data = isBlobLike(blob) ? [await blob.arrayBuffer()] : [blob];
return new File2(data, name2, options);
}
const bits = await getBytes(value);
name2 || (name2 = getName(value) ?? "unknown_file");
if (!options?.type) {
const type = bits[0]?.type;
if (typeof type === "string") {
options = { ...options, type };
}
}
return new File2(bits, name2, 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((p4) => `"${p4}"`).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";
// node_modules/@anthropic-ai/sdk/core.mjs
var __classPrivateFieldSet2 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet2 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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 json;
}
const text = await response.text();
debug("response", response.status, response.url, response.headers, text);
return text;
}
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) => 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((p4) => p4.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 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 ?? fetch2;
}
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) {
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 });
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);
applyHeadersMut(reqHeaders, defaultHeaders);
applyHeadersMut(reqHeaders, headers);
if (isMultipartBody(options.body) && kind !== "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 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;
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 });
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((e4) => castToError(e4).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 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, init2, ms, controller) {
const { signal, ...options } = init2 || {};
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(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet2(this, _AbstractPage_client, client, "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 __classPrivateFieldGet2(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(client, request, Page2) {
super(request, async (props) => new Page2(client, 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, name2) {
const key = name2.toString();
return target[key.toLowerCase()] || target[key];
}
});
};
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 match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[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 = (platform) => {
platform = platform.toLowerCase();
if (platform.includes("ios"))
return "iOS";
if (platform === "android")
return "Android";
if (platform === "darwin")
return "MacOS";
if (platform === "win32")
return "Windows";
if (platform === "freebsd")
return "FreeBSD";
if (platform === "openbsd")
return "OpenBSD";
if (platform === "linux")
return "Linux";
if (platform)
return `Other:${platform}`;
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 = (name2, n4) => {
if (typeof n4 !== "number" || !Number.isInteger(n4)) {
throw new AnthropicError(`${name2} must be an integer`);
}
if (n4 < 0) {
throw new AnthropicError(`${name2} must be a positive integer`);
}
return n4;
};
var castToError = (err) => {
if (err instanceof Error)
return err;
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(`Anthropic:DEBUG:${action}`, ...args);
}
}
var uuid4 = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c5) => {
const r4 = Math.random() * 16 | 0;
const v6 = c5 === "x" ? r4 : r4 & 3 | 8;
return v6.toString(16);
});
};
var isRunningInBrowser = () => {
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 APIError = class extends AnthropicError {
constructor(status, error, message, headers) {
super(`${APIError.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 APIConnectionError({ message, cause: castToError(errorResponse) });
}
const error = errorResponse;
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 {
};
// node_modules/@anthropic-ai/sdk/resource.mjs
var APIResource = class {
constructor(client) {
this._client = client;
}
};
// node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
var tokenize = (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 partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
// node_modules/@anthropic-ai/sdk/lib/PromptCachingBetaMessageStream.mjs
var __classPrivateFieldSet3 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet3 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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) => {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_errored, true, "f");
if (error instanceof Error && error.name === "AbortError") {
error = new APIUserAbortError();
}
if (error instanceof APIUserAbortError) {
__classPrivateFieldSet3(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)));
});
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_resolveConnectedPromise, resolve, "f");
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, reject, "f");
}), "f");
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_endPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_resolveEndPromise, resolve, "f");
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_rejectEndPromise, reject, "f");
}), "f");
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_connectedPromise, "f").catch(() => {
});
__classPrivateFieldGet3(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");
}, __classPrivateFieldGet3(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());
}
__classPrivateFieldGet3(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) {
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_endRequest).call(this);
}
_connected() {
if (this.ended)
return;
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_resolveConnectedPromise, "f").call(this);
this._emit("connect");
}
get ended() {
return __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_ended, "f");
}
get errored() {
return __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_errored, "f");
}
get aborted() {
return __classPrivateFieldGet3(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 = __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet3(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 = __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_listeners, "f")[event];
if (!listeners)
return this;
const index = listeners.findIndex((l4) => l4.listener === listener);
if (index >= 0)
listeners.splice(index, 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 = __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet3(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) => {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, true, "f");
if (event !== "error")
this.once("error", reject);
this.once(event, resolve);
});
}
async done() {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, true, "f");
await __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_endPromise, "f");
}
get currentMessage() {
return __classPrivateFieldGet3(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 __classPrivateFieldGet3(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 __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_getFinalText).call(this);
}
_emit(event, ...args) {
if (__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_ended, "f"))
return;
if (event === "end") {
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_ended, true, "f");
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_resolveEndPromise, "f").call(this);
}
const listeners = __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_listeners, "f")[event];
if (listeners) {
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
listeners.forEach(({ listener }) => listener(...args));
}
if (event === "abort") {
const error = args[0];
if (!__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_rejectEndPromise, "f").call(this, error);
this._emit("end");
return;
}
if (event === "error") {
const error = args[0];
if (!__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_rejectEndPromise, "f").call(this, error);
this._emit("end");
}
}
_emitFinal() {
const finalPromptCachingBetaMessage = this.receivedMessages.at(-1);
if (finalPromptCachingBetaMessage) {
this._emit("finalPromptCachingBetaMessage", __classPrivateFieldGet3(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());
}
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_beginRequest).call(this);
this._connected();
const stream = Stream.fromReadableStream(readableStream, this.controller);
for await (const event of stream) {
__classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_instances, "m", _PromptCachingBetaMessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet3(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;
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, void 0, "f");
}, _PromptCachingBetaMessageStream_addStreamEvent = function _PromptCachingBetaMessageStream_addStreamEvent2(event) {
if (this.ended)
return;
const messageSnapshot = __classPrivateFieldGet3(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": {
__classPrivateFieldSet3(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 = __classPrivateFieldGet3(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, "f");
if (!snapshot) {
throw new AnthropicError(`request ended without sending any chunks`);
}
__classPrivateFieldSet3(this, _PromptCachingBetaMessageStream_currentMessageSnapshot, void 0, "f");
return snapshot;
}, _PromptCachingBetaMessageStream_accumulateMessage = function _PromptCachingBetaMessageStream_accumulateMessage2(event) {
let snapshot = __classPrivateFieldGet3(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 = partialParse(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 Stream(this[Symbol.asyncIterator].bind(this), this.controller);
return stream.toReadableStream();
}
};
// node_modules/@anthropic-ai/sdk/resources/beta/prompt-caching/messages.mjs
var Messages = class extends APIResource {
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) {
})(Messages || (Messages = {}));
// node_modules/@anthropic-ai/sdk/resources/beta/prompt-caching/prompt-caching.mjs
var PromptCaching = class extends APIResource {
constructor() {
super(...arguments);
this.messages = new Messages(this._client);
}
};
(function(PromptCaching2) {
PromptCaching2.Messages = Messages;
})(PromptCaching || (PromptCaching = {}));
// node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
var Beta = class extends APIResource {
constructor() {
super(...arguments);
this.promptCaching = new PromptCaching(this._client);
}
};
(function(Beta3) {
Beta3.PromptCaching = PromptCaching;
})(Beta || (Beta = {}));
// node_modules/@anthropic-ai/sdk/resources/completions.mjs
var Completions = class extends APIResource {
create(body, options) {
return this._client.post("/v1/complete", {
body,
timeout: this._client._options.timeout ?? 6e5,
...options,
stream: body.stream ?? false
});
}
};
(function(Completions7) {
})(Completions || (Completions = {}));
// node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
var __classPrivateFieldSet4 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet4 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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) => {
__classPrivateFieldSet4(this, _MessageStream_errored, true, "f");
if (error instanceof Error && error.name === "AbortError") {
error = new APIUserAbortError();
}
if (error instanceof APIUserAbortError) {
__classPrivateFieldSet4(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)));
});
__classPrivateFieldSet4(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet4(this, _MessageStream_resolveConnectedPromise, resolve, "f");
__classPrivateFieldSet4(this, _MessageStream_rejectConnectedPromise, reject, "f");
}), "f");
__classPrivateFieldSet4(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet4(this, _MessageStream_resolveEndPromise, resolve, "f");
__classPrivateFieldSet4(this, _MessageStream_rejectEndPromise, reject, "f");
}), "f");
__classPrivateFieldGet4(this, _MessageStream_connectedPromise, "f").catch(() => {
});
__classPrivateFieldGet4(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");
}, __classPrivateFieldGet4(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());
}
__classPrivateFieldGet4(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) {
__classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
}
_connected() {
if (this.ended)
return;
__classPrivateFieldGet4(this, _MessageStream_resolveConnectedPromise, "f").call(this);
this._emit("connect");
}
get ended() {
return __classPrivateFieldGet4(this, _MessageStream_ended, "f");
}
get errored() {
return __classPrivateFieldGet4(this, _MessageStream_errored, "f");
}
get aborted() {
return __classPrivateFieldGet4(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 = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet4(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 = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event];
if (!listeners)
return this;
const index = listeners.findIndex((l4) => l4.listener === listener);
if (index >= 0)
listeners.splice(index, 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 = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet4(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) => {
__classPrivateFieldSet4(this, _MessageStream_catchingPromiseCreated, true, "f");
if (event !== "error")
this.once("error", reject);
this.once(event, resolve);
});
}
async done() {
__classPrivateFieldSet4(this, _MessageStream_catchingPromiseCreated, true, "f");
await __classPrivateFieldGet4(this, _MessageStream_endPromise, "f");
}
get currentMessage() {
return __classPrivateFieldGet4(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 __classPrivateFieldGet4(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 __classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
}
_emit(event, ...args) {
if (__classPrivateFieldGet4(this, _MessageStream_ended, "f"))
return;
if (event === "end") {
__classPrivateFieldSet4(this, _MessageStream_ended, true, "f");
__classPrivateFieldGet4(this, _MessageStream_resolveEndPromise, "f").call(this);
}
const listeners = __classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event];
if (listeners) {
__classPrivateFieldGet4(this, _MessageStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
listeners.forEach(({ listener }) => listener(...args));
}
if (event === "abort") {
const error = args[0];
if (!__classPrivateFieldGet4(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet4(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet4(this, _MessageStream_rejectEndPromise, "f").call(this, error);
this._emit("end");
return;
}
if (event === "error") {
const error = args[0];
if (!__classPrivateFieldGet4(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet4(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet4(this, _MessageStream_rejectEndPromise, "f").call(this, error);
this._emit("end");
}
}
_emitFinal() {
const finalMessage = this.receivedMessages.at(-1);
if (finalMessage) {
this._emit("finalMessage", __classPrivateFieldGet4(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());
}
__classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
this._connected();
const stream = Stream.fromReadableStream(readableStream, this.controller);
for await (const event of stream) {
__classPrivateFieldGet4(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet4(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;
__classPrivateFieldSet4(this, _MessageStream_currentMessageSnapshot, void 0, "f");
}, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
if (this.ended)
return;
const messageSnapshot = __classPrivateFieldGet4(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": {
__classPrivateFieldSet4(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 = __classPrivateFieldGet4(this, _MessageStream_currentMessageSnapshot, "f");
if (!snapshot) {
throw new AnthropicError(`request ended without sending any chunks`);
}
__classPrivateFieldSet4(this, _MessageStream_currentMessageSnapshot, void 0, "f");
return snapshot;
}, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
let snapshot = __classPrivateFieldGet4(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 = partialParse(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 Stream(this[Symbol.asyncIterator].bind(this), this.controller);
return stream.toReadableStream();
}
};
// node_modules/@anthropic-ai/sdk/resources/messages.mjs
var Messages2 = class extends APIResource {
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) {
})(Messages2 || (Messages2 = {}));
// node_modules/@anthropic-ai/sdk/index.mjs
var _a;
var Anthropic = class extends APIClient {
/**
* 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 = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) {
const options = {
apiKey,
authToken,
...opts,
baseURL: baseURL || `https://api.anthropic.com`
};
if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
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 Completions(this);
this.messages = new Messages2(this);
this.beta = new Beta(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 && !isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
if (bearerAuth != null && !isEmptyObj(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}` };
}
};
_a = Anthropic;
Anthropic.Anthropic = _a;
Anthropic.HUMAN_PROMPT = "\n\nHuman:";
Anthropic.AI_PROMPT = "\n\nAssistant:";
Anthropic.DEFAULT_TIMEOUT = 6e5;
Anthropic.AnthropicError = AnthropicError;
Anthropic.APIError = APIError;
Anthropic.APIConnectionError = APIConnectionError;
Anthropic.APIConnectionTimeoutError = APIConnectionTimeoutError;
Anthropic.APIUserAbortError = APIUserAbortError;
Anthropic.NotFoundError = NotFoundError;
Anthropic.ConflictError = ConflictError;
Anthropic.RateLimitError = RateLimitError;
Anthropic.BadRequestError = BadRequestError;
Anthropic.AuthenticationError = AuthenticationError;
Anthropic.InternalServerError = InternalServerError;
Anthropic.PermissionDeniedError = PermissionDeniedError;
Anthropic.UnprocessableEntityError = UnprocessableEntityError;
Anthropic.toFile = toFile;
Anthropic.fileFromPath = fileFromPath;
var { HUMAN_PROMPT, AI_PROMPT } = Anthropic;
var { AnthropicError: AnthropicError2, APIError: APIError2, APIConnectionError: APIConnectionError2, APIConnectionTimeoutError: APIConnectionTimeoutError2, APIUserAbortError: APIUserAbortError2, NotFoundError: NotFoundError2, ConflictError: ConflictError2, RateLimitError: RateLimitError2, BadRequestError: BadRequestError2, AuthenticationError: AuthenticationError2, InternalServerError: InternalServerError2, PermissionDeniedError: PermissionDeniedError2, UnprocessableEntityError: UnprocessableEntityError2 } = error_exports;
(function(Anthropic2) {
Anthropic2.Completions = Completions;
Anthropic2.Messages = Messages2;
Anthropic2.Beta = Beta;
})(Anthropic || (Anthropic = {}));
// node_modules/@langchain/core/messages.js
init_messages2();
// node_modules/@langchain/anthropic/dist/chat_models.js
init_outputs2();
// node_modules/@langchain/core/utils/env.js
init_env();
// node_modules/@langchain/core/dist/language_models/chat_models.js
init_esm();
init_messages2();
init_outputs();
init_base8();
init_manager();
init_base4();
init_event_stream();
init_log_stream();
init_stream();
init_passthrough();
// node_modules/@langchain/core/dist/utils/types/is_zod_schema.js
function isZodSchema(input) {
return typeof input?.parse === "function";
}
// node_modules/@langchain/core/dist/language_models/chat_models.js
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()]
});
}
_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) {
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;
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);
}
}
} 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]]
})));
}
}
getLsParams(options) {
return {
ls_model_type: "chat",
ls_stop: options.stop
};
}
/** @ignore */
async _generateUncached(messages, 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 generations = [];
const llmOutputs = [];
const hasStreamingHandler = !!runManagers?.[0].handlers.find((handler) => {
return isStreamEventsHandler(handler) || isLogStreamHandler(handler);
});
if (hasStreamingHandler && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) {
try {
const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]);
let aggregated;
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 (aggregated === void 0) {
throw new Error("Received empty response from chat model call.");
}
generations.push([aggregated]);
await runManagers?.[0].handleLLMEnd({
generations,
llmOutput: {}
});
} catch (e4) {
await runManagers?.[0].handleLLMError(e4);
throw e4;
}
} else {
const results = await Promise.allSettled(baseMessages.map((messageList, i4) => this._generate(messageList, { ...parsedOptions, promptIndex: i4 }, runManagers?.[i4])));
await Promise.all(results.map(async (pResult, i4) => {
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[i4] = result.generations;
llmOutputs[i4] = result.llmOutput;
return runManagers?.[i4]?.handleLLMEnd({
generations: [result.generations],
llmOutput: result.llmOutput
});
} else {
await runManagers?.[i4]?.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,
cached: true
};
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, index) => {
const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();
const result = await cache2.lookup(prompt, llmStringKey);
if (result == null) {
missingPromptIndices.push(index);
}
return result;
}));
const cachedResults = results.map((result, index) => ({ result, runManager: runManagers?.[index] })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected");
const generations = [];
await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i4) => {
if (promiseResult.status === "fulfilled") {
const result = promiseResult.value;
generations[i4] = result;
if (result.length) {
await runManager?.handleLLMNewToken(result[0].text);
}
return runManager?.handleLLMEnd({
generations: [result]
});
} else {
await runManager?.handleLLMError(promiseResult.reason);
return Promise.reject(promiseResult.reason);
}
}));
const output = {
generations,
missingPromptIndices
};
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 } = 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((i4) => baseMessages[i4]), callOptions, runnableConfig);
await Promise.all(results.generations.map(async (generation, index) => {
const promptIndex = missingPromptIndices[index];
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.`);
}
const schema = outputSchema;
const name2 = 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 = name2 ?? "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/anthropic/dist/chat_models.js
init_base9();
init_esm();
init_runnables2();
// node_modules/@langchain/core/dist/utils/function_calling.js
init_esm();
init_base4();
function convertToOpenAIFunction(tool, fields) {
const fieldsCopy = typeof fields === "number" ? void 0 : fields;
return {
name: tool.name,
description: tool.description,
parameters: zodToJsonSchema(tool.schema),
// Do not include the `strict` field if it is `undefined`.
...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {}
};
}
function convertToOpenAITool(tool, fields) {
const fieldsCopy = typeof fields === "number" ? void 0 : fields;
let toolDef;
if (isLangChainTool(tool)) {
toolDef = {
type: "function",
function: convertToOpenAIFunction(tool)
};
} else {
toolDef = tool;
}
if (fieldsCopy?.strict !== void 0) {
toolDef.function.strict = fieldsCopy.strict;
}
return toolDef;
}
function isStructuredTool(tool) {
return tool !== void 0 && Array.isArray(tool.lc_namespace);
}
function isRunnableToolLike(tool) {
return tool !== void 0 && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike";
}
function isStructuredToolParams(tool) {
return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && // eslint-disable-next-line @typescript-eslint/no-explicit-any
isZodSchema(tool.schema);
}
function isLangChainTool(tool) {
return isStructuredToolParams(tool) || isRunnableToolLike(tool) || // eslint-disable-next-line @typescript-eslint/no-explicit-any
isStructuredTool(tool);
}
// 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 (e4) {
throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e4.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 tool2 = extractToolCalls(message.content)[0];
return tool2;
});
if (tools[0] === void 0) {
throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");
}
const [tool] = tools;
const validatedResult = await this._validateResult(tool.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((c5) => c5.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((c5) => c5.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 match = imageUrl.match(regex2);
if (match === 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: match[1] ?? "",
data: match[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((t4) => t4 === contentPart.type) && "text" in contentPart) {
return {
type: "text",
text: contentPart.text,
...cacheControl ? { cache_control: cacheControl } : {}
};
} else if (toolTypes.find((t4) => t4 === 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(tool) {
return "input_schema" in tool;
}
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 ?? getEnvironmentVariable("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((tool) => {
if (isAnthropicTool(tool)) {
return tool;
}
if (isOpenAITool(tool)) {
return {
name: tool.function.name,
description: tool.function.description,
input_schema: tool.function.parameters
};
}
if (isLangChainTool(tool)) {
return {
name: tool.name,
description: tool.description,
input_schema: zodToJsonSchema(tool.schema)
};
}
throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, 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 name2 = 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 = name2 ?? "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/openai/error.mjs
var error_exports2 = {};
__export(error_exports2, {
APIConnectionError: () => APIConnectionError3,
APIConnectionTimeoutError: () => APIConnectionTimeoutError3,
APIError: () => APIError3,
APIUserAbortError: () => APIUserAbortError3,
AuthenticationError: () => AuthenticationError3,
BadRequestError: () => BadRequestError3,
ConflictError: () => ConflictError3,
ContentFilterFinishReasonError: () => ContentFilterFinishReasonError,
InternalServerError: () => InternalServerError3,
LengthFinishReasonError: () => LengthFinishReasonError,
NotFoundError: () => NotFoundError3,
OpenAIError: () => OpenAIError,
PermissionDeniedError: () => PermissionDeniedError3,
RateLimitError: () => RateLimitError3,
UnprocessableEntityError: () => UnprocessableEntityError3
});
// node_modules/openai/version.mjs
var VERSION2 = "4.65.0";
// node_modules/openai/_shims/registry.mjs
var auto2 = false;
var kind2 = void 0;
var fetch3 = void 0;
var Request3 = void 0;
var Response3 = void 0;
var Headers3 = 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 'openai/shims/${shims.kind}'\` before importing anything else from openai`);
}
if (kind2) {
throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind2}'\``);
}
auto2 = options.auto;
kind2 = shims.kind;
fetch3 = shims.fetch;
Request3 = shims.Request;
Response3 = shims.Response;
Headers3 = 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/openai/_shims/MultipartBody.mjs
var MultipartBody2 = class {
constructor(body) {
this.body = body;
}
get [Symbol.toStringTag]() {
return "MultipartBody";
}
};
// node_modules/openai/_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 '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 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/openai/openai-node#file-uploads");
},
isFsReadStream: (value) => false
};
}
// node_modules/openai/_shims/index.mjs
if (!kind2)
setShims2(getRuntime2(), { auto: true });
// node_modules/openai/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 (done)
continue;
if (sse.data.startsWith("[DONE]")) {
done = true;
continue;
}
if (sse.event === null) {
let data;
try {
data = JSON.parse(sse.data);
} catch (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
if (data && data.error) {
throw new APIError3(void 0, data.error, void 0, void 0);
}
yield data;
} else {
let data;
try {
data = JSON.parse(sse.data);
} catch (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
if (sse.event == "error") {
throw new APIError3(void 0, data.error, data.message, void 0);
}
yield { event: sse.event, data };
}
}
done = true;
} catch (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 OpenAIError(`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 i4 = 0; i4 < buffer.length - 2; i4++) {
if (buffer[i4] === newline && buffer[i4 + 1] === newline) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === carriage) {
return i4 + 2;
}
if (buffer[i4] === carriage && buffer[i4 + 1] === newline && i4 + 3 < buffer.length && buffer[i4 + 2] === carriage && buffer[i4 + 3] === newline) {
return i4 + 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] = 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;
}
};
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 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;
}
};
LineDecoder2.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function partition2(str2, delimiter) {
const index = str2.indexOf(delimiter);
if (index !== -1) {
return [str2.substring(0, index), delimiter, str2.substring(index + 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 (e4) {
reader.releaseLock();
throw e4;
}
},
async return() {
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
return { done: true, value: void 0 };
},
[Symbol.asyncIterator]() {
return this;
}
};
}
// node_modules/openai/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";
var isUploadable = (value) => {
return isFileLike2(value) || isResponseLike2(value) || isFsReadStream2(value);
};
async function toFile2(value, name2, options) {
value = await value;
if (isFileLike2(value)) {
return value;
}
if (isResponseLike2(value)) {
const blob = await value.blob();
name2 || (name2 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
const data = isBlobLike2(blob) ? [await blob.arrayBuffer()] : [blob];
return new File3(data, name2, options);
}
const bits = await getBytes2(value);
name2 || (name2 = getName2(value) ?? "unknown_file");
if (!options?.type) {
const type = bits[0]?.type;
if (typeof type === "string") {
options = { ...options, type };
}
}
return new File3(bits, name2, 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((p4) => `"${p4}"`).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";
var multipartFormRequestOptions = async (opts) => {
const form = await createForm(opts.body);
return getMultipartRequestOptions2(form, opts);
};
var createForm = async (body) => {
const form = new FormData3();
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 toFile2(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(([name2, prop]) => addFormValue(form, `${key}[${name2}]`, 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 __classPrivateFieldSet5 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet5 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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 _addRequestID(json, response);
}
const text = await response.text();
debug2("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 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) => _addRequestID(transform(await this.parseResponse(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((p4) => p4.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 '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 };
}
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 ?? 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(),
...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, { retryCount = 0 } = {}) {
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, 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);
applyHeadersMut2(reqHeaders, defaultHeaders);
applyHeadersMut2(reqHeaders, headers);
if (isMultipartBody2(options.body) && kind2 !== "node") {
delete reqHeaders["content-type"];
}
if (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 APIError3.generate(status, error, message, headers);
}
request(options, remainingRetries = null) {
return new APIPromise2(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 });
debug2("request", url, options, req.headers);
if (options.signal?.aborted) {
throw new APIUserAbortError3();
}
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 APIUserAbortError3();
}
if (retriesRemaining) {
return this.retryRequest(options, retriesRemaining);
}
if (response.name === "AbortError") {
throw new APIConnectionTimeoutError3();
}
throw new APIConnectionError3({ 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((e4) => castToError2(e4).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 (!isEmptyObj2(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, init2, ms, controller) {
const { signal, ...options } = init2 || {};
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(client, response, body, options) {
_AbstractPage_client2.set(this, void 0);
__classPrivateFieldSet5(this, _AbstractPage_client2, client, "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 __classPrivateFieldGet5(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(client, request, Page2) {
super(request, async (props) => new Page2(client, 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, name2) {
const key = name2.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 && !isEmptyObj2(obj) && Object.keys(obj).every((k3) => hasOwn2(requestOptionsKeys, k3));
};
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 match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[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 = (platform) => {
platform = platform.toLowerCase();
if (platform.includes("ios"))
return "iOS";
if (platform === "android")
return "Android";
if (platform === "darwin")
return "MacOS";
if (platform === "win32")
return "Windows";
if (platform === "freebsd")
return "FreeBSD";
if (platform === "openbsd")
return "OpenBSD";
if (platform === "linux")
return "Linux";
if (platform)
return `Other:${platform}`;
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 = (name2, n4) => {
if (typeof n4 !== "number" || !Number.isInteger(n4)) {
throw new OpenAIError(`${name2} must be an integer`);
}
if (n4 < 0) {
throw new OpenAIError(`${name2} must be a positive integer`);
}
return n4;
};
var castToError2 = (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 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 isEmptyObj2(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(`OpenAI:DEBUG:${action}`, ...args);
}
}
var uuid42 = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c5) => {
const r4 = Math.random() * 16 | 0;
const v6 = c5 === "x" ? r4 : r4 & 3 | 8;
return v6.toString(16);
});
};
var isRunningInBrowser2 = () => {
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/error.mjs
var OpenAIError = class extends Error {
};
var APIError3 = class extends OpenAIError {
constructor(status, error, message, headers) {
super(`${APIError3.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 APIConnectionError3({ message, cause: castToError2(errorResponse) });
}
const error = errorResponse?.["error"];
if (status === 400) {
return new BadRequestError3(status, error, message, headers);
}
if (status === 401) {
return new AuthenticationError3(status, error, message, headers);
}
if (status === 403) {
return new PermissionDeniedError3(status, error, message, headers);
}
if (status === 404) {
return new NotFoundError3(status, error, message, headers);
}
if (status === 409) {
return new ConflictError3(status, error, message, headers);
}
if (status === 422) {
return new UnprocessableEntityError3(status, error, message, headers);
}
if (status === 429) {
return new RateLimitError3(status, error, message, headers);
}
if (status >= 500) {
return new InternalServerError3(status, error, message, headers);
}
return new APIError3(status, error, message, headers);
}
};
var APIUserAbortError3 = class extends APIError3 {
constructor({ message } = {}) {
super(void 0, void 0, message || "Request was aborted.", void 0);
this.status = void 0;
}
};
var APIConnectionError3 = class extends APIError3 {
constructor({ message, cause }) {
super(void 0, void 0, message || "Connection error.", void 0);
this.status = void 0;
if (cause)
this.cause = cause;
}
};
var APIConnectionTimeoutError3 = class extends APIConnectionError3 {
constructor({ message } = {}) {
super({ message: message ?? "Request timed out." });
}
};
var BadRequestError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 400;
}
};
var AuthenticationError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 401;
}
};
var PermissionDeniedError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 403;
}
};
var NotFoundError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 404;
}
};
var ConflictError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 409;
}
};
var UnprocessableEntityError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 422;
}
};
var RateLimitError3 = class extends APIError3 {
constructor() {
super(...arguments);
this.status = 429;
}
};
var InternalServerError3 = class extends APIError3 {
};
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/qs/formats.mjs
var default_format = "RFC3986";
var formatters = {
RFC1738: (v6) => String(v6).replace(/%20/g, "+"),
RFC3986: (v6) => String(v6)
};
var RFC1738 = "RFC1738";
// node_modules/openai/internal/qs/utils.mjs
var is_array = Array.isArray;
var hex_table = (() => {
const array = [];
for (let i4 = 0; i4 < 256; ++i4) {
array.push("%" + ((i4 < 16 ? "0" : "") + i4.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 i4 = 0; i4 < segment.length; ++i4) {
let c5 = segment.charCodeAt(i4);
if (c5 === 45 || // -
c5 === 46 || // .
c5 === 95 || // _
c5 === 126 || // ~
c5 >= 48 && c5 <= 57 || // 0-9
c5 >= 65 && c5 <= 90 || // a-z
c5 >= 97 && c5 <= 122 || // A-Z
format === RFC1738 && (c5 === 40 || c5 === 41)) {
arr2[arr2.length] = segment.charAt(i4);
continue;
}
if (c5 < 128) {
arr2[arr2.length] = hex_table[c5];
continue;
}
if (c5 < 2048) {
arr2[arr2.length] = hex_table[192 | c5 >> 6] + hex_table[128 | c5 & 63];
continue;
}
if (c5 < 55296 || c5 >= 57344) {
arr2[arr2.length] = hex_table[224 | c5 >> 12] + hex_table[128 | c5 >> 6 & 63] + hex_table[128 | c5 & 63];
continue;
}
i4 += 1;
c5 = 65536 + ((c5 & 1023) << 10 | segment.charCodeAt(i4) & 1023);
arr2[arr2.length] = hex_table[240 | c5 >> 18] + hex_table[128 | c5 >> 12 & 63] + hex_table[128 | c5 >> 6 & 63] + hex_table[128 | c5 & 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 i4 = 0; i4 < val2.length; i4 += 1) {
mapped.push(fn(val2[i4]));
}
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(v6) {
return typeof v6 === "string" || typeof v6 === "number" || typeof v6 === "boolean" || typeof v6 === "symbol" || typeof v6 === "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 i4 = 0; i4 < obj_keys.length; ++i4) {
const key = obj_keys[i4];
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/pagination.mjs
var Page = class extends AbstractPage2 {
constructor(client, response, body, options) {
super(client, 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 AbstractPage2 {
constructor(client, response, body, options) {
super(client, 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 APIResource2 = class {
constructor(client) {
this._client = client;
}
};
// node_modules/openai/resources/chat/completions.mjs
var Completions2 = class extends APIResource2 {
create(body, options) {
return this._client.post("/chat/completions", { body, ...options, stream: body.stream ?? false });
}
};
(function(Completions7) {
})(Completions2 || (Completions2 = {}));
// node_modules/openai/resources/chat/chat.mjs
var Chat = class extends APIResource2 {
constructor() {
super(...arguments);
this.completions = new Completions2(this._client);
}
};
(function(Chat5) {
Chat5.Completions = Completions2;
})(Chat || (Chat = {}));
// node_modules/openai/resources/audio/speech.mjs
var Speech = class extends APIResource2 {
/**
* Generates audio from the input text.
*/
create(body, options) {
return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true });
}
};
(function(Speech2) {
})(Speech || (Speech = {}));
// node_modules/openai/resources/audio/transcriptions.mjs
var Transcriptions = class extends APIResource2 {
/**
* Transcribes audio into the input language.
*/
create(body, options) {
return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ body, ...options }));
}
};
(function(Transcriptions3) {
})(Transcriptions || (Transcriptions = {}));
// node_modules/openai/resources/audio/translations.mjs
var Translations = class extends APIResource2 {
/**
* Translates audio into English.
*/
create(body, options) {
return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options }));
}
};
(function(Translations3) {
})(Translations || (Translations = {}));
// node_modules/openai/resources/audio/audio.mjs
var Audio = class extends APIResource2 {
constructor() {
super(...arguments);
this.transcriptions = new Transcriptions(this._client);
this.translations = new Translations(this._client);
this.speech = new Speech(this._client);
}
};
(function(Audio3) {
Audio3.Transcriptions = Transcriptions;
Audio3.Translations = Translations;
Audio3.Speech = Speech;
})(Audio || (Audio = {}));
// node_modules/openai/resources/batches.mjs
var Batches = class extends APIResource2 {
/**
* 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 {
};
(function(Batches2) {
Batches2.BatchesPage = BatchesPage;
})(Batches || (Batches = {}));
// node_modules/openai/resources/beta/assistants.mjs
var Assistants = class extends APIResource2 {
/**
* 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 {
};
(function(Assistants2) {
Assistants2.AssistantsPage = AssistantsPage;
})(Assistants || (Assistants = {}));
// 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 isToolMessage = (message) => {
return message?.role === "tool";
};
// node_modules/openai/lib/EventStream.mjs
var __classPrivateFieldSet6 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet6 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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);
__classPrivateFieldSet6(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet6(this, _EventStream_resolveConnectedPromise, resolve, "f");
__classPrivateFieldSet6(this, _EventStream_rejectConnectedPromise, reject, "f");
}), "f");
__classPrivateFieldSet6(this, _EventStream_endPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet6(this, _EventStream_resolveEndPromise, resolve, "f");
__classPrivateFieldSet6(this, _EventStream_rejectEndPromise, reject, "f");
}), "f");
__classPrivateFieldGet6(this, _EventStream_connectedPromise, "f").catch(() => {
});
__classPrivateFieldGet6(this, _EventStream_endPromise, "f").catch(() => {
});
}
_run(executor) {
setTimeout(() => {
executor().then(() => {
this._emitFinal();
this._emit("end");
}, __classPrivateFieldGet6(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
}, 0);
}
_connected() {
if (this.ended)
return;
__classPrivateFieldGet6(this, _EventStream_resolveConnectedPromise, "f").call(this);
this._emit("connect");
}
get ended() {
return __classPrivateFieldGet6(this, _EventStream_ended, "f");
}
get errored() {
return __classPrivateFieldGet6(this, _EventStream_errored, "f");
}
get aborted() {
return __classPrivateFieldGet6(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 = __classPrivateFieldGet6(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet6(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 = __classPrivateFieldGet6(this, _EventStream_listeners, "f")[event];
if (!listeners)
return this;
const index = listeners.findIndex((l4) => l4.listener === listener);
if (index >= 0)
listeners.splice(index, 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 = __classPrivateFieldGet6(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet6(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) => {
__classPrivateFieldSet6(this, _EventStream_catchingPromiseCreated, true, "f");
if (event !== "error")
this.once("error", reject);
this.once(event, resolve);
});
}
async done() {
__classPrivateFieldSet6(this, _EventStream_catchingPromiseCreated, true, "f");
await __classPrivateFieldGet6(this, _EventStream_endPromise, "f");
}
_emit(event, ...args) {
if (__classPrivateFieldGet6(this, _EventStream_ended, "f")) {
return;
}
if (event === "end") {
__classPrivateFieldSet6(this, _EventStream_ended, true, "f");
__classPrivateFieldGet6(this, _EventStream_resolveEndPromise, "f").call(this);
}
const listeners = __classPrivateFieldGet6(this, _EventStream_listeners, "f")[event];
if (listeners) {
__classPrivateFieldGet6(this, _EventStream_listeners, "f")[event] = listeners.filter((l4) => !l4.once);
listeners.forEach(({ listener }) => listener(...args));
}
if (event === "abort") {
const error = args[0];
if (!__classPrivateFieldGet6(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet6(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet6(this, _EventStream_rejectEndPromise, "f").call(this, error);
this._emit("end");
return;
}
if (event === "error") {
const error = args[0];
if (!__classPrivateFieldGet6(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet6(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet6(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) {
__classPrivateFieldSet6(this, _EventStream_errored, true, "f");
if (error instanceof Error && error.name === "AbortError") {
error = new APIUserAbortError3();
}
if (error instanceof APIUserAbortError3) {
__classPrivateFieldSet6(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(tool, { parser, callback }) {
const obj = { ...tool };
Object.defineProperties(obj, {
$brand: {
value: "auto-parseable-tool",
enumerable: false
},
$parseRaw: {
value: parser,
enumerable: false
},
$callback: {
value: callback,
enumerable: false
}
});
return obj;
}
function isAutoParsableTool(tool) {
return tool?.["$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((t4) => isAutoParsableTool(t4) || t4.type === "function" && t4.function.strict === true) ?? false;
}
function validateInputTools(tools) {
for (const tool of tools ?? []) {
if (tool.type !== "function") {
throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);
}
if (tool.function.strict !== true) {
throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
}
}
}
// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
var __classPrivateFieldGet7 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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) || isToolMessage(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 __classPrivateFieldGet7(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 __classPrivateFieldGet7(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 __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
}
async finalFunctionCallResult() {
await this.done();
return __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
}
async totalUsage() {
await this.done();
return __classPrivateFieldGet7(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 = __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
if (finalMessage)
this._emit("finalMessage", finalMessage);
const finalContent = __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
if (finalContent)
this._emit("finalContent", finalContent);
const finalFunctionCall = __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);
if (finalFunctionCall)
this._emit("finalFunctionCall", finalFunctionCall);
const finalFunctionCallResult = __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);
if (finalFunctionCallResult != null)
this._emit("finalFunctionCallResult", finalFunctionCallResult);
if (this._chatCompletions.some((c5) => c5.usage)) {
this._emit("totalUsage", __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
}
}
async _createChatCompletion(client, params, options) {
const signal = options?.signal;
if (signal) {
if (signal.aborted)
this.controller.abort();
signal.addEventListener("abort", () => this.controller.abort());
}
__classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
this._connected();
return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
}
async _runChatCompletion(client, params, options) {
for (const message of params.messages) {
this._addMessage(message, false);
}
return await this._createChatCompletion(client, params, options);
}
async _runFunctions(client, 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 f4 of params.functions) {
functionsByName[f4.name || f4.function.name] = f4;
}
const functions = params.functions.map((f4) => ({
name: f4.name || f4.function.name,
parameters: f4.parameters,
description: f4.description
}));
for (const message of params.messages) {
this._addMessage(message, false);
}
for (let i4 = 0; i4 < maxChatCompletions; ++i4) {
const chatCompletion = await this._createChatCompletion(client, {
...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: name2, arguments: args } = message.function_call;
const fn = functionsByName[name2];
if (!fn) {
const content2 = `Invalid function_call: ${JSON.stringify(name2)}. Available options are: ${functions.map((f4) => JSON.stringify(f4.name)).join(", ")}. Please try again`;
this._addMessage({ role, name: name2, content: content2 });
continue;
} else if (singleFunctionToCall && singleFunctionToCall !== name2) {
const content2 = `Invalid function_call: ${JSON.stringify(name2)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
this._addMessage({ role, name: name2, content: content2 });
continue;
}
let parsed;
try {
parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
} catch (error) {
this._addMessage({
role,
name: name2,
content: error instanceof Error ? error.message : String(error)
});
continue;
}
const rawContent = await fn.function(parsed, this);
const content = __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
this._addMessage({ role, name: name2, content });
if (singleFunctionToCall)
return;
}
}
async _runTools(client, 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((tool) => {
if (isAutoParsableTool(tool)) {
if (!tool.$callback) {
throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
}
return {
type: "function",
function: {
function: tool.$callback,
name: tool.function.name,
description: tool.function.description || "",
parameters: tool.function.parameters,
parse: tool.$parseRaw,
strict: true
}
};
}
return tool;
});
const functionsByName = {};
for (const f4 of inputTools) {
if (f4.type === "function") {
functionsByName[f4.function.name || f4.function.function.name] = f4.function;
}
}
const tools = "tools" in params ? inputTools.map((t4) => t4.type === "function" ? {
type: "function",
function: {
name: t4.function.name || t4.function.function.name,
parameters: t4.function.parameters,
description: t4.function.description,
strict: t4.function.strict
}
} : t4) : void 0;
for (const message of params.messages) {
this._addMessage(message, false);
}
for (let i4 = 0; i4 < maxChatCompletions; ++i4) {
const chatCompletion = await this._createChatCompletion(client, {
...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: name2, arguments: args } = tool_call.function;
const fn = functionsByName[name2];
if (!fn) {
const content2 = `Invalid tool_call: ${JSON.stringify(name2)}. Available options are: ${Object.keys(functionsByName).map((name3) => JSON.stringify(name3)).join(", ")}. Please try again`;
this._addMessage({ role, tool_call_id, content: content2 });
continue;
} else if (singleFunctionToCall && singleFunctionToCall !== name2) {
const content2 = `Invalid tool_call: ${JSON.stringify(name2)}. ${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 = __classPrivateFieldGet7(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 __classPrivateFieldGet7(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
let i4 = this.messages.length;
while (i4-- > 0) {
const message = this.messages[i4];
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 i4 = this.messages.length - 1; i4 >= 0; i4--) {
const message = this.messages[i4];
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 i4 = this.messages.length - 1; i4 >= 0; i4--) {
const message = this.messages[i4];
if (isFunctionMessage(message) && message.content != null) {
return message.content;
}
if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x2) => x2.role === "assistant" && x2.tool_calls?.some((y3) => y3.type === "function" && y3.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(client, params, options) {
const runner = new ChatCompletionRunner();
const opts = {
...options,
headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" }
};
runner._run(() => runner._runFunctions(client, params, opts));
return runner;
}
static runTools(client, params, options) {
const runner = new ChatCompletionRunner();
const opts = {
...options,
headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
};
runner._run(() => runner._runTools(client, 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 parseJSON(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 index = 0;
const markPartialJSON = (msg) => {
throw new PartialJSON(`${msg} at position ${index}`);
};
const throwMalformedError = (msg) => {
throw new MalformedJSON(`${msg} at position ${index}`);
};
const parseAny = () => {
skipBlank();
if (index >= length)
markPartialJSON("Unexpected end of input");
if (jsonString[index] === '"')
return parseStr();
if (jsonString[index] === "{")
return parseObj();
if (jsonString[index] === "[")
return parseArr();
if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
index += 4;
return null;
}
if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
index += 4;
return true;
}
if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
index += 5;
return false;
}
if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
index += 8;
return Infinity;
}
if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
index += 9;
return -Infinity;
}
if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
index += 3;
return NaN;
}
return parseNum();
};
const parseStr = () => {
const start = index;
let escape2 = false;
index++;
while (index < length && (jsonString[index] !== '"' || escape2 && jsonString[index - 1] === "\\")) {
escape2 = jsonString[index] === "\\" ? !escape2 : false;
index++;
}
if (jsonString.charAt(index) == '"') {
try {
return JSON.parse(jsonString.substring(start, ++index - Number(escape2)));
} catch (e4) {
throwMalformedError(String(e4));
}
} else if (Allow.STR & allow) {
try {
return JSON.parse(jsonString.substring(start, index - Number(escape2)) + '"');
} catch (e4) {
return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
}
}
markPartialJSON("Unterminated string literal");
};
const parseObj = () => {
index++;
skipBlank();
const obj = {};
try {
while (jsonString[index] !== "}") {
skipBlank();
if (index >= length && Allow.OBJ & allow)
return obj;
const key = parseStr();
skipBlank();
index++;
try {
const value = parseAny();
Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
} catch (e4) {
if (Allow.OBJ & allow)
return obj;
else
throw e4;
}
skipBlank();
if (jsonString[index] === ",")
index++;
}
} catch (e4) {
if (Allow.OBJ & allow)
return obj;
else
markPartialJSON("Expected '}' at end of object");
}
index++;
return obj;
};
const parseArr = () => {
index++;
const arr2 = [];
try {
while (jsonString[index] !== "]") {
arr2.push(parseAny());
skipBlank();
if (jsonString[index] === ",") {
index++;
}
}
} catch (e4) {
if (Allow.ARR & allow) {
return arr2;
}
markPartialJSON("Expected ']' at end of array");
}
index++;
return arr2;
};
const parseNum = () => {
if (index === 0) {
if (jsonString === "-" && Allow.NUM & allow)
markPartialJSON("Not sure what '-' is");
try {
return JSON.parse(jsonString);
} catch (e4) {
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 (e5) {
}
}
throwMalformedError(String(e4));
}
}
const start = index;
if (jsonString[index] === "-")
index++;
while (jsonString[index] && !",]}".includes(jsonString[index]))
index++;
if (index == length && !(Allow.NUM & allow))
markPartialJSON("Unterminated number literal");
try {
return JSON.parse(jsonString.substring(start, index));
} catch (e4) {
if (jsonString.substring(start, index) === "-" && Allow.NUM & allow)
markPartialJSON("Not sure what '-' is");
try {
return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
} catch (e5) {
throwMalformedError(String(e5));
}
}
};
const skipBlank = () => {
while (index < length && " \n\r ".includes(jsonString[index])) {
index++;
}
};
return parseAny();
};
var partialParse2 = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);
// node_modules/openai/lib/ChatCompletionStream.mjs
var __classPrivateFieldSet7 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet8 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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);
__classPrivateFieldSet7(this, _ChatCompletionStream_params, params, "f");
__classPrivateFieldSet7(this, _ChatCompletionStream_choiceEventStates, [], "f");
}
get currentChatCompletionSnapshot() {
return __classPrivateFieldGet8(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(client, params, options) {
const runner = new ChatCompletionStream(params);
runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
return runner;
}
async _createChatCompletion(client, params, options) {
super._createChatCompletion;
const signal = options?.signal;
if (signal) {
if (signal.aborted)
this.controller.abort();
signal.addEventListener("abort", () => this.controller.abort());
}
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
this._connected();
for await (const chunk of stream) {
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addChatCompletion(__classPrivateFieldGet8(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());
}
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
this._connected();
const stream = Stream2.fromReadableStream(readableStream, this.controller);
let chatId;
for await (const chunk of stream) {
if (chatId && chatId !== chunk.id) {
this._addChatCompletion(__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
}
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
chatId = chunk.id;
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addChatCompletion(__classPrivateFieldGet8(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;
__classPrivateFieldSet7(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
}, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
let state = __classPrivateFieldGet8(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
};
__classPrivateFieldGet8(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
return state;
}, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
if (this.ended)
return;
const completion = __classPrivateFieldGet8(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 = __classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
if (choiceSnapshot.finish_reason) {
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
if (state.current_tool_call_index != null) {
__classPrivateFieldGet8(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) {
__classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
if (state.current_tool_call_index != null) {
__classPrivateFieldGet8(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 = __classPrivateFieldGet8(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 = __classPrivateFieldGet8(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === "function" && tool.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 = __classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
if (choiceSnapshot.message.content && !state.content_done) {
state.content_done = true;
const responseFormat = __classPrivateFieldGet8(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 = __classPrivateFieldGet8(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
if (!snapshot) {
throw new OpenAIError(`request ended without sending any chunks`);
}
__classPrivateFieldSet7(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
__classPrivateFieldSet7(this, _ChatCompletionStream_choiceEventStates, [], "f");
return finalizeChatCompletion(snapshot, __classPrivateFieldGet8(this, _ChatCompletionStream_params, "f"));
}, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() {
const responseFormat = __classPrivateFieldGet8(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 = __classPrivateFieldGet8(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
const { choices, ...rest } = chunk;
if (!snapshot) {
snapshot = __classPrivateFieldSet7(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
...rest,
choices: []
}, "f");
} else {
Object.assign(snapshot, rest);
}
for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
let choice = snapshot.choices[index];
if (!choice) {
choice = snapshot.choices[index] = { finish_reason, index, 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 (__classPrivateFieldGet8(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet8(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 && __classPrivateFieldGet8(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
choice.message.parsed = partialParse2(choice.message.content);
}
}
if (tool_calls) {
if (!choice.message.tool_calls)
choice.message.tool_calls = [];
for (const { index: index2, id, type, function: fn, ...rest3 } of tool_calls) {
const tool_call = (_d = choice.message.tool_calls)[index2] ?? (_d[index2] = {});
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(__classPrivateFieldGet8(this, _ChatCompletionStream_params, "f"), tool_call)) {
tool_call.function.parsed_arguments = partialParse2(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 Stream2(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, logprobs, ...choiceRest }) => {
if (!finish_reason) {
throw new OpenAIError(`missing finish_reason for choice ${index}`);
}
const { content = null, function_call, tool_calls, ...messageRest } = message;
const role = message.role;
if (!role) {
throw new OpenAIError(`missing role for choice ${index}`);
}
if (function_call) {
const { arguments: args, name: name2 } = function_call;
if (args == null) {
throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
}
if (!name2) {
throw new OpenAIError(`missing function_call.name for choice ${index}`);
}
return {
...choiceRest,
message: {
content,
function_call: { arguments: args, name: name2 },
role,
refusal: message.refusal ?? null
},
finish_reason,
index,
logprobs
};
}
if (tool_calls) {
return {
...choiceRest,
index,
finish_reason,
logprobs,
message: {
...messageRest,
role,
content,
refusal: message.refusal ?? null,
tool_calls: tool_calls.map((tool_call, i4) => {
const { function: fn, type, id: id2, ...toolRest } = tool_call;
const { arguments: args, name: name2, ...fnRest } = fn || {};
if (id2 == null) {
throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].id
${str(snapshot)}`);
}
if (type == null) {
throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].type
${str(snapshot)}`);
}
if (name2 == null) {
throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].function.name
${str(snapshot)}`);
}
if (args == null) {
throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].function.arguments
${str(snapshot)}`);
}
return { ...toolRest, id: id2, type, function: { ...fnRest, name: name2, arguments: args } };
})
}
};
}
return {
...choiceRest,
message: { ...messageRest, content, role, refusal: message.refusal ?? null },
finish_reason,
index,
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(client, params, options) {
const runner = new ChatCompletionStreamingRunner(null);
const opts = {
...options,
headers: { ...options?.headers, "X-Stainless-Helper-Method": "runFunctions" }
};
runner._run(() => runner._runFunctions(client, params, opts));
return runner;
}
static runTools(client, 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(client, params, opts));
return runner;
}
};
// node_modules/openai/resources/beta/chat/completions.mjs
var Completions3 = class extends APIResource2 {
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 APIResource2 {
constructor() {
super(...arguments);
this.completions = new Completions3(this._client);
}
};
(function(Chat5) {
Chat5.Completions = Completions3;
})(Chat2 || (Chat2 = {}));
// node_modules/openai/lib/AssistantStream.mjs
var __classPrivateFieldGet9 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver);
};
var __classPrivateFieldSet8 = function(receiver, state, value, kind4, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.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 = Stream2.fromReadableStream(readableStream, this.controller);
for await (const event of stream) {
__classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addRun(__classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
}
toReadableStream() {
const stream = new Stream2(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) {
__classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addRun(__classPrivateFieldGet9(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 __classPrivateFieldGet9(this, _AssistantStream_currentEvent, "f");
}
currentRun() {
return __classPrivateFieldGet9(this, _AssistantStream_currentRunSnapshot, "f");
}
currentMessageSnapshot() {
return __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f");
}
currentRunStepSnapshot() {
return __classPrivateFieldGet9(this, _AssistantStream_currentRunStepSnapshot, "f");
}
async finalRunSteps() {
await this.done();
return Object.values(__classPrivateFieldGet9(this, _AssistantStream_runStepSnapshots, "f"));
}
async finalMessages() {
await this.done();
return Object.values(__classPrivateFieldGet9(this, _AssistantStream_messageSnapshots, "f"));
}
async finalRun() {
await this.done();
if (!__classPrivateFieldGet9(this, _AssistantStream_finalRun, "f"))
throw Error("Final run was not received.");
return __classPrivateFieldGet9(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) {
__classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addRun(__classPrivateFieldGet9(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) {
__classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError3();
}
return this._addRun(__classPrivateFieldGet9(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 index = deltaEntry["index"];
if (index == null) {
console.error(deltaEntry);
throw new Error("Expected array delta entry to have an `index` property");
}
if (typeof index !== "number") {
throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);
}
const accEntry = accValue[index];
if (accEntry == null) {
accValue.push(deltaEntry);
} else {
accValue[index] = 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;
__classPrivateFieldSet8(this, _AssistantStream_currentEvent, event, "f");
__classPrivateFieldGet9(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":
__classPrivateFieldGet9(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":
__classPrivateFieldGet9(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":
__classPrivateFieldGet9(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 (!__classPrivateFieldGet9(this, _AssistantStream_finalRun, "f"))
throw Error("Final run has not been received");
return __classPrivateFieldGet9(this, _AssistantStream_finalRun, "f");
}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) {
const [accumulatedMessage, newContent] = __classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f"));
__classPrivateFieldSet8(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
__classPrivateFieldGet9(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 != __classPrivateFieldGet9(this, _AssistantStream_currentContentIndex, "f")) {
if (__classPrivateFieldGet9(this, _AssistantStream_currentContent, "f")) {
switch (__classPrivateFieldGet9(this, _AssistantStream_currentContent, "f").type) {
case "text":
this._emit("textDone", __classPrivateFieldGet9(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f"));
break;
case "image_file":
this._emit("imageFileDone", __classPrivateFieldGet9(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f"));
break;
}
}
__classPrivateFieldSet8(this, _AssistantStream_currentContentIndex, content.index, "f");
}
__classPrivateFieldSet8(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
}
}
break;
case "thread.message.completed":
case "thread.message.incomplete":
if (__classPrivateFieldGet9(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
const currentContent = event.data.content[__classPrivateFieldGet9(this, _AssistantStream_currentContentIndex, "f")];
if (currentContent) {
switch (currentContent.type) {
case "image_file":
this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f"));
break;
case "text":
this._emit("textDone", currentContent.text, __classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f"));
break;
}
}
}
if (__classPrivateFieldGet9(this, _AssistantStream_messageSnapshot, "f")) {
this._emit("messageDone", event.data);
}
__classPrivateFieldSet8(this, _AssistantStream_messageSnapshot, void 0, "f");
}
}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event) {
const accumulatedRunStep = __classPrivateFieldGet9(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
__classPrivateFieldSet8(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 == __classPrivateFieldGet9(this, _AssistantStream_currentToolCallIndex, "f")) {
this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
} else {
if (__classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f")) {
this._emit("toolCallDone", __classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f"));
}
__classPrivateFieldSet8(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
__classPrivateFieldSet8(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
if (__classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f"))
this._emit("toolCallCreated", __classPrivateFieldGet9(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":
__classPrivateFieldSet8(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
const details = event.data.step_details;
if (details.type == "tool_calls") {
if (__classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f")) {
this._emit("toolCallDone", __classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f"));
__classPrivateFieldSet8(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) {
__classPrivateFieldGet9(this, _AssistantStream_events, "f").push(event);
this._emit("event", event);
}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event) {
switch (event.event) {
case "thread.run.step.created":
__classPrivateFieldGet9(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
return event.data;
case "thread.run.step.delta":
let snapshot = __classPrivateFieldGet9(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);
__classPrivateFieldGet9(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
}
return __classPrivateFieldGet9(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":
__classPrivateFieldGet9(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
break;
}
if (__classPrivateFieldGet9(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
return __classPrivateFieldGet9(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] = __classPrivateFieldGet9(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) {
__classPrivateFieldSet8(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":
__classPrivateFieldSet8(this, _AssistantStream_finalRun, event.data, "f");
if (__classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f")) {
this._emit("toolCallDone", __classPrivateFieldGet9(this, _AssistantStream_currentToolCall, "f"));
__classPrivateFieldSet8(this, _AssistantStream_currentToolCall, void 0, "f");
}
break;
case "thread.run.cancelling":
break;
}
};
// node_modules/openai/resources/beta/threads/messages.mjs
var Messages3 = class extends APIResource2 {
/**
* 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 {
};
(function(Messages4) {
Messages4.MessagesPage = MessagesPage;
})(Messages3 || (Messages3 = {}));
// node_modules/openai/resources/beta/threads/runs/steps.mjs
var Steps = class extends APIResource2 {
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 {
};
(function(Steps2) {
Steps2.RunStepsPage = RunStepsPage;
})(Steps || (Steps = {}));
// node_modules/openai/resources/beta/threads/runs/runs.mjs
var Runs = class extends APIResource2 {
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 sleep2(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 {
};
(function(Runs2) {
Runs2.RunsPage = RunsPage;
Runs2.Steps = Steps;
Runs2.RunStepsPage = RunStepsPage;
})(Runs || (Runs = {}));
// node_modules/openai/resources/beta/threads/threads.mjs
var Threads = class extends APIResource2 {
constructor() {
super(...arguments);
this.runs = new Runs(this._client);
this.messages = new Messages3(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);
}
};
(function(Threads2) {
Threads2.Runs = Runs;
Threads2.RunsPage = RunsPage;
Threads2.Messages = Messages3;
Threads2.MessagesPage = MessagesPage;
})(Threads || (Threads = {}));
// 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 APIResource2 {
/**
* 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 sleep2(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 {
};
(function(Files3) {
Files3.VectorStoreFilesPage = VectorStoreFilesPage;
})(Files || (Files = {}));
// node_modules/openai/resources/beta/vector-stores/file-batches.mjs
var FileBatches = class extends APIResource2 {
/**
* 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 sleep2(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 client = this._client;
const fileIterator = files.values();
const allFileIds = [...fileIds];
async function processFiles(iterator) {
for (let item of iterator) {
const fileObj = await client.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
});
}
};
(function(FileBatches2) {
})(FileBatches || (FileBatches = {}));
// node_modules/openai/resources/beta/vector-stores/vector-stores.mjs
var VectorStores = class extends APIResource2 {
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 {
};
(function(VectorStores2) {
VectorStores2.VectorStoresPage = VectorStoresPage;
VectorStores2.Files = Files;
VectorStores2.VectorStoreFilesPage = VectorStoreFilesPage;
VectorStores2.FileBatches = FileBatches;
})(VectorStores || (VectorStores = {}));
// node_modules/openai/resources/beta/beta.mjs
var Beta2 = class extends APIResource2 {
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);
}
};
(function(Beta3) {
Beta3.VectorStores = VectorStores;
Beta3.VectorStoresPage = VectorStoresPage;
Beta3.Chat = Chat2;
Beta3.Assistants = Assistants;
Beta3.AssistantsPage = AssistantsPage;
Beta3.Threads = Threads;
})(Beta2 || (Beta2 = {}));
// node_modules/openai/resources/completions.mjs
var Completions4 = class extends APIResource2 {
create(body, options) {
return this._client.post("/completions", { body, ...options, stream: body.stream ?? false });
}
};
(function(Completions7) {
})(Completions4 || (Completions4 = {}));
// node_modules/openai/resources/embeddings.mjs
var Embeddings = class extends APIResource2 {
/**
* Creates an embedding vector representing the input text.
*/
create(body, options) {
return this._client.post("/embeddings", { body, ...options });
}
};
(function(Embeddings4) {
})(Embeddings || (Embeddings = {}));
// node_modules/openai/resources/files.mjs
var Files2 = class extends APIResource2 {
/**
* 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 100 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 sleep2(pollInterval);
file = await this.retrieve(id);
if (Date.now() - start > maxWait) {
throw new APIConnectionTimeoutError3({
message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
});
}
}
return file;
}
};
var FileObjectsPage = class extends Page {
};
(function(Files3) {
Files3.FileObjectsPage = FileObjectsPage;
})(Files2 || (Files2 = {}));
// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
var Checkpoints = class extends APIResource2 {
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 {
};
(function(Checkpoints2) {
Checkpoints2.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
})(Checkpoints || (Checkpoints = {}));
// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
var Jobs = class extends APIResource2 {
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 {
};
(function(Jobs2) {
Jobs2.FineTuningJobsPage = FineTuningJobsPage;
Jobs2.FineTuningJobEventsPage = FineTuningJobEventsPage;
Jobs2.Checkpoints = Checkpoints;
Jobs2.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;
})(Jobs || (Jobs = {}));
// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
var FineTuning = class extends APIResource2 {
constructor() {
super(...arguments);
this.jobs = new Jobs(this._client);
}
};
(function(FineTuning2) {
FineTuning2.Jobs = Jobs;
FineTuning2.FineTuningJobsPage = FineTuningJobsPage;
FineTuning2.FineTuningJobEventsPage = FineTuningJobEventsPage;
})(FineTuning || (FineTuning = {}));
// node_modules/openai/resources/images.mjs
var Images = class extends APIResource2 {
/**
* 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 });
}
};
(function(Images2) {
})(Images || (Images = {}));
// node_modules/openai/resources/models.mjs
var Models = class extends APIResource2 {
/**
* 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 {
};
(function(Models3) {
Models3.ModelsPage = ModelsPage;
})(Models || (Models = {}));
// node_modules/openai/resources/moderations.mjs
var Moderations = class extends APIResource2 {
/**
* 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 });
}
};
(function(Moderations2) {
})(Moderations || (Moderations = {}));
// node_modules/openai/resources/uploads/parts.mjs
var Parts = class extends APIResource2 {
/**
* 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 }));
}
};
(function(Parts2) {
})(Parts || (Parts = {}));
// node_modules/openai/resources/uploads/uploads.mjs
var Uploads = class extends APIResource2 {
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 });
}
};
(function(Uploads2) {
Uploads2.Parts = Parts;
})(Uploads || (Uploads = {}));
// node_modules/openai/index.mjs
var _a2;
var OpenAI = class extends APIClient2 {
/**
* 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 = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("OPENAI_API_KEY"), organization = readEnv2("OPENAI_ORG_ID") ?? null, project = readEnv2("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 && isRunningInBrowser2()) {
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 Completions4(this);
this.chat = new Chat(this);
this.embeddings = new Embeddings(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 Beta2(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 = APIError3;
OpenAI.APIConnectionError = APIConnectionError3;
OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError3;
OpenAI.APIUserAbortError = APIUserAbortError3;
OpenAI.NotFoundError = NotFoundError3;
OpenAI.ConflictError = ConflictError3;
OpenAI.RateLimitError = RateLimitError3;
OpenAI.BadRequestError = BadRequestError3;
OpenAI.AuthenticationError = AuthenticationError3;
OpenAI.InternalServerError = InternalServerError3;
OpenAI.PermissionDeniedError = PermissionDeniedError3;
OpenAI.UnprocessableEntityError = UnprocessableEntityError3;
OpenAI.toFile = toFile2;
OpenAI.fileFromPath = fileFromPath2;
var { OpenAIError: OpenAIError2, APIError: APIError4, APIConnectionError: APIConnectionError4, APIConnectionTimeoutError: APIConnectionTimeoutError4, APIUserAbortError: APIUserAbortError4, NotFoundError: NotFoundError4, ConflictError: ConflictError4, RateLimitError: RateLimitError4, BadRequestError: BadRequestError4, AuthenticationError: AuthenticationError4, InternalServerError: InternalServerError4, PermissionDeniedError: PermissionDeniedError4, UnprocessableEntityError: UnprocessableEntityError4 } = error_exports2;
(function(OpenAI3) {
OpenAI3.Page = Page;
OpenAI3.CursorPage = CursorPage;
OpenAI3.Completions = Completions4;
OpenAI3.Chat = Chat;
OpenAI3.Embeddings = Embeddings;
OpenAI3.Files = Files2;
OpenAI3.FileObjectsPage = FileObjectsPage;
OpenAI3.Images = Images;
OpenAI3.Audio = Audio;
OpenAI3.Moderations = Moderations;
OpenAI3.Models = Models;
OpenAI3.ModelsPage = ModelsPage;
OpenAI3.FineTuning = FineTuning;
OpenAI3.Beta = Beta2;
OpenAI3.Batches = Batches;
OpenAI3.BatchesPage = BatchesPage;
OpenAI3.Uploads = Uploads;
})(OpenAI || (OpenAI = {}));
var openai_default = OpenAI;
// 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 (e4) {
return void 0;
}
} else {
try {
functionArgs = JSON.parse(rawToolCall.function.arguments);
} catch (e4) {
throw new OutputParserException([
`Function "${rawToolCall.function.name}" arguments:`,
``,
rawToolCall.function.arguments,
``,
`are not valid JSON.`,
`Error: ${e4.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 isEmptyObj3(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(([name2, def]) => [
zodDef(def),
{
def: zodDef(def),
path: [..._options.basePath, _options.definitionPath, name2],
// 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, i4) => 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((c5) => /[a-zA-Z0-9]/.test(c5) ? c5 : `\\${c5}`).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: processRegExp2(regex2, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else {
setResponseValueAndErrors2(schema, "pattern", processRegExp2(regex2, refs), message, refs);
}
};
var processRegExp2 = (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 i4 = 0; i4 < source.length; i4++) {
if (isEscaped) {
pattern += source[i4];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i4].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i4];
pattern += `${source[i4 - 2]}-${source[i4]}`.toUpperCase();
inCharRange = false;
} else if (source[i4 + 1] === "-" && source[i4 + 2]?.match(/[a-z]/)) {
pattern += source[i4];
inCharRange = true;
} else {
pattern += `${source[i4]}${source[i4].toUpperCase()}`;
}
continue;
}
} else if (source[i4].match(/[a-z]/)) {
pattern += `[${source[i4]}${source[i4].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i4] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i4] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i4] === ".") {
pattern += inCharGroup ? `${source[i4]}\r
` : `[${source[i4]}\r
]`;
continue;
}
pattern += source[i4];
if (source[i4] === "\\") {
isEscaped = true;
} else if (inCharGroup && source[i4] === "]") {
inCharGroup = false;
} else if (!inCharGroup && source[i4] === "[") {
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, i4, a4) => a4.indexOf(x2) === i4);
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, i4) => parseDef2(x2._def, {
...refs,
currentPath: [...refs.currentPath, "anyOf", `${i4}`]
})).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 a4 = parseDef2(def.in._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"]
});
const b3 = parseDef2(def.out._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", a4 ? "1" : "0"]
});
return {
allOf: [a4, 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, i4) => parseDef2(x2._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i4}`]
})).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, i4) => parseDef2(x2._def, {
...refs,
currentPath: [...refs.currentPath, "items", `${i4}`]
})).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 name2 = item.path.slice(refs.basePath.length + 1).join("_");
if (name2 !== refs.name && refs.nameStrategy === "duplicate-ref") {
refs.definitions[name2] = item.def;
}
return { $ref: [...refs.basePath, refs.definitionPath, name2].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, index) => refs.currentPath[index] === 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 i4 = 0;
for (; i4 < pathA.length && i4 < pathB.length; i4++) {
if (pathA[i4] !== pathB[i4])
break;
}
return [(pathA.length - i4).toString(), ...pathB.slice(i4)].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 name2 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
const main = parseDef2(schema._def, name2 === void 0 ? refs : {
...refs,
currentPath: [...refs.basePath, refs.definitionPath, name2]
}, 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 (isEmptyObj3(refs.definitions)) {
return void 0;
}
const definitions2 = {};
const processedDefinitions = /* @__PURE__ */ new Set();
for (let i4 = 0; i4 < 500; i4++) {
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 = name2 === 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 ? { [name2]: main } : void 0
}
} : void 0
} : {
$ref: [...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name2].join("/"),
[refs.definitionPath]: {
...definitions,
[name2]: 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, name2, props) {
return makeParseableResponseFormat({
type: "json_schema",
json_schema: {
...props,
name: name2,
strict: true,
schema: zodToJsonSchema3(zodObject, { name: name2 })
}
}, (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 } = config;
if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) {
return `${azureOpenAIBasePath}/${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();
function wrapOpenAIClientError(e4) {
let error;
if (e4.constructor.name === APIConnectionTimeoutError4.name) {
error = new Error(e4.message);
error.name = "TimeoutError";
} else if (e4.constructor.name === APIUserAbortError4.name) {
error = new Error(e4.message);
error.name = "AbortError";
} else {
error = e4;
}
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 f4 of functions) {
if (f4.description) {
lines.push(`// ${f4.description}`);
}
if (Object.keys(f4.parameters.properties ?? {}).length > 0) {
lines.push(`type ${f4.name} = (_: {`);
lines.push(formatObjectProperties(f4.parameters, 0));
lines.push("}) => any;");
} else {
lines.push(`type ${f4.name} = () => any;`);
}
lines.push("");
}
lines.push("} // namespace functions");
return lines.join("\n");
}
function formatObjectProperties(obj, indent) {
const lines = [];
for (const [name2, param] of Object.entries(obj.properties ?? {})) {
if (param.description && indent < 2) {
lines.push(`// ${param.description}`);
}
if (obj.required?.includes(name2)) {
lines.push(`${name2}: ${formatType(param, indent)},`);
} else {
lines.push(`${name2}?: ${formatType(param, indent)},`);
}
}
return lines.map((line) => " ".repeat(indent) + line).join("\n");
}
function formatType(param, indent) {
if (isAnyOfProp(param)) {
return param.anyOf.map((v6) => formatType(v6, indent)).join(" | ");
}
switch (param.type) {
case "string":
if (param.enum) {
return param.enum.map((v6) => `"${v6}"`).join(" | ");
}
return "string";
case "number":
if (param.enum) {
return param.enum.map((v6) => `${v6}`).join(" | ");
}
return "number";
case "integer":
if (param.enum) {
return param.enum.map((v6) => `${v6}`).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(tool, fields) {
let toolDef;
if (isLangChainTool(tool)) {
const oaiToolDef = zodFunction({
name: tool.name,
parameters: tool.schema,
description: tool.description
});
if (!oaiToolDef.function.parameters) {
toolDef = {
type: "function",
function: convertToOpenAIFunction(tool, 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 = tool;
}
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 (e4) {
invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e4.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 = {
system_fingerprint: rawResponse.system_fingerprint
};
}
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 (role === "user") {
return new HumanMessageChunk({ content });
} 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
});
} else if (role === "system") {
return new SystemMessageChunk({ content });
} else if (role === "function") {
return new FunctionMessageChunk({
content,
additional_kwargs,
name: delta.name
});
} else if (role === "tool") {
return new ToolMessageChunk({
content,
additional_kwargs,
tool_call_id: delta.tool_call_id
});
} else {
return new ChatMessageChunk({ content, role });
}
}
function _convertMessagesToOpenAIParams(messages) {
return messages.map((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;
}
}
return completionParam;
});
}
function _convertChatOpenAIToolTypeToOpenAITool(tool, fields) {
if (isOpenAITool(tool)) {
if (fields?.strict !== void 0) {
return {
...tool,
function: {
...tool.function,
strict: fields.strict
}
};
}
return tool;
}
return _convertToOpenAITool(tool, 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, configuration) {
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, "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
});
this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? fields?.configuration?.apiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
this.apiKey = this.openAIApiKey;
this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? getEnvironmentVariable("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 ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME");
this.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME");
this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION");
this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH");
this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION");
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;
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");
}
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: configuration?.basePath ?? fields?.configuration?.basePath,
dangerouslyAllowBrowser: true,
defaultHeaders: configuration?.baseOptions?.headers ?? fields?.configuration?.baseOptions?.headers,
defaultQuery: configuration?.baseOptions?.params ?? fields?.configuration?.baseOptions?.params,
...configuration,
...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 strict;
if (kwargs?.strict !== void 0) {
strict = kwargs.strict;
} else if (this.supportsStrictToolCalling !== void 0) {
strict = this.supportsStrictToolCalling;
}
return this.bind({
tools: tools.map((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict })),
...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 strict;
if (options?.strict !== void 0) {
strict = options.strict;
} else if (this.supportsStrictToolCalling !== void 0) {
strict = 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((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict })) : 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.modelKwargs
};
return params;
}
/** @ignore */
_identifyingParams() {
return {
model_name: this.model,
...this.invocationParams(),
...this.clientConfig
};
}
async *_streamResponseChunks(messages, options, runManager) {
if (this.model.includes("o1-")) {
console.warn("[WARNING]: OpenAI o1 models do not yet support token-level streaming. Streaming will yield single chunk.");
const result = await this._generate(messages, options, runManager);
const messageChunk = convertToChunk(result.generations[0].message);
yield new ChatGenerationChunk({
message: messageChunk,
text: typeof messageChunk.content === "string" ? messageChunk.content : ""
});
return;
}
const messagesMapped = _convertMessagesToOpenAIParams(messages);
const params = {
...this.invocationParams(options, {
streaming: true
}),
messages: messagesMapped,
stream: true
};
let defaultRole;
if (params.response_format && params.response_format.type === "json_schema") {
console.warn(`OpenAI does not yet support streaming with "response_format" set to "json_schema". Falling back to non-streaming mode.`);
const res = await this._generate(messages, options, runManager);
const chunk = new ChatGenerationChunk({
message: new AIMessageChunk({
...res.generations[0].message
}),
text: res.generations[0].text,
generationInfo: res.generations[0].generationInfo
});
yield chunk;
return runManager?.handleLLMNewToken(res.generations[0].text ?? "", void 0, void 0, void 0, void 0, { chunk });
}
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 generationChunk = new ChatGenerationChunk({
message: new AIMessageChunk({
content: "",
usage_metadata: {
input_tokens: usage.prompt_tokens,
output_tokens: usage.completion_tokens,
total_tokens: usage.total_tokens
}
}),
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 tokenUsage = {};
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 index = chunk.generationInfo?.completion ?? 0;
if (finalChunks[index] === void 0) {
finalChunks[index] = chunk;
} else {
finalChunks[index] = finalChunks[index].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);
tokenUsage.promptTokens = promptTokenUsage;
tokenUsage.completionTokens = completionTokenUsage;
tokenUsage.totalTokens = promptTokenUsage + completionTokenUsage;
return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
} 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 } = 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 = [];
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 = {
input_tokens: tokenUsage.promptTokens ?? 0,
output_tokens: tokenUsage.completionTokens ?? 0,
total_tokens: tokenUsage.totalTokens ?? 0
};
}
generations.push(generation);
}
return {
generations,
llmOutput: { tokenUsage }
};
}
}
/**
* 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((a4, b3) => a4 + 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 count3 = textCount + tokensPerMessage + roleCount + nameCount;
const openAIMessage = message;
if (openAIMessage._getType() === "function") {
count3 -= 2;
}
if (openAIMessage.additional_kwargs?.function_call) {
count3 += 3;
}
if (openAIMessage?.additional_kwargs.function_call?.name) {
count3 += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);
}
if (openAIMessage.additional_kwargs.function_call?.arguments) {
try {
count3 += 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));
count3 += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);
}
}
totalCount += count3;
return count3;
}));
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 (e4) {
const error = wrapOpenAIClientError(e4);
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 (e4) {
const error = wrapOpenAIClientError(e4);
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
};
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 name2;
let method;
let includeRaw;
if (isStructuredOutputMethodParams(outputSchema)) {
schema = outputSchema.schema;
name2 = outputSchema.name;
method = outputSchema.method;
includeRaw = outputSchema.includeRaw;
} else {
schema = outputSchema;
name2 = 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: name2 ?? "extract",
description: schema.description,
schema,
strict: config?.strict
}
}
});
if (isZodSchema2(schema)) {
outputParser = StructuredOutputParser.fromZodSchema(schema);
} else {
outputParser = new JsonOutputParser();
}
} else {
let functionName = name2 ?? "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/core/dist/language_models/llms.js
init_messages2();
init_outputs();
init_manager();
init_base8();
init_event_stream();
init_log_stream();
init_stream();
// node_modules/@langchain/core/dist/utils/chunk_array.js
var chunkArray = (arr2, chunkSize) => arr2.reduce((chunks, elem, index) => {
const chunkIndex = Math.floor(index / chunkSize);
const chunk = chunks[chunkIndex] || [];
chunks[chunkIndex] = chunk.concat([elem]);
return chunks;
}, []);
// node_modules/@langchain/openai/dist/legacy.js
init_outputs2();
// node_modules/@langchain/core/dist/embeddings.js
init_async_caller2();
var Embeddings2 = class {
constructor(params) {
Object.defineProperty(this, "caller", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.caller = new AsyncCaller2(params ?? {});
}
};
// node_modules/@langchain/openai/dist/embeddings.js
var OpenAIEmbeddings = class extends Embeddings2 {
constructor(fields, configuration) {
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 ?? getEnvironmentVariable("OPENAI_API_KEY");
const azureApiKey = fieldsWithDefaults?.azureOpenAIApiKey ?? getEnvironmentVariable("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 ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME");
const azureApiDeploymentName = (fieldsWithDefaults?.azureOpenAIApiEmbeddingsDeploymentName || fieldsWithDefaults?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"));
const azureApiVersion = fieldsWithDefaults?.azureOpenAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION");
this.azureOpenAIBasePath = fieldsWithDefaults?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH");
this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable("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: configuration?.basePath,
dangerouslyAllowBrowser: true,
defaultHeaders: configuration?.baseOptions?.headers,
defaultQuery: configuration?.baseOptions?.params,
...configuration,
...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((t4) => t4.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 i4 = 0; i4 < batchResponses.length; i4 += 1) {
const batch = batches[i4];
const { data: batchResponse } = batchResponses[i4];
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 (e4) {
const error = wrapOpenAIClientError(e4);
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;
if (_isToolCall(input)) {
tool_call_id = input.id;
toolInput = input.args;
} else {
toolInput = input;
}
const ensuredConfig = ensureConfig(config);
return this.call(toolInput, {
...ensuredConfig,
configurable: {
...ensuredConfig.configurable,
tool_call_id
}
});
}
/**
* @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 (e4) {
let message = `Received tool input did not match expected schema`;
if (this.verboseParsingErrors) {
message = `${message}
Details: ${e4.message}`;
}
throw new ToolInputParsingException(message, JSON.stringify(arg));
}
const config = parseCallbackConfigArg(configArg);
const callbackManager_ = await 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 (e4) {
await runManager?.handleToolError(e4);
throw e4;
}
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);
}
};
function _formatToolOutput(params) {
const { content, artifact, toolCallId } = params;
if (toolCallId) {
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 ?? getEnvironmentVariable("OPENAI_API_KEY");
const organization = fields?.organization ?? getEnvironmentVariable("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/langchainWrappers.ts
var import_obsidian2 = require("obsidian");
var ProxyChatOpenAI = class extends ChatOpenAI {
constructor(fields) {
super(fields ?? {});
this["client"] = new openai_default({
...this["clientConfig"],
baseURL: fields.openAIProxyBaseUrl,
dangerouslyAllowBrowser: true,
fetch: fields.enableCors ? safeFetch : void 0
});
}
};
var ProxyOpenAIEmbeddings = class extends OpenAIEmbeddings {
constructor(fields) {
super(fields ?? {});
this["client"] = new openai_default({
...this["clientConfig"],
baseURL: fields.openAIEmbeddingProxyBaseUrl,
dangerouslyAllowBrowser: true,
fetch: safeFetch
});
}
};
var ChatAnthropicWrapped = class extends ChatAnthropic {
constructor(fields) {
super({
...fields,
// Required to bypass CORS restrictions
clientOptions: { defaultHeaders: { "anthropic-dangerous-direct-browser-access": "true" } }
});
}
};
async function safeFetch(url, options) {
delete options.headers["content-length"];
if (typeof options.body === "string") {
const newBody = JSON.parse(options.body ?? {});
delete newBody["frequency_penalty"];
options.body = JSON.stringify(newBody);
}
const response = await (0, import_obsidian2.requestUrl)({
url,
contentType: "application/json",
headers: options.headers,
method: "POST",
body: options.body?.toString()
});
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,
body: createReadableStreamFromString(response.text),
bodyUsed: true,
json: () => response.json,
text: async () => response.text,
clone: () => {
throw new Error("not implemented");
},
arrayBuffer: () => {
throw new Error("not implemented");
},
blob: () => {
throw new Error("not implemented");
},
formData: () => {
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();
}
});
}
// node_modules/@langchain/cohere/dist/chat_models.js
var import_cohere_ai = __toESM(require_cohere_ai(), 1);
init_esm();
init_base9();
init_outputs2();
// node_modules/@langchain/cohere/node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex4 = [];
for (i4 = 0; i4 < 256; ++i4) {
byteToHex4.push((i4 + 256).toString(16).slice(1));
}
var i4;
function unsafeStringify4(arr2, offset = 0) {
return (byteToHex4[arr2[offset + 0]] + byteToHex4[arr2[offset + 1]] + byteToHex4[arr2[offset + 2]] + byteToHex4[arr2[offset + 3]] + "-" + byteToHex4[arr2[offset + 4]] + byteToHex4[arr2[offset + 5]] + "-" + byteToHex4[arr2[offset + 6]] + byteToHex4[arr2[offset + 7]] + "-" + byteToHex4[arr2[offset + 8]] + byteToHex4[arr2[offset + 9]] + "-" + byteToHex4[arr2[offset + 10]] + byteToHex4[arr2[offset + 11]] + byteToHex4[arr2[offset + 12]] + byteToHex4[arr2[offset + 13]] + byteToHex4[arr2[offset + 14]] + byteToHex4[arr2[offset + 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, offset) {
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) {
offset = offset || 0;
for (var i4 = 0; i4 < 16; ++i4) {
buf[offset + i4] = rnds[i4];
}
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(tool) {
return "name" in tool && "description" in tool && "parameterDefinitions" in tool;
}
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((tool) => {
return {
name: tool.function.name,
description: tool.function.description ?? "",
parameterDefinitions: _convertJsonSchemaToCohereTool(tool.function.parameters)
};
});
} else if (tools.every(isLangChainTool)) {
return tools.map((tool) => {
const parameterDefinitionsFromZod = zodToJsonSchema(tool.schema);
return {
name: tool.name,
description: tool.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 ?? getEnvironmentVariable("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 i4 = 0; i4 < messages.length - 1; i4 += 1) {
const message = messages[i4];
if (message._getType().toLowerCase() === "tool") {
tempToolResults = tempToolResults.concat(this._messageToCohereToolResults(messages, i4));
if (i4 === messages.length - 1 || !(messages[i4 + 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 i4 = 0; i4 < messages.length - 1; i4 += 1) {
const message = messages[i4];
if (isAIMessage(message) && message.tool_calls) {
continue;
}
if (message._getType().toLowerCase() === "tool") {
tempToolResults = tempToolResults.concat(this._messageToCohereToolResults(messages, i4));
if (i4 === messages.length - 1 || !(messages[i4 + 1]._getType().toLowerCase() === "tool")) {
const cohereMessage = convertMessageToCohereMessage(message, tempToolResults);
chatHistory.push(cohereMessage);
tempToolResults = [];
}
} else {
chatHistory.push(convertMessageToCohereMessage(message, []));
}
}
for (let i4 = messages.length - 1; i4 >= 0; i4 -= 1) {
const message = messages[i4];
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 i4 = messages.length - 1; i4 >= 0; i4 -= 1) {
const message = messages[i4];
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 index = chunk.generationInfo?.completion ?? 0;
if (finalChunks[index] === void 0) {
finalChunks[index] = chunk;
} else {
finalChunks[index] = finalChunks[index].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 (e4) {
e4.status = e4.status ?? e4.statusCode;
throw e4;
}
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 (e4) {
e4.status = e4.status ?? e4.statusCode;
throw e4;
}
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/cohere/dist/embeddings.js
var import_cohere_ai3 = __toESM(require_cohere_ai(), 1);
var CohereEmbeddings = class extends Embeddings2 {
/**
* 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 || getEnvironmentVariable("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 i4 = 0; i4 < batchResponses.length; i4 += 1) {
const batch = batches[i4];
const { embeddings: batchResponse } = batchResponses[i4];
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 (e4) {
e4.status = e4.status ?? e4.statusCode;
throw e4;
}
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 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["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 FunctionDeclarationSchemaType;
(function(FunctionDeclarationSchemaType2) {
FunctionDeclarationSchemaType2["STRING"] = "STRING";
FunctionDeclarationSchemaType2["NUMBER"] = "NUMBER";
FunctionDeclarationSchemaType2["INTEGER"] = "INTEGER";
FunctionDeclarationSchemaType2["BOOLEAN"] = "BOOLEAN";
FunctionDeclarationSchemaType2["ARRAY"] = "ARRAY";
FunctionDeclarationSchemaType2["OBJECT"] = "OBJECT";
})(FunctionDeclarationSchemaType || (FunctionDeclarationSchemaType = {}));
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 DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
var DEFAULT_API_VERSION = "v1beta";
var PACKAGE_VERSION = "0.7.1";
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) {
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);
return headers;
}
async function constructRequest(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 makeRequest(model, task, apiKey, stream, body, requestOptions) {
return _makeRequestInternal(model, task, apiKey, stream, body, requestOptions, fetch);
}
async function _makeRequestInternal(model, task, apiKey, stream, body, requestOptions, fetchFn = fetch) {
const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
let response;
try {
const request = await constructRequest(model, task, apiKey, stream, body, requestOptions);
response = await fetchFn(request.url, request.fetchOptions);
if (!response.ok) {
let message = "";
try {
const json = await response.json();
message = json.error.message;
if (json.error.details) {
message += ` ${JSON.stringify(json.error.details)}`;
}
} catch (e4) {
}
throw new Error(`[${response.status} ${response.statusText}] ${message}`);
}
} catch (e4) {
const err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e4.message}`);
err.stack = e4.stack;
throw err;
}
return response;
}
function buildFetchOptions(requestOptions) {
const fetchOptions = {};
if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
const abortController = new AbortController();
const signal = abortController.signal;
setTimeout(() => abortController.abort(), requestOptions.timeout);
fetchOptions.signal = 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;
if ((_d = (_c = (_b = (_a5 = response.candidates) === null || _a5 === void 0 ? void 0 : _a5[0].content) === null || _b === void 0 ? void 0 : _b.parts) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text) {
return response.candidates[0].content.parts.map(({ text }) => text).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];
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(v6) {
return this instanceof __await5 ? (this.v = v6, this) : new __await5(v6);
}
function __asyncGenerator5(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
return this;
}, i4;
function verb(n4) {
if (g4[n4])
i4[n4] = function(v6) {
return new Promise(function(a4, b3) {
q3.push([n4, v6, a4, b3]) > 1 || resume(n4, v6);
});
};
}
function resume(n4, v6) {
try {
step(g4[n4](v6));
} catch (e4) {
settle(q3[0][3], e4);
}
}
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(f4, v6) {
if (f4(v6), 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 match = currentText.match(responseLineRE);
let parsedResponse;
while (match) {
try {
parsedResponse = JSON.parse(match[1]);
} catch (e4) {
controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`));
return;
}
controller.enqueue(parsedResponse);
currentText = currentText.substring(match[0].length);
match = 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 i4 = candidate.index;
if (!aggregatedResponse.candidates) {
aggregatedResponse.candidates = [];
}
if (!aggregatedResponse.candidates[i4]) {
aggregatedResponse.candidates[i4] = {
index: candidate.index
};
}
aggregatedResponse.candidates[i4].citationMetadata = candidate.citationMetadata;
aggregatedResponse.candidates[i4].finishReason = candidate.finishReason;
aggregatedResponse.candidates[i4].finishMessage = candidate.finishMessage;
aggregatedResponse.candidates[i4].safetyRatings = candidate.safetyRatings;
if (candidate.content && candidate.content.parts) {
if (!aggregatedResponse.candidates[i4].content) {
aggregatedResponse.candidates[i4].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 (Object.keys(newPart).length === 0) {
newPart.text = "";
}
aggregatedResponse.candidates[i4].content.parts.push(newPart);
}
}
}
}
}
return aggregatedResponse;
}
async function generateContentStream(apiKey, model, params, requestOptions) {
const response = await makeRequest(
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 makeRequest(
model,
Task.GENERATE_CONTENT,
apiKey,
/* stream */
false,
JSON.stringify(params),
requestOptions
);
const responseJson = await response.json();
const enhancedResponse = addHelpers(responseJson);
return {
response: enhancedResponse
};
}
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 formatGenerateContentInput(params) {
if (params.contents) {
return params;
} else {
const content = formatNewContent(params);
return { contents: [content] };
}
}
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"
];
var VALID_PARTS_PER_ROLE = {
user: ["text", "inlineData"],
function: ["functionResponse"],
model: ["text", "functionCall"],
// System instructions shouldn't be in history anyway.
system: ["text"]
};
var VALID_PREVIOUS_CONTENT_ROLES = {
user: ["model"],
function: ["model"],
model: ["user", "function"],
// System instructions shouldn't be in history.
system: []
};
function validateChatHistory(history) {
let prevContent;
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
};
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`);
}
}
if (prevContent) {
const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role];
if (!validPreviousContentRoles.includes(prevContent.role)) {
throw new GoogleGenerativeAIError(`Content with role '${role}' can't follow '${prevContent.role}'. Valid previous roles: ${JSON.stringify(VALID_PREVIOUS_CONTENT_ROLES)}`);
}
}
prevContent = currContent;
}
}
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}
*/
async sendMessage(request) {
var _a5, _b, _c, _d, _e;
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,
contents: [...this._history, newContent]
};
let finalResult;
this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, this.requestOptions)).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.
*/
async sendMessageStream(request) {
var _a5, _b, _c, _d, _e;
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,
contents: [...this._history, newContent]
};
const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, this.requestOptions);
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((e4) => {
if (e4.message !== SILENT_ERROR) {
console.error(e4);
}
});
return streamPromise;
}
};
async function countTokens(apiKey, model, params, requestOptions) {
const response = await makeRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(Object.assign(Object.assign({}, params), { model })), requestOptions);
return response.json();
}
async function embedContent(apiKey, model, params, requestOptions) {
const response = await makeRequest(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 makeRequest(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;
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 = modelParams.systemInstruction;
this.requestOptions = requestOptions || {};
}
/**
* Makes a single non-streaming call to the model
* and returns an object containing a single {@link GenerateContentResponse}.
*/
async generateContent(request) {
const formattedParams = formatGenerateContentInput(request);
return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction }, formattedParams), this.requestOptions);
}
/**
* 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.
*/
async generateContentStream(request) {
const formattedParams = formatGenerateContentInput(request);
return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction }, formattedParams), this.requestOptions);
}
/**
* Gets a new {@link ChatSession} instance which can be used for
* multi-turn chats.
*/
startChat(startChatParams) {
return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction }, startChatParams), this.requestOptions);
}
/**
* Counts the tokens in the provided request.
*/
async countTokens(request) {
const formattedParams = formatGenerateContentInput(request);
return countTokens(this.apiKey, this.model, formattedParams, this.requestOptions);
}
/**
* Embeds the provided content.
*/
async embedContent(request) {
const formattedParams = formatEmbedContentInput(request);
return embedContent(this.apiKey, this.model, formattedParams, this.requestOptions);
}
/**
* Embeds an array of {@link EmbedContentRequest}s.
*/
async batchEmbedContents(batchEmbedContentRequest) {
return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, this.requestOptions);
}
};
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);
}
};
// 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;
}
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":
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((c5) => {
if (c5.type === "text") {
return {
text: c5.text
};
}
if (c5.type === "image_url") {
if (!isMultimodalModel) {
throw new Error(`This model does not support images`);
}
let source;
if (typeof c5.image_url === "string") {
source = c5.image_url;
} else if (typeof c5.image_url === "object" && "url" in c5.image_url) {
source = c5.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 (c5.type === "media") {
return messageContentMedia(c5);
} else if (c5.type === "tool_use") {
return {
functionCall: {
name: c5.name,
args: c5.input
}
};
}
throw new Error(`Unknown content type ${c5.type}`);
});
}
return [...messageParts, ...functionCalls, ...functionResponses];
}
function convertBaseMessagesToContent(messages, isMultimodalModel) {
return messages.reduce((acc, message, index) => {
if (!isBaseMessage(message)) {
throw new Error("Unsupported message input");
}
const author = getMessageAuthor(message);
if (author === "system" && index !== 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 = "user";
}
const content = {
role: actualRole,
parts
};
return {
mergeWithPreviousContent: author === "system",
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, ...generationInfo } = candidate;
const text = content?.parts[0]?.text ?? "";
const generation = {
text,
message: new AIMessage({
content: text,
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, ...generationInfo } = candidate;
const text = content?.parts[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: text,
name: !content ? void 0 : content.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((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) {
return tools;
}
return [
{
functionDeclarations: tools.map((tool) => {
if (isLangChainTool(tool)) {
const jsonSchema = zodToGenerativeAIParameters(tool.schema);
return {
name: tool.name,
description: tool.description,
parameters: jsonSchema
};
}
if (isOpenAITool(tool)) {
return {
name: tool.function.name,
description: tool.function.description ?? `A function available to call.`,
parameters: jsonSchemaToGeminiParameters(tool.function.parameters)
};
}
return tool;
})
}
];
}
// 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 [tool] = tools;
const validatedResult = await this._validateResult(tool.args);
return validatedResult;
}
};
// 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");
}
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, "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 ?? getEnvironmentVariable("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;
}
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: convertToGenerativeAITools(tools), ...kwargs });
}
invocationParams(options) {
if (options?.tool_choice) {
throw new Error("'tool_choice' call option is not supported by ChatGoogleGenerativeAI.");
}
const tools = options?.tools;
if (Array.isArray(tools) && !tools.some(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(t4) => !("lc_namespace" in t4)
)) {
return {
tools: convertToGenerativeAITools(options?.tools)
};
}
return {
tools: options?.tools
};
}
async _generate(messages, options, runManager) {
const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel);
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 index = chunk.generationInfo?.completion ?? 0;
if (finalChunks[index] === void 0) {
finalChunks[index] = chunk;
} else {
finalChunks[index] = finalChunks[index].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: prompt
});
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);
const parameters = this.invocationParams(options);
const request = {
...parameters,
contents: prompt
};
const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => {
const { stream: stream2 } = await this.client.generateContentStream(request);
return stream2;
});
let usageMetadata;
let index = 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
});
index += 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 (e4) {
if (e4.message?.includes("400 Bad Request")) {
e4.status = 400;
}
throw e4;
}
});
}
withStructuredOutput(outputSchema, config) {
const schema = outputSchema;
const name2 = 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 = name2 ?? "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
});
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 Embeddings2 {
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 ?? getEnvironmentVariable("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((e4) => e4.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 (e4) {
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(name2) {
if (typeof name2 !== "string") {
name2 = String(name2);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name2) || name2 === "") {
throw new TypeError('Invalid character in header field name: "' + name2 + '"');
}
return name2.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 Headers4(headers) {
this.map = {};
if (headers instanceof Headers4) {
headers.forEach(function(value, name2) {
this.append(name2, 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(name2) {
this.append(name2, headers[name2]);
}, this);
}
}
Headers4.prototype.append = function(name2, value) {
name2 = normalizeName(name2);
value = normalizeValue(value);
var oldValue = this.map[name2];
this.map[name2] = oldValue ? oldValue + ", " + value : value;
};
Headers4.prototype["delete"] = function(name2) {
delete this.map[normalizeName(name2)];
};
Headers4.prototype.get = function(name2) {
name2 = normalizeName(name2);
return this.has(name2) ? this.map[name2] : null;
};
Headers4.prototype.has = function(name2) {
return this.map.hasOwnProperty(normalizeName(name2));
};
Headers4.prototype.set = function(name2, value) {
this.map[normalizeName(name2)] = normalizeValue(value);
};
Headers4.prototype.forEach = function(callback, thisArg) {
for (var name2 in this.map) {
if (this.map.hasOwnProperty(name2)) {
callback.call(thisArg, this.map[name2], name2, this);
}
}
};
Headers4.prototype.keys = function() {
var items = [];
this.forEach(function(value, name2) {
items.push(name2);
});
return iteratorFor(items);
};
Headers4.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items);
};
Headers4.prototype.entries = function() {
var items = [];
this.forEach(function(value, name2) {
items.push([name2, value]);
});
return iteratorFor(items);
};
if (support.iterable) {
Headers4.prototype[Symbol.iterator] = Headers4.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 match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type);
var encoding = match ? match[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 i4 = 0; i4 < view.length; i4++) {
chars[i4] = String.fromCharCode(view[i4]);
}
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 Request4(input, options) {
if (!(this instanceof Request4)) {
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 Request4) {
if (input.bodyUsed) {
throw new TypeError("Already read");
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers4(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 Headers4(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();
}
}
}
}
Request4.prototype.clone = function() {
return new Request4(this, { body: this._bodyInit });
};
function decode(body) {
var form = new FormData();
body.trim().split("&").forEach(function(bytes) {
if (bytes) {
var split = bytes.split("=");
var name2 = split.shift().replace(/\+/g, " ");
var value = split.join("=").replace(/\+/g, " ");
form.append(decodeURIComponent(name2), decodeURIComponent(value));
}
});
return form;
}
function parseHeaders(rawHeaders) {
var headers = new Headers4();
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(Request4.prototype);
function Response4(bodyInit, options) {
if (!(this instanceof Response4)) {
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 Headers4(options.headers);
this.url = options.url || "";
this._initBody(bodyInit);
}
Body.call(Response4.prototype);
Response4.prototype.clone = function() {
return new Response4(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers4(this.headers),
url: this.url
});
};
Response4.error = function() {
var response = new Response4(null, { status: 200, statusText: "" });
response.ok = false;
response.status = 0;
response.type = "error";
return response;
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response4.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError("Invalid status code");
}
return new Response4(null, { status, headers: { location: url } });
};
var DOMException = g3.DOMException;
try {
new DOMException();
} catch (err) {
DOMException = function(message, name2) {
this.message = message;
this.name = name2;
var error = Error(message);
this.stack = error.stack;
};
DOMException.prototype = Object.create(Error.prototype);
DOMException.prototype.constructor = DOMException;
}
function fetch4(input, init2) {
return new Promise(function(resolve, reject) {
var request = new Request4(input, init2);
if (request.signal && request.signal.aborted) {
return reject(new DOMException("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 Response4(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 DOMException("Aborted", "AbortError"));
}, 0);
};
function fixUrl(url) {
try {
return url === "" && g3.location.href ? g3.location.href : url;
} catch (e4) {
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 (init2 && typeof init2.headers === "object" && !(init2.headers instanceof Headers4 || g3.Headers && init2.headers instanceof g3.Headers)) {
var names = [];
Object.getOwnPropertyNames(init2.headers).forEach(function(name2) {
names.push(normalizeName(name2));
xhr.setRequestHeader(name2, normalizeValue(init2.headers[name2]));
});
request.headers.forEach(function(value, name2) {
if (names.indexOf(name2) === -1) {
xhr.setRequestHeader(name2, value);
}
});
} else {
request.headers.forEach(function(value, name2) {
xhr.setRequestHeader(name2, 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);
});
}
fetch4.polyfill = true;
if (!g3.fetch) {
g3.fetch = fetch4;
g3.Headers = Headers4;
g3.Request = Request4;
g3.Response = Response4;
}
// node_modules/ollama/dist/shared/ollama.5360ad67.mjs
var version = "0.5.8";
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
});
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 parseJSON2 = 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((p4) => p4 !== "")) {
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
});
if (!response2.body) {
throw new Error("Missing body");
}
const itr = parseJSON2(response2.body);
const abortableAsyncIterator = new AbortableAsyncIterator(
abortController,
itr,
() => {
const i4 = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator);
if (i4 > -1) {
this.ongoingStreamedRequests.splice(i4, 1);
}
}
);
this.ongoingStreamedRequests.push(abortableAsyncIterator);
return abortableAsyncIterator;
}
const response = await post(this.fetch, host, request);
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 i4 = 0; i4 < len; i4++) {
byteString += String.fromCharCode(uint8Array[i4]);
}
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 (i4 = 0; i4 < 256; ++i4) {
byteToHex5.push((i4 + 256).toString(16).slice(1));
}
var i4;
function unsafeStringify5(arr2, offset = 0) {
return (byteToHex5[arr2[offset + 0]] + byteToHex5[arr2[offset + 1]] + byteToHex5[arr2[offset + 2]] + byteToHex5[arr2[offset + 3]] + "-" + byteToHex5[arr2[offset + 4]] + byteToHex5[arr2[offset + 5]] + "-" + byteToHex5[arr2[offset + 6]] + byteToHex5[arr2[offset + 7]] + "-" + byteToHex5[arr2[offset + 8]] + byteToHex5[arr2[offset + 9]] + "-" + byteToHex5[arr2[offset + 10]] + byteToHex5[arr2[offset + 11]] + byteToHex5[arr2[offset + 12]] + byteToHex5[arr2[offset + 13]] + byteToHex5[arr2[offset + 14]] + byteToHex5[arr2[offset + 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, offset) {
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) {
offset = offset || 0;
for (var i4 = 0; i4 < 16; ++i4) {
buf[offset + i4] = rnds[i4];
}
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 match = dataUrl.match(/^data:.*?;base64,(.*)$/);
return match ? match[1] : "";
}
function convertAMessagesToOllama(messages) {
if (typeof messages.content === "string") {
return [
{
role: "assistant",
content: messages.content
}
];
}
const textFields = messages.content.filter((c5) => c5.type === "text" && typeof c5.text === "string");
const textMessages = textFields.map((c5) => ({
role: "assistant",
content: c5.text
}));
let toolCallMsgs;
if (messages.content.find((c5) => c5.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((c5) => c5.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((c5) => {
if (c5.type === "text") {
return {
role: "user",
content: c5.text
};
} else if (c5.type === "image_url") {
if (typeof c5.image_url === "string") {
return {
role: "user",
content: "",
images: [extractBase64FromDataUrl(c5.image_url)]
};
} else if (c5.image_url.url && typeof c5.image_url.url === "string") {
return {
role: "user",
content: "",
images: [extractBase64FromDataUrl(c5.image_url.url)]
};
}
}
throw new Error(`Unsupported content type: ${c5.type}`);
});
}
function convertSystemMessageToOllama(message) {
if (typeof message.content === "string") {
return [
{
role: "system",
content: message.content
}
];
} else if (message.content.every((c5) => c5.type === "text" && typeof c5.text === "string")) {
return message.content.map((c5) => ({
role: "system",
content: c5.text
}));
} else {
throw new Error(`Unsupported content type(s): ${message.content.map((c5) => c5.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
});
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((tool) => convertToOpenAITool(tool)),
...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((tool) => convertToOpenAITool(tool)) : 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 Embeddings2 {
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
});
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();
// src/LLMProviders/embeddingManager.ts
var EmbeddingManager = class {
constructor(getLangChainParams, encryptionService, activeEmbeddingModels) {
this.getLangChainParams = getLangChainParams;
this.encryptionService = encryptionService;
this.activeEmbeddingModels = activeEmbeddingModels;
this.buildModelMap(activeEmbeddingModels);
}
static getInstance(getLangChainParams, encryptionService, activeEmbeddingModels) {
if (!EmbeddingManager.instance) {
EmbeddingManager.instance = new EmbeddingManager(
getLangChainParams,
encryptionService,
activeEmbeddingModels
);
}
return EmbeddingManager.instance;
}
// Build a map of modelKey to model config
buildModelMap(activeEmbeddingModels) {
EmbeddingManager.modelMap = {};
const modelMap = EmbeddingManager.modelMap;
const params = this.getLangChainParams();
activeEmbeddingModels.forEach((model) => {
if (model.enabled) {
let constructor;
let apiKey;
switch (model.provider) {
case "openai" /* OPENAI */:
constructor = OpenAIEmbeddings;
apiKey = params.openAIApiKey;
break;
case "cohereai" /* COHEREAI */:
constructor = CohereEmbeddings;
apiKey = params.cohereApiKey;
break;
case "google" /* GOOGLE */:
constructor = GoogleGenerativeAIEmbeddings;
apiKey = params.googleApiKey;
break;
case "azure_openai" /* AZURE_OPENAI */:
constructor = OpenAIEmbeddings;
apiKey = params.azureOpenAIApiKey;
break;
case "ollama" /* OLLAMA */:
constructor = OllamaEmbeddings;
apiKey = "default-key";
break;
case "3rd party (openai-format)" /* OPENAI_FORMAT */:
constructor = ProxyOpenAIEmbeddings;
apiKey = model.apiKey;
break;
default:
console.warn(`Unknown provider: ${model.provider} for embedding model: ${model.name}`);
return;
}
const modelKey = `${model.name}|${model.provider}`;
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 = `${model.name}|${model.provider}`;
return modelKey === key;
})[0];
}
getEmbeddingsAPI() {
const { embeddingModelKey } = this.getLangChainParams();
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 = 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}`
);
}
}
getEmbeddingConfig(customModel) {
const decrypt = (key) => this.encryptionService.getDecryptedKey(key);
const params = this.getLangChainParams();
const modelName = customModel.name;
const baseConfig = {
maxRetries: 3,
maxConcurrency: 3
};
const providerConfigs = {
["openai" /* OPENAI */]: {
modelName,
openAIApiKey: decrypt(params.openAIApiKey),
timeout: 1e4
},
["cohereai" /* COHEREAI */]: {
model: modelName,
apiKey: decrypt(params.cohereApiKey)
},
["google" /* GOOGLE */]: {
modelName,
apiKey: decrypt(params.googleApiKey)
},
["azure_openai" /* AZURE_OPENAI */]: {
azureOpenAIApiKey: decrypt(params.azureOpenAIApiKey),
azureOpenAIApiInstanceName: params.azureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName: params.azureOpenAIApiEmbeddingDeploymentName,
azureOpenAIApiVersion: params.azureOpenAIApiVersion
},
["ollama" /* OLLAMA */]: {
baseUrl: customModel.baseUrl || "http://localhost:11434",
model: modelName
},
["3rd party (openai-format)" /* OPENAI_FORMAT */]: {
modelName,
openAIApiKey: decrypt(customModel.apiKey || ""),
openAIEmbeddingProxyBaseUrl: customModel.baseUrl
}
};
const modelKey = `${modelName}|${customModel.provider}`;
const selectedModel = EmbeddingManager.modelMap[modelKey];
if (!selectedModel) {
console.error(`No embedding model found for key: ${modelKey}`);
}
const providerConfig = providerConfigs[selectedModel.vendor] || {};
return { ...baseConfig, ...providerConfig };
}
};
// 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 now = Date.now();
const timeToWait = Math.max(0, this.lastRequestTime + 1e3 / this.requestsPerSecond - now);
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;
}
}
};
// 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 i4 = 0; i4 < newArrLength; i4 += MAX_ARGUMENT_FOR_STACK) {
Array.prototype.push.apply(arr2, newArr.slice(i4, i4 + 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(a4, b3) {
if (b3[1] === a4[1]) {
return a4[0] - b3[0];
}
return b3[1] - a4[1];
}
function intersect(arrays) {
if (arrays.length === 0) {
return [];
} else if (arrays.length === 1) {
return arrays[0];
}
for (let i4 = 1; i4 < arrays.length; i4++) {
if (arrays[i4].length < arrays[0].length) {
const tmp = arrays[0];
arrays[0] = arrays[i4];
arrays[i4] = tmp;
}
}
const set = /* @__PURE__ */ new Map();
for (const elem of arrays[0]) {
set.set(elem, 1);
}
for (let i4 = 1; i4 < arrays.length; i4++) {
let found = 0;
for (const elem of arrays[i4]) {
const count3 = set.get(elem);
if (count3 === i4) {
set.set(elem, count3 + 1);
found++;
}
}
if (found === 0)
return [];
}
return arrays[0].filter((e4) => {
const count3 = set.get(e4);
if (count3 !== void 0)
set.set(e4, 0);
return count3 === arrays.length;
});
}
function getDocumentProperties(doc, paths) {
const properties = {};
const pathsLength = paths.length;
for (let i4 = 0; i4 < pathsLength; i4++) {
const path = paths[i4];
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 i4 = 0; i4 < valueLength; i4++) {
if (typeof value[i4] !== "string" && typeof value[i4] !== "number") {
return prop + "." + i4;
}
}
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 i4 = 0; i4 < valueLength; i4++) {
if (typeof value[i4] !== expectedType) {
return prop + "." + i4;
}
}
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 size = Number(type.slice(7, -1));
switch (true) {
case isNaN(size):
throw createError("INVALID_VECTOR_VALUE", type);
case size <= 0:
throw createError("INVALID_VECTOR_SIZE", type);
default:
return size;
}
}
// 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 i4 = 0; i4 < internalIdToIdLength; i4++) {
const internalIdItem = internalIdToId[i4];
orama.internalDocumentIDStore.idToInternalId.set(internalIdItem, i4 + 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 i4 = 0; i4 < idsLength; i4++) {
const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, ids[i4]);
found[i4] = 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 i4 = 0; i4 < pluginsLength; i4++) {
try {
const plugin = orama.plugins[i4];
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, min, max) {
const result = [];
function traverse(node2) {
if (node2 === null) {
return;
}
if (min < node2.k) {
traverse(node2.l);
}
if (node2.k >= min && node2.k <= max) {
safeArrayPush(result, node2.v);
}
if (max > 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((v6) => v6 !== 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 v6 of value) {
const ids = root2.numberToDocumentId.get(v6);
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(a4, b3, tolerance) {
if (tolerance < 0)
return -1;
if (a4 === b3)
return 0;
const m3 = a4.length;
const n4 = b3.length;
if (m3 === 0)
return n4 <= tolerance ? n4 : -1;
if (n4 === 0)
return m3 <= tolerance ? m3 : -1;
a4 = a4.toLowerCase();
b3 = b3.toLowerCase();
if (b3.startsWith(a4) || a4.startsWith(b3))
return 0;
if (Math.abs(m3 - n4) > tolerance)
return -1;
const matrix = [];
for (let i4 = 0; i4 <= m3; i4++) {
matrix[i4] = [i4];
for (let j3 = 1; j3 <= n4; j3++) {
matrix[i4][j3] = i4 === 0 ? j3 : 0;
}
}
for (let i4 = 1; i4 <= m3; i4++) {
let rowMin = Infinity;
for (let j3 = 1; j3 <= n4; j3++) {
if (a4[i4 - 1] === b3[j3 - 1]) {
matrix[i4][j3] = matrix[i4 - 1][j3 - 1];
} else {
matrix[i4][j3] = Math.min(
matrix[i4 - 1][j3] + 1,
// deletion
matrix[i4][j3 - 1] + 1,
// insertion
matrix[i4 - 1][j3 - 1] + 1
// substitution
);
}
rowMin = Math.min(rowMin, matrix[i4][j3]);
}
if (rowMin > tolerance) {
return -1;
}
}
return matrix[m3][n4] <= tolerance ? matrix[m3][n4] : -1;
}
function syncBoundedLevenshtein(a4, b3, tolerance) {
const distance = _boundedLevenshtein(a4, b3, tolerance);
return {
distance,
isBounded: distance >= 0
};
}
// node_modules/@orama/orama/dist/browser/trees/radix.js
var Node = 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 index = node.d.indexOf(docID);
if (index === -1) {
return false;
}
node.d.splice(index, 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 i4 = 0; i4 < docIDsLength; i4++) {
docs.add(docIDs[i4]);
}
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(a4, b3) {
let commonPrefix = "";
const len = Math.min(a4.length, b3.length);
for (let i4 = 0; i4 < len; i4++) {
if (a4[i4] !== b3[i4]) {
return commonPrefix;
}
commonPrefix += a4[i4];
}
return commonPrefix;
}
function create4(end = false, subWord = "", key = "") {
return new Node(key, subWord, end);
}
function insert3(root2, word, docId) {
const wordLength = word.length;
for (let i4 = 0; i4 < wordLength; i4++) {
const currentCharacter = word[i4];
const wordAtIndex = word.substring(i4);
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(i4 + commonPrefixLength), wordAtCommonPrefix);
addDocument(newNode, docId);
inbetweenNode.c[wordAtCommonPrefix] = newNode;
updateParent(inbetweenNode, root2);
updateParent(newNode, inbetweenNode);
updateParent(inbetweenNodeChild, inbetweenNode);
return;
}
i4 += 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, index, 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 i4 = 0; i4 < docIDsLength; i4++) {
docs.add(docIDs[i4]);
}
output[w2] = Array.from(docs);
}
}
}
if (index >= term.length) {
return;
}
if (term[index] in node.c) {
_findLevenshtein(node.c[term[index]], term, index + 1, tolerance, originalTolerance, output);
}
_findLevenshtein(node, term, index + 1, tolerance - 1, originalTolerance, output);
for (const character in node.c) {
_findLevenshtein(node.c[character], term, index, tolerance - 1, originalTolerance, output);
}
for (const character in node.c) {
if (character !== term[index]) {
_findLevenshtein(node.c[character], term, index + 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 i4 = 0; i4 < termLength; i4++) {
const character = term[i4];
if (character in root2.c) {
const rootChildCurrentChar = root2.c[character];
const edgeLabel = rootChildCurrentChar.s;
const termSubstring = term.substring(i4);
const commonPrefix = getCommonPrefix(edgeLabel, termSubstring);
const commonPrefixLength = commonPrefix.length;
if (commonPrefixLength !== edgeLabel.length && commonPrefixLength !== termSubstring.length) {
if (tolerance)
break;
return {};
}
i4 += 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 i4 = 0; i4 < termLength; i4++) {
const character = term[i4];
if (character in root2.c) {
const rootChildCurrentChar = root2.c[character];
i4 += 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 index = node.docIDs?.indexOf(docID);
if (index !== void 0 && index > -1) {
node.docIDs?.splice(index, 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((a4, b3) => {
const distA = distanceFn(center, a4.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((a4, b3) => {
const distA = sortFn(centroid, a4.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 i4 = 0, j3 = polygonLength - 1; i4 < polygonLength; j3 = i4++) {
const xi = polygon[i4].lon;
const yi = polygon[i4].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 y3 = point.lat;
const polygonLength = polygon.length;
for (let i4 = 0, j3 = polygonLength - 1; i4 < polygonLength; j3 = i4++) {
const xi = polygon[i4].lon;
const yi = polygon[i4].lat;
const xj = polygon[j3].lon;
const yj = polygon[j3].lat;
const intersect2 = yi > y3 !== yj > y3 && x2 < (xj - xi) * (y3 - 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 a4 = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
const c5 = 2 * Math.atan2(Math.sqrt(a4), Math.sqrt(1 - a4));
return EARTH_RADIUS * c5;
}
function vincentyDistance(coord1, coord2) {
const a4 = 6378137;
const f4 = 1 / 298.257223563;
const b3 = (1 - f4) * a4;
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 - f4) * Math.tan(lat1));
const U2 = Math.atan((1 - f4) * 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 = f4 / 16 * cos2Alpha * (4 + f4 * (4 - 3 * cos2Alpha));
prevLambda = lambda;
lambda = deltaLon + (1 - C3) * f4 * sinAlpha * (sigma + C3 * sinSigma * (cos2SigmaM + C3 * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
} while (Math.abs(lambda - prevLambda) > 1e-12 && --iterationLimit > 0);
const u22 = cos2Alpha * (a4 * a4 - 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 i4 = 0; i4 < mapsLength; i4++) {
const arr2 = arrays[i4];
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((a4, b3) => b3[1] - a4[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((a4, b3) => {
if (a4[2] > b3[2])
return -1;
if (a4[2] < b3[2])
return 1;
if (a4[1] > b3[1])
return -1;
if (a4[1] < b3[1])
return 1;
return 0;
});
let lastTokenWithAllKeywords = void 0;
for (let i4 = 0; i4 < allResults; i4++) {
if (keywordsPerToken[i4][2] === keywordsCount) {
lastTokenWithAllKeywords = i4;
} else {
break;
}
}
if (typeof lastTokenWithAllKeywords === "undefined") {
if (threshold === 0) {
return [];
}
lastTokenWithAllKeywords = 0;
}
const keywordsPerTokenLength = keywordsPerToken.length;
const resultsWithIdAndScore = new Array(keywordsPerTokenLength);
for (let i4 = 0; i4 < keywordsPerTokenLength; i4++) {
resultsWithIdAndScore[i4] = [keywordsPerToken[i4][0], keywordsPerToken[i4][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 i4 = 0; i4 < vectorLength; i4++) {
magnitude += vector[i4] * vector[i4];
}
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 i4 = 0; i4 < length; i4++) {
dotProduct += targetVector[i4] * vector[i4];
}
const similarity = dotProduct / (targetMagnitude * magnitude);
if (similarity >= threshold) {
similarVectors.push([vectorId, similarity]);
}
}
return similarVectors.sort((a4, b3) => b3[1] - a4[1]);
}
// node_modules/@orama/orama/dist/browser/components/index.js
function insertDocumentScoreParameters(index, prop, id, tokens, docsCount) {
const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id);
index.avgFieldLength[prop] = ((index.avgFieldLength[prop] ?? 0) * (docsCount - 1) + tokens.length) / docsCount;
index.fieldLengths[prop][internalId] = tokens.length;
index.frequencies[prop][internalId] = {};
}
function insertTokenScoreParameters(index, prop, id, tokens, token) {
let tokenFrequency = 0;
for (const t4 of tokens) {
if (t4 === token) {
tokenFrequency++;
}
}
const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id);
const tf = tokenFrequency / tokens.length;
index.frequencies[prop][internalId][token] = tf;
if (!(token in index.tokenOccurrences[prop])) {
index.tokenOccurrences[prop][token] = 0;
}
index.tokenOccurrences[prop][token] = (index.tokenOccurrences[prop][token] ?? 0) + 1;
}
function removeDocumentScoreParameters(index, prop, id, docsCount) {
const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id);
if (docsCount > 1) {
index.avgFieldLength[prop] = (index.avgFieldLength[prop] * docsCount - index.fieldLengths[prop][internalId]) / (docsCount - 1);
} else {
index.avgFieldLength[prop] = void 0;
}
index.fieldLengths[prop][internalId] = void 0;
index.frequencies[prop][internalId] = void 0;
}
function removeTokenScoreParameters(index, prop, token) {
index.tokenOccurrences[prop][token]--;
}
function calculateResultScores(context, index, prop, term, ids) {
const documentIDs = Array.from(ids);
const avgFieldLength = index.avgFieldLength[prop];
const fieldLengths = index.fieldLengths[prop];
const oramaOccurrences = index.tokenOccurrences[prop];
const oramaFrequencies = index.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(index.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, index, prefix = "") {
if (!index) {
index = {
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, index, path);
continue;
}
if (isVectorType(type)) {
index.searchableProperties.push(path);
index.searchablePropertiesWithTypes[path] = type;
index.vectorIndexes[path] = {
size: getVectorSize(type),
vectors: {}
};
} else {
const isArray2 = /\[/.test(type);
switch (type) {
case "boolean":
case "boolean[]":
index.indexes[path] = { type: "Bool", node: { true: [], false: [] }, isArray: isArray2 };
break;
case "number":
case "number[]":
index.indexes[path] = { type: "AVL", node: create2(0, []), isArray: isArray2 };
break;
case "string":
case "string[]":
index.indexes[path] = { type: "Radix", node: create4(), isArray: isArray2 };
index.avgFieldLength[path] = 0;
index.frequencies[path] = {};
index.tokenOccurrences[path] = {};
index.fieldLengths[path] = {};
break;
case "enum":
case "enum[]":
index.indexes[path] = { type: "Flat", node: create3(), isArray: isArray2 };
break;
case "geopoint":
index.indexes[path] = { type: "BKD", node: create5(), isArray: isArray2 };
break;
default:
throw createError("INVALID_SCHEMA_TYPE", Array.isArray(type) ? "array" : type, path);
}
index.searchableProperties.push(path);
index.searchablePropertiesWithTypes[path] = type;
}
}
return index;
}
function insertScalarBuilder(implementation, index, prop, id, language, tokenizer, docsCount, options) {
return (value) => {
const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id);
const { type, node } = index.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(index, prop, internalId, tokens, docsCount);
for (const token of tokens) {
implementation.insertTokenScoreParameters(index, 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, index, prop, id, value, schemaType, language, tokenizer, docsCount, options) {
if (isVectorType(schemaType)) {
return insertVector(index, prop, value, id);
}
const insertScalar = insertScalarBuilder(implementation, index, prop, id, language, tokenizer, docsCount, options);
if (!isArrayType(schemaType)) {
return insertScalar(value);
}
const elements = value;
const elementsLength = elements.length;
for (let i4 = 0; i4 < elementsLength; i4++) {
insertScalar(elements[i4]);
}
}
function insertVector(index, prop, value, id) {
if (!(value instanceof Float32Array)) {
value = new Float32Array(value);
}
const size = index.vectorIndexes[prop].size;
const magnitude = getMagnitude(value, size);
index.vectorIndexes[prop].vectors[id] = [magnitude, value];
}
function removeScalar(implementation, index, prop, id, value, schemaType, language, tokenizer, docsCount) {
const internalId = getInternalDocumentId(index.sharedInternalDocumentStore, id);
if (isVectorType(schemaType)) {
delete index.vectorIndexes[prop].vectors[id];
return true;
}
const { type, node } = index.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(index, prop, id, docsCount);
for (const token of tokens) {
implementation.removeTokenScoreParameters(index, 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, index, prop, id, value, schemaType, language, tokenizer, docsCount) {
if (!isArrayType(schemaType)) {
return removeScalar(implementation, index, prop, id, value, schemaType, language, tokenizer, docsCount);
}
const innerSchemaType = getInnerType(schemaType);
const elements = value;
const elementsLength = elements.length;
for (let i4 = 0; i4 < elementsLength; i4++) {
removeScalar(implementation, index, prop, id, elements[i4], innerSchemaType, language, tokenizer, docsCount);
}
return true;
}
function search(context, index, prop, term) {
if (!(prop in index.tokenOccurrences)) {
return [];
}
const { node, type } = index.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, index, prop, term, Array.from(ids));
}
function searchByWhereClause(context, index, 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 index.indexes[param] === "undefined") {
throw createError("UNKNOWN_FILTER_PROPERTY", param);
}
const { node, type, isArray: isArray2 } = index.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 t4 of term) {
const filteredIDsResults = find2(node, { term: t4, 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 [min, max] = operationValue;
filteredIDs = rangeSearch(node, min, max);
break;
}
}
safeArrayPush(filtersMap[param], filteredIDs);
}
}
return intersect(Object.values(filtersMap));
}
function getSearchableProperties(index) {
return index.searchableProperties;
}
function getSearchablePropertiesWithTypes(index) {
return index.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(index) {
const { indexes, vectorIndexes, searchableProperties, searchablePropertiesWithTypes, frequencies, tokenOccurrences, avgFieldLength, fieldLengths } = index;
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 name2 of Object.keys(indexes)) {
const { type, node, isArray: isArray2 } = indexes[name2];
if (type !== "Flat") {
savedIndexes[name2] = indexes[name2];
continue;
}
savedIndexes[name2] = {
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 i4 = 0; i4 < orderedDocsLength; i4++) {
const docId = s4.orderedDocs[i4][0];
s4.docs.set(docId, i4);
}
}
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 index = s4.docs.get(internalId);
if (!index)
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((a4, b3) => {
const indexOfA = s4.docs.get(getInternalDocumentId(sorter.sharedInternalDocumentStore, a4[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, v6]) => [+k3, v6])),
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 c4 = "[^aeiou]";
var v5 = "[aeiouy]";
var C2 = c4 + "[^aeiouy]*";
var V = v5 + "[aeiou]*";
var mgr0 = "^(" + C2 + ")?" + V + C2;
var meq1 = "^(" + C2 + ")?" + V + C2 + "(" + V + ")?$";
var mgr1 = "^(" + C2 + ")?" + V + C2 + V + C2;
var s_v = "^(" + C2 + ")?" + v5;
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 + v5 + "[^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 + v5 + "[^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 tokenize2(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: tokenize2,
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 = tokenize2.bind(tokenizer);
tokenizer.normalizeToken = normalizeToken;
return tokenizer;
}
// node_modules/@orama/orama/dist/browser/methods/create.js
function validateComponents(components) {
const defaultComponents = {
formatElapsedTime,
getDocumentIndexId,
getDocumentProperties,
validateSchema
};
for (const rawKey of FUNCTION_COMPONENTS) {
const key = rawKey;
if (components[key]) {
if (typeof components[key] !== "function") {
throw createError("COMPONENT_MUST_BE_FUNCTION", key);
}
} else {
components[key] = defaultComponents[key];
}
}
for (const rawKey of Object.keys(components)) {
if (!OBJECT_COMPONENTS.includes(rawKey) && !FUNCTION_COMPONENTS.includes(rawKey)) {
throw createError("UNSUPPORTED_COMPONENT", rawKey);
}
}
}
function create8({ schema, sort, language, components, id, plugins }) {
if (!components) {
components = {};
}
if (!id) {
id = uniqueId();
}
let tokenizer = components.tokenizer;
let index = components.index;
let documentsStore = components.documentsStore;
let sorter = components.sorter;
if (!tokenizer) {
tokenizer = createTokenizer({ language: language ?? "english" });
} else if (!tokenizer.tokenize) {
tokenizer = createTokenizer(tokenizer);
} else {
const customTokenizer = tokenizer;
tokenizer = customTokenizer;
}
if (components.tokenizer && language) {
throw createError("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");
}
const internalDocumentStore = createInternalDocumentIDStore();
index || (index = createIndex());
sorter || (sorter = createSorter());
documentsStore || (documentsStore = createDocumentsStore());
validateComponents(components);
const { getDocumentProperties: getDocumentProperties2, getDocumentIndexId: getDocumentIndexId2, validateSchema: validateSchema2, formatElapsedTime: formatElapsedTime2 } = components;
const orama = {
data: {},
caches: {},
schema,
tokenizer,
index,
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, 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(index);
const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
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, 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(index);
const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
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, 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(index);
const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
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, 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(index);
const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
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 i4 = 0;
async function _removeMultiple() {
const batch = ids.slice(i4 * batchSize, ++i4 * 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 i4 = 0;
function _removeMultipleSync() {
const batch = ids.slice(i4 * batchSize, ++i4 * 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(a4, b3) {
return a4[1] - b3[1];
}
function sortDesc(a4, b3) {
return b3[1] - a4[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 i4 = 0; i4 < rangesLength; i4++) {
const range = ranges[i4];
tmp[i4] = [`${range.from}-${range.to}`, 0];
}
values = Object.fromEntries(tmp);
}
facets[facet] = {
count: 0,
values: values ?? {}
};
}
const allDocsLength = allDocs.length;
for (let i4 = 0; i4 < allDocsLength; i4++) {
const doc = allDocs[i4];
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 v6 of facetValue) {
calculateNumberFacet(v6);
}
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 v6 of facetValue) {
calculateBooleanStringOrEnumFacet(v6);
}
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, index) => {
acc[index] = 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 i4 = 0; i4 < propertiesLength; i4++) {
const property = properties[i4];
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 i4 = 0; i4 < propertiesLength; i4++) {
const groupByKey = properties[i4];
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 i4 = 0; i4 < combinationsLength; i4++) {
const combination = combinations[i4];
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((a4, b3) => a4 - b3);
if (group.indexes.length === 0) {
continue;
}
groups.push(group);
}
const groupsLength = groups.length;
const res = Array.from({ length: groupsLength });
for (let i4 = 0; i4 < groupsLength; i4++) {
const group = groups[i4];
const reduce = groupBy.reduce || DEFAULT_REDUCE;
const docs = group.indexes.map((index) => {
return {
id: allIDs[index],
score: results[index][1],
document: allDocs[index]
};
});
const func = reduce.reducer.bind(null, group.values);
const initialValue = reduce.getInitialValue(group.indexes.length);
const aggregationValue = docs.reduce(func, initialValue);
res[i4] = {
values: group.values,
result: aggregationValue
};
}
return res;
}
function calculateCombination(arrs, index = 0) {
if (index + 1 === arrs.length)
return arrs[index].map((item) => [item]);
const head = arrs[index];
const c5 = calculateCombination(arrs, index + 1);
const combinations = [];
for (const value of head) {
for (const combination of c5) {
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 = 0, term, properties, threshold = 0, distinctOn, includeVectors = false } = params;
const isPreflight = params.preflight === true;
const { index, docs } = orama.data;
const tokens = orama.tokenizer.tokenize(term ?? "", language);
let propertiesToSearch = orama.caches["propertiesToSearch"];
if (!propertiesToSearch) {
const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
propertiesToSearch = orama.index.getSearchableProperties(index);
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, index, params.where);
}
const tokensLength = tokens.length;
if (tokensLength || properties?.length) {
const indexesLength = propertiesToSearch.length;
for (let i4 = 0; i4 < indexesLength; i4++) {
const prop = propertiesToSearch[i4];
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, index, prop, term2);
safeArrayPush(docIds[term2], scoreList);
}
} else {
docIds[""] = [];
const scoreList = orama.index.search(context, index, 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 i5 = 0; i5 < uniqueDocsLength; i5++) {
const [id, score] = uniqueDocs[i5];
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, i4) => [
uniqueDocsArray[i4][0],
uniqueDocsArray[i4][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, offset, limit2, distinctOn) : fetchDocuments(orama, uniqueDocsArray, offset, 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 = 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, 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(index);
propertiesToSearch = orama.index.getSearchableProperties(index);
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, index, 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 i4 = 0; i4 < limit2; i4++) {
const result = results[i4 + offset];
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[i4] = 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 = 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, 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(index);
propertiesToSearch = orama.index.getSearchableProperties(index);
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, index, 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, offset, 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, docs } = orama.data;
const tokens = orama.tokenizer.tokenize(term, language);
let propertiesToSearch = orama.caches["propertiesToSearch"];
if (!propertiesToSearch) {
const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index);
propertiesToSearch = orama.index.getSearchableProperties(index);
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 i4 = 0; i4 < indexesLength; i4++) {
const prop = propertiesToSearch[i4];
if (tokensLength !== 0) {
for (let j3 = 0; j3 < tokensLength; j3++) {
const term2 = tokens[j3];
const scoreList = orama.index.search(context, index, prop, term2);
safeArrayPush(context.indexMap[prop][term2], scoreList);
}
} else {
const indexMapContent = [];
context.indexMap[prop][""] = indexMapContent;
const scoreList = orama.index.search(context, index, 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 i5 = 0; i5 < uniqueDocsLength; i5++) {
const [id, score] = uniqueDocs[i5];
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((a4, b3) => b3[1] - a4[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 i4 = 0; i4 < textResultsLength; i4++) {
const [id, score] = textResults[i4];
const normalizedScore = normalizeScore(score, maxTextScore);
const hybridScoreValue = hybridScore(normalizedScore, 0);
mergedResults.set(id, hybridScoreValue);
}
const vectorResultsLength = vectorResults.length;
for (let i4 = 0; i4 < vectorResultsLength; i4++) {
const [resultId, score] = vectorResults[i4];
const normalizedScore = normalizeScore(score, maxVectorScore);
const existingRes = mergedResults.get(resultId) ?? 0;
mergedResults.set(resultId, existingRes + hybridScore(0, normalizedScore));
}
return [...mergedResults].sort((a4, b3) => b3[1] - a4[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, index, 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,
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, offset, limit2, distinctOn) {
const docs = orama.data.docs;
const values = /* @__PURE__ */ new Map();
const results = [];
const resultIDs = /* @__PURE__ */ new Set();
const uniqueDocsArrayLength = uniqueDocsArray.length;
let count3 = 0;
for (let i4 = 0; i4 < uniqueDocsArrayLength; i4++) {
const idAndScore = uniqueDocsArray[i4];
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);
count3++;
if (count3 <= offset) {
continue;
}
results.push({ id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, id), score, document: doc });
resultIDs.add(id);
if (count3 >= offset + limit2) {
break;
}
}
return results;
}
function fetchDocuments(orama, uniqueDocsArray, offset, limit2) {
const docs = orama.data.docs;
const results = Array.from({
length: limit2
});
const resultIDs = /* @__PURE__ */ new Set();
for (let i4 = offset; i4 < limit2 + offset; i4++) {
const idAndScore = uniqueDocsArray[i4];
if (typeof idAndScore === "undefined") {
break;
}
const [id, score] = idAndScore;
if (!resultIDs.has(id)) {
const fullDoc = orama.documentsStore.get(docs, id);
results[i4] = { 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
};
}
// node_modules/@orama/orama/dist/browser/methods/update.js
function update(orama, id, doc, language, skipHooks) {
const asyncNeeded = isAsyncFunction(orama.afterInsert) || isAsyncFunction(orama.beforeInsert) || isAsyncFunction(orama.afterRemove) || isAsyncFunction(orama.beforeRemove) || isAsyncFunction(orama.beforeUpdate) || isAsyncFunction(orama.afterUpdate);
if (asyncNeeded) {
return updateAsync(orama, id, doc, language, skipHooks);
}
return updateSync(orama, id, doc, language, skipHooks);
}
async function updateAsync(orama, id, doc, language, skipHooks) {
if (!skipHooks && orama.beforeUpdate) {
await runSingleHook(orama.beforeUpdate, orama, id);
}
await remove5(orama, id, language, skipHooks);
const newId = await insert7(orama, doc, language, skipHooks);
if (!skipHooks && orama.afterUpdate) {
await runSingleHook(orama.afterUpdate, orama, newId);
}
return newId;
}
function updateSync(orama, id, doc, language, skipHooks) {
if (!skipHooks && orama.beforeUpdate) {
runSingleHook(orama.beforeUpdate, orama, id);
}
remove5(orama, id, language, skipHooks);
const newId = insert7(orama, doc, language, skipHooks);
if (!skipHooks && orama.afterUpdate) {
runSingleHook(orama.afterUpdate, orama, newId);
}
return newId;
}
// src/vectorDBManager.ts
var import_crypto_js = __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 i4 = 0; i4 < texts.length; i4 += 1) {
const text = texts[i4];
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[i4].loc && typeof _metadatas[i4].loc === "object" ? { ..._metadatas[i4].loc } : {};
loc.lines = {
from: lineCounterIndex,
to: lineCounterIndex + newLinesCount
};
const metadataWithLinesNumber = {
..._metadatas[i4],
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 i4 = 0; i4 < separators.length; i4 += 1) {
const s4 = separators[i4];
if (s4 === "") {
separator = s4;
break;
}
if (text.includes(s4)) {
separator = s4;
newSeparators = separators.slice(i4 + 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/vectorDBManager.ts
var import_obsidian3 = require("obsidian");
var VectorDBManager = class {
static initialize(config) {
this.config = config;
}
static getRateLimiter() {
if (!this.config) {
throw new Error("VectorDBManager not initialized. Call initialize() first.");
}
const requestsPerSecond = this.config.getEmbeddingRequestsPerSecond();
if (!this.rateLimiter || this.rateLimiter.getRequestsPerSecond() !== requestsPerSecond) {
this.rateLimiter = new RateLimiter(requestsPerSecond);
}
return this.rateLimiter;
}
static getDocHash(sourceDocument) {
return (0, import_crypto_js.MD5)(sourceDocument).toString();
}
static async indexFile(db, embeddingsAPI, fileToSave) {
if (!db)
throw new Error("DB not initialized");
if (!this.config)
throw new Error("VectorDBManager not initialized");
const embeddingModel = EmbeddingManager.getModelName(embeddingsAPI);
if (!embeddingModel)
console.error("EmbeddingManager could not determine model name!");
const textSplitter = RecursiveCharacterTextSplitter.fromLanguage("markdown", {
chunkSize: CHUNK_SIZE
});
const chunks = await textSplitter.createDocuments([fileToSave.content], [], {
chunkHeader: "[[" + fileToSave.title + "]]\n\n---\n\n",
appendChunkOverlapHeader: true
});
const docVectors = [];
try {
for (let i4 = 0; i4 < chunks.length; i4++) {
try {
await this.getRateLimiter().wait();
const embedding = await embeddingsAPI.embedDocuments([chunks[i4].pageContent]);
if (embedding.length > 0) {
docVectors.push(embedding[0]);
} else {
console.error("indexFile - Empty embedding for chunk:", {
index: i4,
length: chunks[i4].pageContent.length
});
}
} catch (error) {
console.error("indexFile - Error during embeddings API call for chunk:", {
index: i4,
length: chunks[i4].pageContent.length,
error
});
if (error instanceof Error) {
new import_obsidian3.Notice(
`Embedding error: please check your embedding model context length, and consider switching to a model with a larger context length: ${error.message}`
);
}
throw error;
}
}
} catch (error) {
console.error("indexFile - Unexpected error during embedding process:", error);
throw error;
}
const chunkWithVectors = docVectors.length > 0 ? chunks.map((chunk, i4) => ({
id: VectorDBManager.getDocHash(chunk.pageContent),
content: chunk.pageContent,
embedding: docVectors[i4]
})) : [];
for (const chunkWithVector of chunkWithVectors) {
try {
const docToSave = {
id: chunkWithVector.id,
title: fileToSave.title,
content: chunkWithVector.content,
embedding: chunkWithVector.embedding,
path: fileToSave.path,
embeddingModel: fileToSave.embeddingModel,
created_at: Date.now(),
ctime: fileToSave.ctime,
mtime: fileToSave.mtime,
tags: Array.isArray(fileToSave.tags) ? fileToSave.tags : [],
extension: fileToSave.extension,
nchars: chunkWithVector.content.length,
metadata: fileToSave.metadata
};
docToSave.tags = docToSave.tags.map((tag) => String(tag));
await this.upsert(db, docToSave);
} catch (err) {
console.error("Error storing vectors in VectorDB:", err);
}
}
}
static async upsert(db, docToSave) {
if (!db)
throw new Error("DB not initialized");
if (!this.config)
throw new Error("VectorDBManager not initialized");
try {
const existingDoc = await search2(db, {
term: docToSave.id,
properties: ["id"],
limit: 1
});
if (existingDoc.hits.length > 0) {
await update(db, docToSave, {
id: docToSave.id
});
if (this.config.debug) {
console.log(`Updated document ${docToSave.id} in VectorDB with path: ${docToSave.path}`);
}
} else {
await insert7(db, docToSave);
if (this.config.debug) {
console.log(`Inserted document ${docToSave.id} in VectorDB with path: ${docToSave.path}`);
}
}
} catch (err) {
console.error(`Error upserting document ${docToSave.id} in VectorDB:`, err);
throw err;
}
}
static async getDocsByPath(db, path) {
if (!db)
throw new Error("DB not initialized");
if (!this.config)
throw new Error("VectorDBManager not initialized");
const result = await search2(db, {
term: path,
properties: ["path"],
limit: 100,
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;
}
}
};
var vectorDBManager_default = VectorDBManager;
// 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 {
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.
*/
_getRelevantDocuments(_query, _callbacks) {
throw new Error("Not implemented!");
}
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(db, vault, llm, embeddingsInstance, options, debug4) {
super();
this.db = db;
this.vault = vault;
this.options = options;
this.debug = debug4;
this.lc_namespace = ["hybrid_retriever"];
this.llm = llm;
this.embeddingsInstance = embeddingsInstance;
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);
const uniqueChunks = new Set(explicitChunks.map((chunk) => chunk.pageContent));
const combinedChunks = [...explicitChunks];
for (const chunk of oramaChunks) {
const chunkContent = chunk.pageContent;
if (!uniqueChunks.has(chunkContent)) {
uniqueChunks.add(chunkContent);
combinedChunks.push(chunk);
}
}
if (this.debug) {
console.log("*** HYBRID RETRIEVER DEBUG INFO: ***");
if (config?.runName !== "no_hyde") {
console.log("\nOriginal Query: ", query);
console.log("\nRewritten Query: ", rewrittenQuery);
}
console.log(
"\nNote Titles extracted: ",
noteTitles,
"\n\nExplicit Chunks:",
explicitChunks,
"\n\nOrama Chunks:",
oramaChunks,
"\n\nCombined Chunks:",
combinedChunks
);
}
return combinedChunks.slice(0, this.options.maxK);
}
async rewriteQuery(query) {
try {
const promptResult = await this.queryRewritePrompt.format({ question: query });
const rewrittenQueryObject = await this.llm.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(this.vault, noteTitle);
const hits = await vectorDBManager_default.getDocsByPath(this.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;
}
async getOramaChunks(query) {
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 searchResults = await search2(this.db, {
mode: "vector",
vector: {
value: queryVector,
property: "embedding"
},
similarity: this.options.minSimilarityScore,
limit: this.options.maxK,
includeVectors: true
});
const vectorChunks = searchResults.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
}
})
);
return vectorChunks;
}
async convertQueryToVector(query) {
return await this.embeddingsInstance.embedQuery(query);
}
};
// src/LLMProviders/chainManager.ts
init_prompts3();
var import_obsidian5 = require("obsidian");
// 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: () => APIConnectionError5,
APIConnectionTimeoutError: () => APIConnectionTimeoutError5,
APIError: () => APIError5,
APIUserAbortError: () => APIUserAbortError5,
AuthenticationError: () => AuthenticationError5,
BadRequestError: () => BadRequestError5,
ConflictError: () => ConflictError5,
GroqError: () => GroqError,
InternalServerError: () => InternalServerError5,
NotFoundError: () => NotFoundError5,
PermissionDeniedError: () => PermissionDeniedError5,
RateLimitError: () => RateLimitError5,
UnprocessableEntityError: () => UnprocessableEntityError5
});
var GroqError = class extends Error {
};
var APIError5 = class extends GroqError {
constructor(status, error, message, headers) {
super(`${APIError5.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 APIConnectionError5({ cause: castToError3(errorResponse) });
}
const error = errorResponse;
if (status === 400) {
return new BadRequestError5(status, error, message, headers);
}
if (status === 401) {
return new AuthenticationError5(status, error, message, headers);
}
if (status === 403) {
return new PermissionDeniedError5(status, error, message, headers);
}
if (status === 404) {
return new NotFoundError5(status, error, message, headers);
}
if (status === 409) {
return new ConflictError5(status, error, message, headers);
}
if (status === 422) {
return new UnprocessableEntityError5(status, error, message, headers);
}
if (status === 429) {
return new RateLimitError5(status, error, message, headers);
}
if (status >= 500) {
return new InternalServerError5(status, error, message, headers);
}
return new APIError5(status, error, message, headers);
}
};
var APIUserAbortError5 = class extends APIError5 {
constructor({ message } = {}) {
super(void 0, void 0, message || "Request was aborted.", void 0);
this.status = void 0;
}
};
var APIConnectionError5 = class extends APIError5 {
constructor({ message, cause }) {
super(void 0, void 0, message || "Connection error.", void 0);
this.status = void 0;
if (cause)
this.cause = cause;
}
};
var APIConnectionTimeoutError5 = class extends APIConnectionError5 {
constructor({ message } = {}) {
super({ message: message ?? "Request timed out." });
}
};
var BadRequestError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 400;
}
};
var AuthenticationError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 401;
}
};
var PermissionDeniedError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 403;
}
};
var NotFoundError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 404;
}
};
var ConflictError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 409;
}
};
var UnprocessableEntityError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 422;
}
};
var RateLimitError5 = class extends APIError5 {
constructor() {
super(...arguments);
this.status = 429;
}
};
var InternalServerError5 = class extends APIError5 {
};
// 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 (e4) {
console.error(`Could not parse message into JSON:`, sse.data);
console.error(`From chunk:`, sse.raw);
throw e4;
}
if (data && data.error) {
throw new APIError5(void 0, data.error, void 0, void 0);
}
yield data;
}
}
done = true;
} catch (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 (e4) {
if (e4 instanceof Error && e4.name === "AbortError")
return;
throw e4;
} 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 index = str2.indexOf(delimiter);
if (index !== -1) {
return [str2.substring(0, index), delimiter, str2.substring(index + 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 (e4) {
reader.releaseLock();
throw e4;
}
},
async return() {
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
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, name2, options) {
value = await value;
options ?? (options = isFileLike3(value) ? { lastModified: value.lastModified, type: value.type } : {});
if (isResponseLike3(value)) {
const blob = await value.blob();
name2 || (name2 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
return new File4([blob], name2, options);
}
const bits = await getBytes3(value);
name2 || (name2 = getName3(value) ?? "unknown_file");
if (!options.type) {
const type = bits[0]?.type;
if (typeof type === "string") {
options = { ...options, type };
}
}
return new File4(bits, name2, 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((p4) => `"${p4}"`).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(([name2, prop]) => addFormValue2(form, `${key}[${name2}]`, 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, f4) {
if (kind4 === "m")
throw new TypeError("Private method is not writable");
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot write private member to an object whose class did not declare it");
return kind4 === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet14 = function(receiver, state, kind4, f4) {
if (kind4 === "a" && !f4)
throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver))
throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind4 === "m" ? f4 : kind4 === "a" ? f4.call(receiver) : f4 ? f4.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((p4) => p4.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 APIError5.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 APIUserAbortError5();
}
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 APIUserAbortError5();
}
if (retriesRemaining) {
return this.retryRequest(options, retriesRemaining);
}
if (response.name === "AbortError") {
throw new APIConnectionTimeoutError5();
}
throw new APIConnectionError5({ 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((e4) => castToError3(e4).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, init2, ms, controller) {
const { signal, ...options } = init2 || {};
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(client, response, body, options) {
_AbstractPage_client3.set(this, void 0);
__classPrivateFieldSet13(this, _AbstractPage_client3, client, "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(client, request, Page2) {
super(request, async (props) => new Page2(client, 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, name2) {
const key = name2.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 match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[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 = (platform) => {
platform = platform.toLowerCase();
if (platform.includes("ios"))
return "iOS";
if (platform === "android")
return "Android";
if (platform === "darwin")
return "MacOS";
if (platform === "win32")
return "Windows";
if (platform === "freebsd")
return "FreeBSD";
if (platform === "openbsd")
return "OpenBSD";
if (platform === "linux")
return "Linux";
if (platform)
return `Other:${platform}`;
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 = (name2, n4) => {
if (typeof n4 !== "number" || !Number.isInteger(n4)) {
throw new GroqError(`${name2} must be an integer`);
}
if (n4 < 0) {
throw new GroqError(`${name2} 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, (c5) => {
const r4 = Math.random() * 16 | 0;
const v6 = c5 === "x" ? r4 : r4 & 3 | 8;
return v6.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(client) {
this._client = client;
}
};
// 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 = APIError5;
Groq.APIConnectionError = APIConnectionError5;
Groq.APIConnectionTimeoutError = APIConnectionTimeoutError5;
Groq.APIUserAbortError = APIUserAbortError5;
Groq.NotFoundError = NotFoundError5;
Groq.ConflictError = ConflictError5;
Groq.RateLimitError = RateLimitError5;
Groq.BadRequestError = BadRequestError5;
Groq.AuthenticationError = AuthenticationError5;
Groq.InternalServerError = InternalServerError5;
Groq.PermissionDeniedError = PermissionDeniedError5;
Groq.UnprocessableEntityError = UnprocessableEntityError5;
Groq.toFile = toFile3;
Groq.fileFromPath = fileFromPath3;
var { GroqError: GroqError2, APIError: APIError6, APIConnectionError: APIConnectionError6, APIConnectionTimeoutError: APIConnectionTimeoutError6, APIUserAbortError: APIUserAbortError6, NotFoundError: NotFoundError6, ConflictError: ConflictError6, RateLimitError: RateLimitError6, BadRequestError: BadRequestError6, AuthenticationError: AuthenticationError6, InternalServerError: InternalServerError6, PermissionDeniedError: PermissionDeniedError6, UnprocessableEntityError: UnprocessableEntityError6 } = 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 (e4) {
invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e4.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, index) {
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
}));
}
function _convertDeltaToMessageChunk2(delta, index, 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, index);
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 ?? index,
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 || getEnvironmentVariable("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((tool) => convertToOpenAITool(tool)),
...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((t4) => t4.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 index = chunk.generationInfo?.completion ?? 0;
if (finalChunks[index] === void 0) {
finalChunks[index] = chunk;
} else {
finalChunks[index] = finalChunks[index].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 name2 = config?.name;
const method = config?.method;
const includeRaw = config?.includeRaw;
let functionName = name2 ?? "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_obsidian4 = require("obsidian");
var ChatModelManager = class {
constructor(getLangChainParams, encryptionService, activeModels) {
this.getLangChainParams = getLangChainParams;
this.encryptionService = encryptionService;
this.buildModelMap(activeModels);
}
static getInstance(getLangChainParams, encryptionService, activeModels) {
if (!ChatModelManager.instance) {
ChatModelManager.instance = new ChatModelManager(
getLangChainParams,
encryptionService,
activeModels
);
}
return ChatModelManager.instance;
}
getModelConfig(customModel) {
const decrypt = (key) => this.encryptionService.getDecryptedKey(key);
const params = this.getLangChainParams();
const baseConfig = {
modelName: customModel.name,
temperature: params.temperature,
streaming: true,
maxRetries: 3,
maxConcurrency: 3,
enableCors: customModel.enableCors
};
const providerConfig = {
["openai" /* OPENAI */]: {
modelName: customModel.name,
openAIApiKey: decrypt(customModel.apiKey || params.openAIApiKey),
openAIOrgId: decrypt(params.openAIOrgId),
maxTokens: params.maxTokens
},
["anthropic" /* ANTHROPIC */]: {
anthropicApiKey: decrypt(customModel.apiKey || params.anthropicApiKey),
modelName: customModel.name
},
["azure openai" /* AZURE_OPENAI */]: {
maxTokens: params.maxTokens,
azureOpenAIApiKey: decrypt(customModel.apiKey || params.azureOpenAIApiKey),
azureOpenAIApiInstanceName: params.azureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName: params.azureOpenAIApiDeploymentName,
azureOpenAIApiVersion: params.azureOpenAIApiVersion
},
["cohereai" /* COHEREAI */]: {
apiKey: decrypt(customModel.apiKey || params.cohereApiKey),
model: customModel.name
},
["google" /* GOOGLE */]: {
apiKey: decrypt(customModel.apiKey || params.googleApiKey),
modelName: customModel.name
},
["openrouterai" /* OPENROUTERAI */]: {
modelName: customModel.name,
openAIApiKey: decrypt(customModel.apiKey || params.openRouterAiApiKey),
openAIProxyBaseUrl: "https://openrouter.ai/api/v1"
},
["groq" /* GROQ */]: {
apiKey: decrypt(customModel.apiKey || params.groqApiKey),
modelName: customModel.name
},
["ollama" /* OLLAMA */]: {
// ChatOllama has `model` instead of `modelName`!!
model: customModel.name,
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: customModel.name,
openAIApiKey: customModel.apiKey || "default-key",
openAIProxyBaseUrl: customModel.baseUrl || "http://localhost:1234/v1"
},
["3rd party (openai-format)" /* OPENAI_FORMAT */]: {
modelName: customModel.name,
openAIApiKey: decrypt(customModel.apiKey || "default-key"),
maxTokens: params.maxTokens,
openAIProxyBaseUrl: customModel.baseUrl || ""
}
};
const selectedProviderConfig = providerConfig[customModel.provider] || {};
return { ...baseConfig, ...selectedProviderConfig };
}
// Build a map of modelKey to model config
buildModelMap(activeModels) {
ChatModelManager.modelMap = {};
const modelMap = ChatModelManager.modelMap;
const allModels = activeModels ?? BUILTIN_CHAT_MODELS;
allModels.forEach((model) => {
if (model.enabled) {
let constructor;
let apiKey;
switch (model.provider) {
case "openai" /* OPENAI */:
constructor = ChatOpenAI;
apiKey = model.apiKey || this.getLangChainParams().openAIApiKey;
break;
case "google" /* GOOGLE */:
constructor = ChatGoogleGenerativeAI;
apiKey = model.apiKey || this.getLangChainParams().googleApiKey;
break;
case "azure openai" /* AZURE_OPENAI */:
constructor = ChatOpenAI;
apiKey = model.apiKey || this.getLangChainParams().azureOpenAIApiKey;
break;
case "anthropic" /* ANTHROPIC */:
constructor = ChatAnthropicWrapped;
apiKey = model.apiKey || this.getLangChainParams().anthropicApiKey;
break;
case "cohereai" /* COHEREAI */:
constructor = ChatCohere;
apiKey = model.apiKey || this.getLangChainParams().cohereApiKey;
break;
case "openrouterai" /* OPENROUTERAI */:
constructor = ProxyChatOpenAI;
apiKey = model.apiKey || this.getLangChainParams().openRouterAiApiKey;
break;
case "ollama" /* OLLAMA */:
constructor = ChatOllama;
apiKey = model.apiKey || "default-key";
break;
case "lm-studio" /* LM_STUDIO */:
constructor = ProxyChatOpenAI;
apiKey = model.apiKey || "default-key";
break;
case "groq" /* GROQ */:
constructor = ChatGroq;
apiKey = model.apiKey || this.getLangChainParams().groqApiKey;
break;
case "3rd party (openai-format)" /* OPENAI_FORMAT */:
constructor = ProxyChatOpenAI;
apiKey = model.apiKey || "default-key";
break;
default:
console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`);
return;
}
const modelKey = `${model.name}|${model.provider}`;
modelMap[modelKey] = {
hasApiKey: Boolean(model.apiKey || apiKey),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
AIConstructor: constructor,
vendor: model.provider
};
}
});
}
getChatModel() {
return ChatModelManager.chatModel;
}
setChatModel(model) {
const modelKey = `${model.name}|${model.provider}`;
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_obsidian4.Notice(errorMessage);
throw new Error(errorMessage);
}
const modelConfig = this.getModelConfig(model);
this.getLangChainParams().modelKey = `${model.name}|${model.provider}`;
new import_obsidian4.Notice(`Setting model: ${modelConfig.modelName}`);
try {
const newModelInstance = new selectedModel.AIConstructor({
...modelConfig
});
ChatModelManager.chatModel = newModelInstance;
} catch (error) {
console.error(error);
new import_obsidian4.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);
}
};
// 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) {
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(langChainParams) {
this.langChainParams = langChainParams;
this.initMemory();
}
static getInstance(langChainParams) {
if (!MemoryManager.instance) {
MemoryManager.instance = new MemoryManager(langChainParams);
}
return MemoryManager.instance;
}
initMemory() {
this.memory = new BufferWindowMemory({
k: this.langChainParams.chatContextTurns * 2,
memoryKey: "history",
inputKey: "input",
returnMessages: true
});
}
getMemory() {
return this.memory;
}
clearChatMemory() {
console.log("clearing chat memory");
this.memory.clear();
}
};
// src/LLMProviders/promptManager.ts
init_prompts3();
var PromptManager = class {
constructor(langChainParams) {
this.langChainParams = langChainParams;
this.initChatPrompt();
}
static getInstance(langChainParams) {
if (!PromptManager.instance) {
PromptManager.instance = new PromptManager(langChainParams);
}
return PromptManager.instance;
}
initChatPrompt() {
const escapedSystemMessage = this.escapeTemplateString(this.langChainParams.systemMessage);
this.chatPrompt = ChatPromptTemplate.fromMessages([
SystemMessagePromptTemplate.fromTemplate(escapedSystemMessage),
new MessagesPlaceholder("history"),
HumanMessagePromptTemplate.fromTemplate("{input}")
]);
}
// Add this new method to escape curly braces
escapeTemplateString(str2) {
return str2.replace(/\{/g, "{{").replace(/\}/g, "}}");
}
getChatPrompt() {
return this.chatPrompt;
}
};
// src/LLMProviders/chainManager.ts
var _ChainManager = class {
constructor(app2, getLangChainParams, encryptionService, settings, vectorStoreManager) {
this.app = app2;
this.langChainParams = getLangChainParams();
this.settings = settings;
this.vectorStoreManager = vectorStoreManager;
this.memoryManager = MemoryManager.getInstance(this.getLangChainParams());
this.encryptionService = encryptionService;
this.chatModelManager = ChatModelManager.getInstance(
() => this.getLangChainParams(),
encryptionService,
this.settings.activeModels
);
this.embeddingsManager = this.vectorStoreManager.getEmbeddingsManager();
this.promptManager = PromptManager.getInstance(this.getLangChainParams());
this.createChainWithNewModel(this.getLangChainParams().modelKey);
}
getLangChainParams() {
return this.langChainParams;
}
setLangChainParam(key, value) {
this.langChainParams[key] = value;
}
setNoteFile(noteFile) {
this.setLangChainParam("options", { ...this.getLangChainParams().options, noteFile });
}
validateChainType(chainType) {
if (chainType === void 0 || chainType === null)
throw new Error("No chain type set");
}
findCustomModel(modelKey) {
const [name2, provider] = modelKey.split("|");
return this.settings.activeModels.find(
(model) => model.name === name2 && model.provider === provider
);
}
static storeRetrieverDocuments(documents) {
_ChainManager.retrievedDocuments = documents;
}
/**
* Update the active model and create a new chain
* with the specified model name.
*
* @param {string} newModel - the name of the new model in the dropdown
* @return {void}
*/
createChainWithNewModel(newModelKey) {
try {
let customModel = this.findCustomModel(newModelKey);
if (!customModel) {
console.error("Resetting default model. No model configuration found for: ", newModelKey);
customModel = BUILTIN_CHAT_MODELS[0];
newModelKey = customModel.name + "|" + customModel.provider;
}
this.setLangChainParam("modelKey", newModelKey);
this.chatModelManager.setChatModel(customModel);
this.createChain(this.getLangChainParams().chainType, {
...this.getLangChainParams().options,
forceNewCreation: true
});
console.log(`Setting model to ${newModelKey}`);
} catch (error) {
console.error("createChainWithNewModel failed: ", error);
console.log("modelKey:", this.getLangChainParams().modelKey);
}
}
/* Create a new chain, or update chain with new model */
createChain(chainType, options) {
this.validateChainType(chainType);
try {
this.setChain(chainType, options);
} catch (error) {
new import_obsidian5.Notice("Error creating chain:", error);
console.error("Error creating chain:", error);
}
}
async setChain(chainType, options = {}) {
if (!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())) {
console.error("setChain failed: No chat model set.");
return;
}
this.validateChainType(chainType);
if (chainType === "vault_qa" /* VAULT_QA_CHAIN */) {
this.embeddingsManager = EmbeddingManager.getInstance(
() => this.getLangChainParams(),
this.encryptionService,
this.settings.activeEmbeddingModels
);
}
const chatModel = this.chatModelManager.getChatModel();
const memory = this.memoryManager.getMemory();
const chatPrompt = this.promptManager.getChatPrompt();
switch (chainType) {
case "llm_chain" /* LLM_CHAIN */: {
if (options.forceNewCreation) {
_ChainManager.chain = chainFactory_default.createNewLLMChain({
llm: chatModel,
memory,
prompt: options.prompt || chatPrompt,
abortController: options.abortController
});
} else {
_ChainManager.chain = chainFactory_default.getLLMChainFromMap({
llm: chatModel,
memory,
prompt: options.prompt || chatPrompt,
abortController: options.abortController
});
}
this.setLangChainParam("chainType", "llm_chain" /* LLM_CHAIN */);
break;
}
case "vault_qa" /* VAULT_QA_CHAIN */: {
const embeddingsAPI = this.embeddingsManager.getEmbeddingsAPI();
if (!embeddingsAPI) {
console.error("Error getting embeddings API. Please check your settings.");
return;
}
const retriever = new HybridRetriever(
this.vectorStoreManager.getDb(),
this.app.vault,
chatModel,
embeddingsAPI,
{
minSimilarityScore: 0.3,
maxK: this.settings.maxSourceChunks
},
options.debug
);
_ChainManager.retrievalChain = chainFactory_default.createConversationalRetrievalChain(
{
llm: chatModel,
retriever,
systemMessage: this.getLangChainParams().systemMessage
},
_ChainManager.storeRetrieverDocuments.bind(_ChainManager),
options.debug
);
this.setLangChainParam("chainType", "vault_qa" /* VAULT_QA_CHAIN */);
if (options.debug) {
console.log("New Vault QA chain with hybrid retriever created for entire vault");
console.log("Set chain:", "vault_qa" /* VAULT_QA_CHAIN */);
}
break;
}
default:
this.validateChainType(chainType);
break;
}
}
async runChain(userMessage, abortController, updateCurrentAiMessage, addMessage, options = {}) {
const { debug: debug4 = false, ignoreSystemMessage = false } = options;
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_obsidian5.Notice(errorMsg);
console.error(errorMsg);
return;
}
if (!_ChainManager.chain || !isSupportedChain(_ChainManager.chain)) {
console.error(
"Chain is not initialized properly, re-initializing chain: ",
this.getLangChainParams().chainType
);
this.setChain(this.getLangChainParams().chainType, this.getLangChainParams().options);
}
const { temperature, maxTokens, systemMessage, chatContextTurns, chainType } = this.getLangChainParams();
const memory = this.memoryManager.getMemory();
const chatPrompt = this.promptManager.getChatPrompt();
const systemPrompt = ignoreSystemMessage ? "" : systemMessage;
if (ignoreSystemMessage) {
const effectivePrompt = ignoreSystemMessage ? ChatPromptTemplate.fromMessages([
new MessagesPlaceholder("history"),
HumanMessagePromptTemplate.fromTemplate("{input}")
]) : chatPrompt;
this.setChain(chainType, {
...this.getLangChainParams().options,
prompt: effectivePrompt
});
} else {
this.setChain(chainType, this.getLangChainParams().options);
}
let fullAIResponse = "";
const chatModel = _ChainManager.chain.last.bound;
const chatStream = await _ChainManager.chain.stream({
input: userMessage
// eslint-disable-next-line @typescript-eslint/no-explicit-any
});
try {
switch (chainType) {
case "llm_chain" /* LLM_CHAIN */:
if (debug4) {
console.log(
`*** DEBUG INFO ***
user message: ${userMessage}
model: ${chatModel.modelName || chatModel.model}
chain type: ${chainType}
temperature: ${temperature}
maxTokens: ${maxTokens}
system prompt: ${systemPrompt}
chat context turns: ${chatContextTurns}
`
);
console.log("chain RunnableSequence:", _ChainManager.chain);
console.log("Chat memory:", memory);
}
for await (const chunk of chatStream) {
if (abortController.signal.aborted)
break;
fullAIResponse += chunk.content;
updateCurrentAiMessage(fullAIResponse);
}
break;
case "vault_qa" /* VAULT_QA_CHAIN */:
if (debug4) {
console.log(
`*** DEBUG INFO ***
user message: ${userMessage}
model: ${chatModel.modelName || chatModel.model}
chain type: ${chainType}
temperature: ${temperature}
maxTokens: ${maxTokens}
system prompt: ${systemPrompt}
chat context turns: ${chatContextTurns}
`
);
console.log("chain RunnableSequence:", _ChainManager.chain);
console.log("embedding model:", this.getLangChainParams().embeddingModelKey);
}
fullAIResponse = await this.runRetrievalChain(
userMessage,
memory,
updateCurrentAiMessage,
abortController,
{ debug: debug4 }
);
break;
default:
console.error("Chain type not supported:", this.getLangChainParams().chainType);
}
} catch (error) {
const errorData = error?.response?.data?.error || error;
const errorCode = errorData?.code || error;
if (errorCode === "model_not_found") {
const modelNotFoundMsg = "You do not have access to this model or the model does not exist, please check with your API provider.";
new import_obsidian5.Notice(modelNotFoundMsg);
console.error(modelNotFoundMsg);
} else {
new import_obsidian5.Notice(`LangChain error: ${errorCode}`);
console.error(errorData);
}
} finally {
if (fullAIResponse && abortController.signal.reason !== "new-chat" /* NEW_CHAT */) {
await memory.saveContext({ input: userMessage }, { output: fullAIResponse });
addMessage({
message: fullAIResponse,
sender: AI_SENDER,
isVisible: true,
timestamp: formatDateTime(new Date())
});
}
updateCurrentAiMessage("");
}
return fullAIResponse;
}
async runRetrievalChain(userMessage, memory, updateCurrentAiMessage, abortController, options = {}) {
const memoryVariables = await memory.loadMemoryVariables({});
const chatHistory = extractChatHistory(memoryVariables);
const qaStream = await _ChainManager.retrievalChain.stream({
question: userMessage,
chat_history: chatHistory
// eslint-disable-next-line @typescript-eslint/no-explicit-any
});
let fullAIResponse = "";
for await (const chunk of qaStream) {
if (abortController.signal.aborted)
break;
fullAIResponse += chunk.content;
updateCurrentAiMessage(fullAIResponse);
}
if (options.debug) {
console.log("Max source chunks:", this.settings.maxSourceChunks);
console.log("Retrieved chunks:", _ChainManager.retrievedDocuments);
}
if (this.getLangChainParams().chainType === "vault_qa" /* VAULT_QA_CHAIN */) {
const docTitles = extractUniqueTitlesFromDocs(_ChainManager.retrievedDocuments);
if (docTitles.length > 0) {
const markdownLinks = docTitles.map(
(title) => `- [${title}](obsidian://open?vault=${encodeURIComponent(this.app.vault.getName())}&file=${encodeURIComponent(
title
)})`
).join("\n");
fullAIResponse += "\n\n#### Sources:\n" + markdownLinks;
}
}
return fullAIResponse;
}
async indexFile(noteFile) {
const embeddingsAPI = this.embeddingsManager.getEmbeddingsAPI();
if (!embeddingsAPI) {
const errorMsg = "Failed to load file, embedding API is not set correctly, please check your settings.";
new import_obsidian5.Notice(errorMsg);
console.error(errorMsg);
return;
}
return await vectorDBManager_default.indexFile(
this.vectorStoreManager.getDb(),
embeddingsAPI,
noteFile
);
}
async updateMemoryWithLoadedMessages(messages) {
await this.memoryManager.clearChatMemory();
for (let i4 = 0; i4 < messages.length; i4 += 2) {
const userMsg = messages[i4];
const aiMsg = messages[i4 + 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/VectorStoreManager.ts
var import_crypto_js2 = __toESM(require_crypto_js());
var import_obsidian6 = require("obsidian");
var VectorStoreManager = class {
constructor(app2, settings, encryptionService, getLangChainParams) {
this.isIndexingPaused = false;
this.isIndexingCancelled = false;
this.currentIndexingNotice = null;
this.indexNoticeMessage = null;
this.indexedCount = 0;
this.totalFilesToIndex = 0;
this.app = app2;
this.settings = settings;
this.encryptionService = encryptionService;
this.getLangChainParams = getLangChainParams;
this.dbPath = this.getDbPath();
this.embeddingsManager = EmbeddingManager.getInstance(
this.getLangChainParams,
this.encryptionService,
this.settings.activeEmbeddingModels
);
this.initializationPromise = this.initializeDB().then((db) => {
this.oramaDb = db;
console.log("Copilot database initialized successfully.");
this.performPostInitializationTasks();
}).catch((error) => {
console.error("Failed to initialize Copilot database:", error);
});
vectorDBManager_default.initialize({
getEmbeddingRequestsPerSecond: () => this.settings.embeddingRequestsPerSecond,
debug: this.settings.debug
});
}
async performPostInitializationTasks() {
if (this.settings.indexVaultToVectorStore === "ON STARTUP" /* ON_STARTUP */) {
try {
await this.indexVaultToVectorStore();
} catch (err) {
console.error("Error indexing vault to vector store on startup:", err);
new import_obsidian6.Notice("An error occurred while indexing vault to vector store.");
}
}
}
getDbPath() {
return `${this.app.vault.configDir}/copilot-index-${this.getVaultIdentifier()}.json`;
}
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 initializeDB() {
this.dbPath = this.getDbPath();
const configDir = this.app.vault.configDir;
if (!await this.app.vault.adapter.exists(configDir)) {
console.log(`Config directory does not exist. Creating: ${configDir}`);
await this.app.vault.adapter.mkdir(configDir);
}
try {
if (await this.app.vault.adapter.exists(this.dbPath)) {
const savedDb = await this.app.vault.adapter.read(this.dbPath);
const parsedDb = JSON.parse(savedDb);
const schema = parsedDb.schema;
const newDb = await create8({ schema });
await load5(newDb, parsedDb);
console.log(`Loaded existing Orama database for ${this.dbPath} from disk.`);
return newDb;
} else {
return await this.createNewDb();
}
} catch (error) {
console.error(`Error initializing Orama database:`, error);
return await this.createNewDb();
}
}
async createNewDb() {
const embeddingInstance = this.embeddingsManager.getEmbeddingsAPI();
if (!embeddingInstance) {
throw new CustomError("Embedding instance not found.");
}
const vectorLength = await this.getVectorLength(embeddingInstance);
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}.`
);
return db;
}
async getVectorLength(embeddingInstance) {
const sampleText = "Sample text for embedding";
const sampleEmbedding = await embeddingInstance.embedQuery(sampleText);
return sampleEmbedding.length;
}
async ensureCorrectSchema(db, embeddingInstance) {
const currentVectorLength = await this.getVectorLength(embeddingInstance);
const dbSchema = db.schema;
if (dbSchema.embedding !== `vector[${currentVectorLength}]`) {
console.log(
`Schema mismatch detected. Rebuilding database with new vector length: ${currentVectorLength}`
);
await this.clearVectorStore();
}
}
async saveDB() {
try {
const rawData = await save5(this.oramaDb);
const dataToSave = {
schema: this.oramaDb.schema,
...rawData
};
await this.app.vault.adapter.write(this.dbPath, JSON.stringify(dataToSave));
console.log(`Saved Orama database to ${this.dbPath}.`);
} catch (error) {
console.error(`Error saving Orama database to ${this.dbPath}:`, error);
}
}
getVaultIdentifier() {
const vaultName = this.app.vault.getName();
return (0, import_crypto_js2.MD5)(vaultName).toString();
}
getDb() {
return this.oramaDb;
}
getEmbeddingsManager() {
return this.embeddingsManager;
}
pauseIndexing() {
this.isIndexingPaused = true;
this.updateIndexingNoticeMessage();
}
resumeIndexing() {
this.isIndexingPaused = false;
this.updateIndexingNoticeMessage();
}
updateIndexingNoticeMessage() {
if (this.indexNoticeMessage) {
const status = this.isIndexingPaused ? " (Paused)" : "";
this.indexNoticeMessage.textContent = `Copilot is indexing your vault...
${this.indexedCount}/${this.totalFilesToIndex} files processed.${status}
Exclusions: ${this.settings.qaExclusions ? this.settings.qaExclusions : "None"}`;
}
}
createIndexingNotice() {
const frag = document.createDocumentFragment();
const container = frag.createEl("div", { cls: "copilot-notice-container" });
this.indexNoticeMessage = container.createEl("div", { cls: "copilot-notice-message" });
this.updateIndexingNoticeMessage();
const pauseButton = frag.createEl("button");
pauseButton.textContent = "Pause";
pauseButton.addEventListener("click", (event) => {
event.stopPropagation();
event.preventDefault();
if (this.isIndexingPaused) {
this.resumeIndexing();
pauseButton.textContent = "Pause";
} else {
this.pauseIndexing();
pauseButton.textContent = "Resume";
}
});
frag.appendChild(this.indexNoticeMessage);
frag.appendChild(pauseButton);
return new import_obsidian6.Notice(frag, 0);
}
async getExcludedFiles() {
const excludedFiles = /* @__PURE__ */ new Set();
if (this.settings.qaExclusions) {
const exclusions = this.settings.qaExclusions.split(",").map((item) => item.trim());
for (const exclusion of exclusions) {
if (exclusion.startsWith("#")) {
const tagName = exclusion.slice(1);
const taggedFiles = await getNotesFromTags(this.app.vault, [tagName]);
taggedFiles.forEach((file) => excludedFiles.add(file.path));
} else if (exclusion.startsWith("*")) {
const extensionName = exclusion.slice(1);
this.app.vault.getFiles().forEach((file) => {
if (file.name.toLowerCase().contains(extensionName.toLowerCase())) {
excludedFiles.add(file.path);
}
});
} else {
this.app.vault.getFiles().forEach((file) => {
if (isPathInList(file.path, exclusion)) {
excludedFiles.add(file.path);
}
});
}
}
}
return excludedFiles;
}
async indexVaultToVectorStore(overwrite) {
await this.waitForInitialization();
let rateLimitNoticeShown = false;
try {
const embeddingInstance = this.embeddingsManager.getEmbeddingsAPI();
if (!embeddingInstance) {
throw new CustomError("Embedding instance not found.");
}
await this.ensureCorrectSchema(this.oramaDb, embeddingInstance);
const singleDoc = await search2(this.getDb(), {
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)) {
await this.initializeDB();
overwrite = true;
new import_obsidian6.Notice("Detected change in embedding model. Rebuilding vector store from scratch.");
console.log("Detected change in embedding model. Rebuilding vector store from scratch.");
}
} else {
console.log("No previous embedding model found in the database.");
}
const latestMtime = await vectorDBManager_default.getLatestFileMtime(this.oramaDb);
this.isIndexingPaused = false;
this.isIndexingCancelled = false;
const excludedFiles = await this.getExcludedFiles();
const files = this.app.vault.getMarkdownFiles().filter((file) => {
if (!latestMtime || overwrite)
return true;
return file.stat.mtime > latestMtime;
}).filter((file) => !excludedFiles.has(file.path));
const fileContents = await Promise.all(
files.map((file) => this.app.vault.cachedRead(file))
);
const fileMetadatas = files.map((file) => this.app.metadataCache.getFileCache(file));
const totalFiles = files.length;
if (totalFiles === 0) {
new import_obsidian6.Notice("Copilot vault index is up-to-date.");
return 0;
}
this.indexedCount = 0;
this.totalFilesToIndex = totalFiles;
this.currentIndexingNotice = this.createIndexingNotice();
const errors2 = [];
for (let index = 0; index < files.length; index++) {
if (this.isIndexingCancelled) {
break;
}
while (this.isIndexingPaused) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const file = files[index];
try {
const fileToSave = {
title: file.basename,
path: file.path,
content: fileContents[index],
embeddingModel: EmbeddingManager.getModelName(embeddingInstance),
ctime: file.stat.ctime,
mtime: file.stat.mtime,
tags: fileMetadatas[index]?.tags ?? [],
// Assuming tags are in the metadata
extension: file.extension,
metadata: fileMetadatas[index]?.frontmatter ?? {}
};
await vectorDBManager_default.indexFile(this.oramaDb, embeddingInstance, fileToSave);
this.indexedCount++;
this.updateIndexingNoticeMessage();
} catch (err) {
console.error("Error indexing file:", err);
errors2.push(`Error indexing file: ${file.basename}`);
if (err instanceof Error && err.message.includes("Status code: 429") && !rateLimitNoticeShown) {
const match = err.message.match(/Body: ({.*})/);
let errorMessage = "Embedding API rate limit exceeded. Please try decreasing the requests per second in settings, or wait for the rate limit to reset with your provider.";
if (match && match[1]) {
try {
const errorBody = JSON.parse(match[1]);
if (errorBody.message) {
errorMessage = errorBody.message;
}
} catch (parseError) {
console.error("Error parsing API error message:", parseError);
}
}
new import_obsidian6.Notice(errorMessage, 8e3);
rateLimitNoticeShown = true;
break;
}
}
}
setTimeout(() => {
this.currentIndexingNotice?.hide();
this.currentIndexingNotice = null;
this.indexNoticeMessage = null;
this.isIndexingPaused = false;
this.isIndexingCancelled = false;
this.saveDB();
}, 3e3);
if (errors2.length > 0) {
new import_obsidian6.Notice(`Indexing completed with errors. Check the console for details.`);
console.log("Indexing Errors:", errors2.join("\n"));
}
return files.length;
} catch (error) {
if (error instanceof CustomError) {
console.error("Error indexing vault to vector store:", error.msg);
new import_obsidian6.Notice(
`Error indexing vault: ${error.msg}. Please check your embedding model settings.`
);
} else {
console.error("Unexpected error indexing vault to vector store:", error);
new import_obsidian6.Notice(
"An unexpected error occurred while indexing the vault. Please check the console for details."
);
}
return 0;
}
}
async clearVectorStore() {
try {
this.oramaDb = await this.createNewDb();
await this.saveDB();
new import_obsidian6.Notice("Local vector store cleared successfully.");
console.log("Local vector store cleared successfully, new instance created.");
} catch (err) {
console.error("Error clearing the local vector store:", err);
new import_obsidian6.Notice("An error occurred while clearing the local vector store.");
throw err;
}
}
async garbageCollectVectorStore() {
try {
const files = this.app.vault.getMarkdownFiles();
const filePaths = new Set(files.map((file) => file.path));
const result = await search2(this.oramaDb, {
term: "",
properties: ["path"],
limit: Infinity
});
const docsToRemove = result.hits.filter((hit) => !filePaths.has(hit.document.path)).map((hit) => hit.id);
if (docsToRemove.length === 0) {
console.log("No documents to remove during garbage collection.");
return;
}
if (docsToRemove.length === 1) {
await remove5(this.oramaDb, docsToRemove[0]);
} else {
const removedCount = await removeMultiple(this.oramaDb, docsToRemove, 500);
console.log(`Removed ${removedCount} documents during garbage collection.`);
}
await this.saveDB();
new import_obsidian6.Notice("Local vector store garbage collected successfully.");
console.log("Local vector store garbage collected successfully.");
} catch (err) {
console.error("Error garbage collecting the vector store:", err);
new import_obsidian6.Notice("An error occurred while garbage collecting the vector store.");
}
}
async removeDocs(filePath) {
try {
const searchResult = await search2(this.oramaDb, {
term: filePath,
properties: ["path"],
tolerance: 1
});
if (searchResult.hits.length > 0) {
await removeMultiple(
this.oramaDb,
searchResult.hits.map((hit) => hit.id),
500
);
}
} catch (err) {
console.error("Error deleting document from local Copilotindex:", err);
}
}
async waitForInitialization() {
await this.initializationPromise;
}
// Test query to retrieve record by id from the database
async getDocById(id) {
const result = await search2(this.oramaDb, {
term: id,
properties: ["id"],
limit: 1,
includeVectors: true
});
return result.hits[0]?.document;
}
};
var VectorStoreManager_default = VectorStoreManager;
// 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();
let lastUserMessage = "";
for (const msg of messages) {
if (msg.sender === USER_SENDER) {
lastUserMessage = msg.message;
} else if (msg.sender === AI_SENDER && lastUserMessage) {
await memoryManager.getMemory().saveContext({ input: lastUserMessage }, { output: msg.message });
lastUserMessage = "";
}
}
if (lastUserMessage) {
await memoryManager.getMemory().saveContext({ input: lastUserMessage }, { output: "" });
}
}
// src/components/LanguageModal.tsx
var import_obsidian7 = 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_obsidian7.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/ToneModal.tsx
var import_obsidian8 = require("obsidian");
var TONES = ["Professional", "Casual", "Straightforward", "Confident", "Friendly"];
var ToneModal = class extends import_obsidian8.FuzzySuggestModal {
constructor(app2, onChooseTone) {
super(app2);
this.onChooseTone = onChooseTone;
}
getItems() {
return TONES;
}
getItemText(tone) {
return tone;
}
onChooseItem(tone, evt) {
this.onChooseTone(tone);
}
};
// src/commands.ts
var import_obsidian9 = require("obsidian");
function registerBuiltInCommands(plugin) {
const addCommandIfEnabled = (id, callback) => {
const commandSettings = plugin.settings.enabledCommands[id];
if (commandSettings && commandSettings.enabled) {
plugin.addCommand({
id,
name: commandSettings.name,
editorCallback: callback
});
}
};
addCommandIfEnabled(COMMAND_IDS.FIX_GRAMMAR, (editor) => {
plugin.processSelection(editor, "fixGrammarSpellingSelection");
});
addCommandIfEnabled(COMMAND_IDS.SUMMARIZE, (editor) => {
plugin.processSelection(editor, "summarizeSelection");
});
addCommandIfEnabled(COMMAND_IDS.GENERATE_TOC, (editor) => {
plugin.processSelection(editor, "tocSelection");
});
addCommandIfEnabled(COMMAND_IDS.GENERATE_GLOSSARY, (editor) => {
plugin.processSelection(editor, "glossarySelection");
});
addCommandIfEnabled(COMMAND_IDS.SIMPLIFY, (editor) => {
plugin.processSelection(editor, "simplifySelection");
});
addCommandIfEnabled(COMMAND_IDS.EMOJIFY, (editor) => {
plugin.processSelection(editor, "emojifySelection");
});
addCommandIfEnabled(COMMAND_IDS.REMOVE_URLS, (editor) => {
plugin.processSelection(editor, "removeUrlsFromSelection");
});
addCommandIfEnabled(COMMAND_IDS.REWRITE_TWEET, (editor) => {
plugin.processSelection(editor, "rewriteTweetSelection");
});
addCommandIfEnabled(COMMAND_IDS.REWRITE_TWEET_THREAD, (editor) => {
plugin.processSelection(editor, "rewriteTweetThreadSelection");
});
addCommandIfEnabled(COMMAND_IDS.MAKE_SHORTER, (editor) => {
plugin.processSelection(editor, "rewriteShorterSelection");
});
addCommandIfEnabled(COMMAND_IDS.MAKE_LONGER, (editor) => {
plugin.processSelection(editor, "rewriteLongerSelection");
});
addCommandIfEnabled(COMMAND_IDS.ELI5, (editor) => {
plugin.processSelection(editor, "eli5Selection");
});
addCommandIfEnabled(COMMAND_IDS.PRESS_RELEASE, (editor) => {
plugin.processSelection(editor, "rewritePressReleaseSelection");
});
addCommandIfEnabled(COMMAND_IDS.TRANSLATE, (editor) => {
new LanguageModal(plugin.app, (language) => {
if (!language) {
new import_obsidian9.Notice("Please select a language.");
return;
}
plugin.processSelection(editor, "translateSelection", language);
}).open();
});
addCommandIfEnabled(COMMAND_IDS.CHANGE_TONE, (editor) => {
new ToneModal(plugin.app, (tone) => {
if (!tone) {
new import_obsidian9.Notice("Please select a tone.");
return;
}
plugin.processSelection(editor, "changeToneSelection", tone);
}).open();
});
plugin.addCommand({
id: "count-tokens",
name: "Count words and tokens in selection",
editorCallback: (editor) => {
plugin.processSelection(editor, "countTokensSelection");
}
});
plugin.addCommand({
id: "count-total-vault-tokens",
name: "Count total tokens in your vault",
callback: async () => {
const totalTokens = await plugin.countTotalTokens();
new import_obsidian9.Notice(`Total tokens in your vault: ${totalTokens}`);
}
});
}
// src/components/AddPromptModal.tsx
var import_obsidian10 = require("obsidian");
var AddPromptModal = class extends import_obsidian10.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_obsidian10.Notice("Please fill in both fields: Title and Prompt.");
}
});
}
};
// src/components/AdhocPromptModal.tsx
var import_obsidian11 = require("obsidian");
var AdhocPromptModal = class extends import_obsidian11.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/aiState.ts
var import_react = __toESM(require_react());
function useAIState(chainManager) {
const langChainParams = chainManager.getLangChainParams();
const [currentModelKey, setCurrentModelKey] = (0, import_react.useState)(langChainParams.modelKey);
const [currentChain, setCurrentChain] = (0, import_react.useState)(langChainParams.chainType);
const [, setChatMemory] = (0, import_react.useState)(chainManager.memoryManager.getMemory());
const clearChatMemory = () => {
chainManager.memoryManager.clearChatMemory();
setChatMemory(chainManager.memoryManager.getMemory());
};
const setModelKey = (newModelKey) => {
chainManager.createChainWithNewModel(newModelKey);
setCurrentModelKey(newModelKey);
};
const setChain = (newChain, options) => {
chainManager.setChain(newChain, options);
setCurrentChain(newChain);
};
return [currentModelKey, setModelKey, currentChain, setChain, clearChatMemory];
}
// src/components/CopilotPlusModal.tsx
var import_obsidian12 = require("obsidian");
var CopilotPlusModal = class extends import_obsidian12.Modal {
onOpen() {
const { contentEl } = this;
contentEl.empty();
const container = contentEl.createDiv("copilot-plus-modal");
container.createEl("h2", { text: "Copilot Plus (Alpha)" });
const introP = container.createEl("p");
introP.appendChild(document.createTextNode("Coming soon! "));
introP.createEl("strong", { text: "Powerful AI agents" });
introP.appendChild(
document.createTextNode(
" in your vault for more advanced question answering and workflows while "
)
);
introP.createEl("strong", {
text: "keeping all your data stored locally"
});
introP.appendChild(document.createTextNode("."));
container.createEl("h3", { text: "Stay Updated" });
const paragraph = container.createEl("p");
paragraph.appendChild(
document.createTextNode(
"Join our waitlist at the website below to be notified when Copilot Plus is available! "
)
);
paragraph.appendChild(document.createElement("br"));
paragraph.appendChild(document.createElement("br"));
paragraph.createEl("strong", {
text: "Alpha access spots are limited. "
});
paragraph.appendChild(document.createTextNode("We'll "));
paragraph.createEl("strong", {
text: "prioritize supporters who have donated"
});
paragraph.appendChild(
document.createTextNode(" to the project through either GitHub Sponsors or buymeacoffee. ")
);
paragraph.appendChild(document.createTextNode(" so please consider "));
const donateLink = paragraph.createEl("a", {
href: "https://www.buymeacoffee.com/logancyang",
text: "donating now"
});
donateLink.setAttribute("target", "_blank");
donateLink.setAttribute("rel", "noopener noreferrer");
paragraph.appendChild(document.createTextNode(" if you are interested!"));
container.createEl("h3", {
text: "Learn More about Copilot Plus mode and join the waitlist here:"
});
const link = container.createEl("a", {
href: "https://obsidiancopilot.com",
text: "https://obsidiancopilot.com"
});
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
};
// src/components/ChatComponents/ChatIcons.tsx
var import_obsidian13 = require("obsidian");
var import_react3 = __toESM(require_react());
// src/components/Icons.tsx
var import_react2 = __toESM(require_react());
var UserIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" }),
/* @__PURE__ */ import_react2.default.createElement("circle", { cx: "12", cy: "7", r: "4" })
);
var BotIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("rect", { x: "3", y: "11", width: "18", height: "10", rx: "2" }),
/* @__PURE__ */ import_react2.default.createElement("circle", { cx: "12", cy: "5", r: "2" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M12 7v4" }),
/* @__PURE__ */ import_react2.default.createElement("line", { x1: "8", y1: "16", x2: "8", y2: "16" }),
/* @__PURE__ */ import_react2.default.createElement("line", { x1: "16", y1: "16", x2: "16", y2: "16" })
);
var CopyClipboardIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("rect", { x: "9", y: "9", width: "13", height: "13", rx: "2", ry: "2" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" })
);
var CheckIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("polyline", { points: "20 6 9 17 4 12" })
);
var RefreshIcon = ({ className }) => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
className,
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M3 2v6h6" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M21 12A9 9 0 0 0 6 5.3L3 8" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M21 22v-6h-6" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M3 12a9 9 0 0 0 15 6.7l3-2.7" })
);
var SaveAsNoteIcon = ({ className }) => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
className,
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M12 3v12" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "m8 11 4 4 4-4" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4" })
);
var UseActiveNoteAsContextIcon = ({ className }) => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
className,
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.077.877.528 1.073 1.01a2.5 2.5 0 1 0 3.259-3.259c-.482-.196-.933-.558-1.01-1.073-.05-.336.062-.676.303-.917l1.525-1.525A2.402 2.402 0 0 1 12 1.998c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.237 3.237c-.464.18-.894.527-.967 1.02Z" })
);
var EditIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" })
);
var DeleteIcon = () => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M3 6h18" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" }),
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" })
);
var InsertIcon = ({ className }) => /* @__PURE__ */ import_react2.default.createElement(
"svg",
{
className,
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"
},
/* @__PURE__ */ import_react2.default.createElement("path", { d: "M17 11l-5-5-5 5M17 18l-5-5-5 5" })
);
var RegenerateIcon = RefreshIcon;
// src/components/ChatComponents/ChatIcons.tsx
var ChatIcons = ({
currentModelKey,
setCurrentModelKey,
currentChain,
setCurrentChain,
onNewChat,
onSaveAsNote,
onRefreshVaultContext,
onFindSimilarNotes,
addMessage,
settings,
vault,
vault_qa_strategy,
debug: debug4
}) => {
const [selectedChain, setSelectedChain] = (0, import_react3.useState)(currentChain);
const getModelKey = (model) => `${model.name}|${model.provider}`;
const handleModelChange = async (event) => {
const selectedModelKey = event.target.value;
setCurrentModelKey(selectedModelKey);
};
const handleChainChange = async (event) => {
const newChain = stringToChainType(event.target.value);
setSelectedChain(newChain);
if (newChain === "copilot_plus" /* COPILOT_PLUS */) {
new CopilotPlusModal(app).open();
setSelectedChain(currentChain);
} else {
setCurrentChain(newChain, { debug: debug4 });
}
};
(0, import_react3.useEffect)(() => {
const handleChainSelection = async () => {
if (!app) {
console.error("App instance is not available.");
return;
}
if (selectedChain === "vault_qa" /* VAULT_QA_CHAIN */) {
if (vault_qa_strategy === "ON MODE SWITCH" /* ON_MODE_SWITCH */) {
await onRefreshVaultContext();
}
const activeNoteOnMessage = {
sender: AI_SENDER,
message: `OK Feel free to ask me questions about your vault: **${app.vault.getName()}**.
If you have *NEVER* as your auto-index strategy, you must click the *Refresh Index* button below, or run Copilot command: *Index vault for QA* first before you proceed!
Please note that this is a retrieval-based QA. Specific questions are encouraged. For generic questions like 'give me a summary', 'brainstorm based on the content', Chat mode with direct \`[[note title]]\` mention is a more suitable choice.`,
isVisible: true,
timestamp: formatDateTime(new Date())
};
addMessage(activeNoteOnMessage);
}
try {
await setCurrentChain(selectedChain, { debug: debug4 });
} catch (error) {
if (error instanceof CustomError) {
console.error("Error setting QA chain:", error.msg);
new import_obsidian13.Notice(`Error: ${error.msg}. Please check your embedding model settings.`);
} else {
console.error("Unexpected error setting QA chain:", error);
new import_obsidian13.Notice(
"An unexpected error occurred while setting up the QA chain. Please check the console for details."
);
}
}
};
handleChainSelection();
}, [selectedChain]);
(0, import_react3.useEffect)(() => {
setSelectedChain(settings.defaultChainType);
}, [settings.defaultChainType]);
return /* @__PURE__ */ import_react3.default.createElement("div", { className: "chat-icons-container" }, /* @__PURE__ */ import_react3.default.createElement("div", { className: "chat-icon-selection-tooltip" }, /* @__PURE__ */ import_react3.default.createElement("div", { className: "select-wrapper" }, /* @__PURE__ */ import_react3.default.createElement(
"select",
{
id: "aiModelSelect",
className: "chat-icon-selection model-select",
value: currentModelKey,
onChange: handleModelChange
},
settings.activeModels.filter((model) => model.enabled).map((model) => /* @__PURE__ */ import_react3.default.createElement("option", { key: getModelKey(model), value: getModelKey(model) }, model.name))
), /* @__PURE__ */ import_react3.default.createElement("span", { className: "tooltip-text" }, "Model Selection"))), /* @__PURE__ */ import_react3.default.createElement("button", { className: "chat-icon-button clickable-icon", onClick: () => onNewChat(false) }, /* @__PURE__ */ import_react3.default.createElement(RefreshIcon, { className: "icon-scaler" }), /* @__PURE__ */ import_react3.default.createElement("span", { className: "tooltip-text" }, "New Chat", /* @__PURE__ */ import_react3.default.createElement("br", null), "(unsaved history will be lost)")), /* @__PURE__ */ import_react3.default.createElement("button", { className: "chat-icon-button clickable-icon", onClick: onSaveAsNote }, /* @__PURE__ */ import_react3.default.createElement(SaveAsNoteIcon, { className: "icon-scaler" }), /* @__PURE__ */ import_react3.default.createElement("span", { className: "tooltip-text" }, "Save as Note")), /* @__PURE__ */ import_react3.default.createElement("div", { className: "chat-icon-selection-tooltip" }, /* @__PURE__ */ import_react3.default.createElement("div", { className: "select-wrapper" }, /* @__PURE__ */ import_react3.default.createElement(
"select",
{
id: "aiChainSelect",
className: "chat-icon-selection",
value: currentChain,
onChange: handleChainChange
},
/* @__PURE__ */ import_react3.default.createElement("option", { value: "llm_chain" }, "Chat"),
/* @__PURE__ */ import_react3.default.createElement("option", { value: "vault_qa" }, "Vault QA (Basic)"),
/* @__PURE__ */ import_react3.default.createElement("option", { value: "copilot_plus" }, "Copilot Plus (Alpha)")
), /* @__PURE__ */ import_react3.default.createElement("span", { className: "tooltip-text" }, "Mode Selection"))), selectedChain === "vault_qa" && /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement("button", { className: "chat-icon-button clickable-icon", onClick: onRefreshVaultContext }, /* @__PURE__ */ import_react3.default.createElement(UseActiveNoteAsContextIcon, { className: "icon-scaler" }), /* @__PURE__ */ import_react3.default.createElement("span", { className: "tooltip-text" }, "Refresh Index", /* @__PURE__ */ import_react3.default.createElement("br", null), "for Vault"))));
};
var ChatIcons_default = ChatIcons;
// src/components/ListPromptModal.tsx
var import_obsidian14 = require("obsidian");
var ListPromptModal = class extends import_obsidian14.FuzzySuggestModal {
constructor(app2, promptTitles, onChoosePromptTitle) {
super(app2);
this.promptTitles = promptTitles;
this.onChoosePromptTitle = onChoosePromptTitle;
}
getItems() {
return this.promptTitles;
}
getItemText(promptTitle) {
return promptTitle;
}
onChooseItem(promptTitle, evt) {
this.onChoosePromptTitle(promptTitle);
}
};
// src/components/NoteTitleModal.tsx
var import_obsidian15 = require("obsidian");
var NoteTitleModal = class extends import_obsidian15.FuzzySuggestModal {
constructor(app2, noteTitles, onChooseNoteTitle) {
super(app2);
this.noteTitles = noteTitles;
this.onChooseNoteTitle = onChooseNoteTitle;
}
getItems() {
return this.noteTitles;
}
getItemText(noteTitle) {
return noteTitle;
}
onChooseItem(noteTitle, evt) {
this.onChooseNoteTitle(noteTitle);
}
};
// src/customPromptProcessor.ts
var import_obsidian16 = require("obsidian");
var CustomPromptProcessor = class {
constructor(vault, settings, usageStrategy) {
this.vault = vault;
this.settings = settings;
this.usageStrategy = usageStrategy;
}
static getInstance(vault, settings, usageStrategy) {
if (!CustomPromptProcessor.instance) {
if (!usageStrategy) {
console.warn("PromptUsageStrategy not initialize");
}
CustomPromptProcessor.instance = new CustomPromptProcessor(vault, settings, usageStrategy);
}
return CustomPromptProcessor.instance;
}
async recordPromptUsage(title) {
return this.usageStrategy?.recordUsage(title).save();
}
async getAllPrompts() {
const folder = this.settings.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)).save();
return prompts.sort((a4, b3) => this.usageStrategy?.compare(b3.title, a4.title) || 0);
}
async getPrompt(title) {
const filePath = `${this.settings.customPromptsFolder}/${title}.md`;
const file = this.vault.getAbstractFileByPath(filePath);
if (file instanceof import_obsidian16.TFile) {
const content = await this.vault.read(file);
return { title, content };
}
return null;
}
async savePrompt(title, content) {
const folderPath = (0, import_obsidian16.normalizePath)(this.settings.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.settings.customPromptsFolder}/${originTitle}.md`;
const file = this.vault.getAbstractFileByPath(filePath);
if (file instanceof import_obsidian16.TFile) {
if (originTitle !== newTitle) {
const newFilePath = `${this.settings.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."
);
}
await Promise.all([
this.usageStrategy?.updateUsage(originTitle, newTitle).save(),
this.vault.rename(file, newFilePath)
]);
}
await this.vault.modify(file, content);
}
}
async deletePrompt(title) {
const filePath = `${this.settings.customPromptsFolder}/${title}.md`;
const file = this.vault.getAbstractFileByPath(filePath);
if (file instanceof import_obsidian16.TFile) {
await Promise.all([
this.usageStrategy?.removeUnusedPrompts([title]).save(),
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 match;
while ((match = variableRegex.exec(customPrompt)) !== null) {
const variableName = match[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_obsidian16.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 {
new import_obsidian16.Notice(`Warning: No valid notes found for the provided path '${variableName}'.`);
}
}
return variablesWithContent;
}
async processCustomPrompt(customPrompt, selectedText, activeNote) {
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 i4 = 0; i4 < variablesWithContent.length; i4++) {
if (matches[i4]) {
const varname = matches[i4][1];
if (varname.toLowerCase() === "activenote" && activeNoteContent) {
continue;
}
additionalInfo += `
${varname}:
${variablesWithContent[i4]}`;
}
}
const noteTitles = extractNoteTitles(processedPrompt);
for (const noteTitle of noteTitles) {
if (!matches.some((match) => match[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;
}
};
// node_modules/@tabler/icons-react/dist/esm/createReactComponent.js
var import_react4 = __toESM(require_react());
var import_prop_types = __toESM(require_prop_types());
// node_modules/@tabler/icons-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/@tabler/icons-react/dist/esm/createReactComponent.js
var __defProp4 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp4 = (obj, key, value) => key in obj ? __defProp4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a4, b3) => {
for (var prop in b3 || (b3 = {}))
if (__hasOwnProp2.call(b3, prop))
__defNormalProp4(a4, prop, b3[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b3)) {
if (__propIsEnum.call(b3, prop))
__defNormalProp4(a4, prop, b3[prop]);
}
return a4;
};
var __spreadProps = (a4, b3) => __defProps(a4, __getOwnPropDescs(b3));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp2.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var createReactComponent = (iconName, iconNamePascal, iconNode) => {
const Component2 = (0, import_react4.forwardRef)(
(_a5, ref) => {
var _b = _a5, { color: color2 = "currentColor", size = 24, stroke = 2, children } = _b, rest = __objRest(_b, ["color", "size", "stroke", "children"]);
return (0, import_react4.createElement)(
"svg",
__spreadValues(__spreadProps(__spreadValues({
ref
}, defaultAttributes), {
width: size,
height: size,
stroke: color2,
strokeWidth: stroke,
className: `tabler-icon tabler-icon-${iconName}`
}), rest),
[...iconNode.map(([tag, attrs]) => (0, import_react4.createElement)(tag, attrs)), ...children || []]
);
}
);
Component2.propTypes = {
color: import_prop_types.default.string,
size: import_prop_types.default.oneOfType([import_prop_types.default.string, import_prop_types.default.number]),
stroke: import_prop_types.default.oneOfType([import_prop_types.default.string, import_prop_types.default.number])
};
Component2.displayName = `${iconNamePascal}`;
return Component2;
};
// node_modules/@tabler/icons-react/dist/esm/icons/IconPlayerStopFilled.js
var IconPlayerStopFilled = createReactComponent(
"player-stop-filled",
"IconPlayerStopFilled",
[
[
"path",
{
d: "M17 4h-10a3 3 0 0 0 -3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3 -3v-10a3 3 0 0 0 -3 -3z",
fill: "currentColor",
key: "svg-0",
strokeWidth: "0"
}
]
]
);
// node_modules/@tabler/icons-react/dist/esm/icons/IconSend.js
var IconSend = createReactComponent("send", "IconSend", [
["path", { d: "M10 14l11 -11", key: "svg-0" }],
[
"path",
{
d: "M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1l18 -6.5",
key: "svg-1"
}
]
]);
// src/components/ChatComponents/ChatInput.tsx
var import_react5 = __toESM(require_react());
var ChatInput = ({
inputMessage,
setInputMessage,
handleSendMessage,
isGenerating,
onStopGenerating,
app: app2,
settings,
navigateHistory,
chatIsVisible
}) => {
const [shouldFocus, setShouldFocus] = (0, import_react5.useState)(false);
const [historyIndex, setHistoryIndex] = (0, import_react5.useState)(-1);
const [tempInput, setTempInput] = (0, import_react5.useState)("");
const textAreaRef = (0, import_react5.useRef)(null);
const containerRef = (0, import_react5.useRef)(null);
const handleInputChange = async (event) => {
const inputValue = event.target.value;
setInputMessage(inputValue);
adjustTextareaHeight();
if (inputValue.slice(-2) === "[[") {
showNoteTitleModal();
} else if (inputValue === "/") {
showCustomPromptModal();
}
};
const adjustTextareaHeight = () => {
if (textAreaRef.current) {
textAreaRef.current.style.height = "auto";
textAreaRef.current.style.height = `${textAreaRef.current.scrollHeight}px`;
}
};
(0, import_react5.useEffect)(() => {
adjustTextareaHeight();
}, [inputMessage]);
const showNoteTitleModal = () => {
const fetchNoteTitles = async () => {
const noteTitles = app2.vault.getMarkdownFiles().map((file) => file.basename);
new NoteTitleModal(app2, noteTitles, (noteTitle) => {
setInputMessage(inputMessage.slice(0, -2) + ` [[${noteTitle}]]`);
}).open();
};
fetchNoteTitles();
};
const showCustomPromptModal = async () => {
const customPromptProcessor = CustomPromptProcessor.getInstance(app2.vault, settings);
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) {
await customPromptProcessor.recordPromptUsage(selectedPrompt.title);
setInputMessage(selectedPrompt.content);
}
}).open();
};
(0, import_react5.useEffect)(() => {
setShouldFocus(chatIsVisible);
}, [chatIsVisible]);
(0, import_react5.useEffect)(() => {
if (textAreaRef.current && shouldFocus) {
textAreaRef.current.focus();
}
}, [shouldFocus]);
const handleKeyDown = (e4) => {
if (e4.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 (e4.key === "Enter" && !e4.shiftKey) {
e4.preventDefault();
handleSendMessage();
setHistoryIndex(-1);
setTempInput("");
} else if (e4.key === "ArrowUp") {
if (currentLineIndex > 0 || selectionStart > 0) {
return;
}
e4.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 (e4.key === "ArrowDown") {
if (currentLineIndex < lines.length - 1 || selectionStart < value.length) {
return;
}
e4.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);
}
}
};
return /* @__PURE__ */ import_react5.default.createElement("div", { className: "chat-input-container", ref: containerRef }, /* @__PURE__ */ import_react5.default.createElement(
"textarea",
{
ref: textAreaRef,
className: "chat-input-textarea",
placeholder: "Ask anything. [[ for notes. / for custom prompts.",
value: inputMessage,
onChange: handleInputChange,
onKeyDown: handleKeyDown
}
), /* @__PURE__ */ import_react5.default.createElement(
"button",
{
onClick: isGenerating ? onStopGenerating : handleSendMessage,
"aria-label": isGenerating ? "Stop generating" : "Send message"
},
isGenerating ? /* @__PURE__ */ import_react5.default.createElement(IconPlayerStopFilled, { size: 18 }) : /* @__PURE__ */ import_react5.default.createElement(IconSend, { size: 18 })
));
};
var ChatInput_default = ChatInput;
// src/components/ChatComponents/ChatButtons.tsx
var import_react6 = __toESM(require_react());
var ChatButtons = ({
message,
onCopy,
isCopied,
onInsertAtCursor,
onRegenerate,
onEdit,
onDelete
}) => {
return /* @__PURE__ */ import_react6.default.createElement("div", { className: "chat-message-buttons" }, /* @__PURE__ */ import_react6.default.createElement("button", { onClick: onCopy, className: "clickable-icon", title: "Copy" }, isCopied ? /* @__PURE__ */ import_react6.default.createElement(CheckIcon, null) : /* @__PURE__ */ import_react6.default.createElement(CopyClipboardIcon, null)), message.sender === USER_SENDER ? /* @__PURE__ */ import_react6.default.createElement(import_react6.default.Fragment, null, /* @__PURE__ */ import_react6.default.createElement("button", { onClick: onEdit, className: "clickable-icon", title: "Edit" }, /* @__PURE__ */ import_react6.default.createElement(EditIcon, null)), /* @__PURE__ */ import_react6.default.createElement("button", { onClick: onDelete, className: "clickable-icon", title: "Delete" }, /* @__PURE__ */ import_react6.default.createElement(DeleteIcon, null))) : /* @__PURE__ */ import_react6.default.createElement(import_react6.default.Fragment, null, /* @__PURE__ */ import_react6.default.createElement(
"button",
{
onClick: onInsertAtCursor,
className: "clickable-icon",
title: "Insert to note at cursor"
},
/* @__PURE__ */ import_react6.default.createElement(InsertIcon, null)
), /* @__PURE__ */ import_react6.default.createElement("button", { onClick: onRegenerate, className: "clickable-icon", title: "Regenerate" }, /* @__PURE__ */ import_react6.default.createElement(RegenerateIcon, null)), /* @__PURE__ */ import_react6.default.createElement("button", { onClick: onDelete, className: "clickable-icon", title: "Delete" }, /* @__PURE__ */ import_react6.default.createElement(DeleteIcon, null))));
};
// src/components/ChatComponents/ChatSingleMessage.tsx
var import_obsidian17 = require("obsidian");
var import_react7 = __toESM(require_react());
var ChatSingleMessage = ({
message,
app: app2,
isStreaming,
onInsertAtCursor,
onRegenerate,
onEdit,
onDelete
}) => {
const [isCopied, setIsCopied] = (0, import_react7.useState)(false);
const [isEditing, setIsEditing] = (0, import_react7.useState)(false);
const [editedMessage, setEditedMessage] = (0, import_react7.useState)(message.message);
const contentRef = (0, import_react7.useRef)(null);
const componentRef = (0, import_react7.useRef)(null);
const textareaRef = (0, import_react7.useRef)(null);
const copyToClipboard = () => {
if (!navigator.clipboard || !navigator.clipboard.writeText) {
return;
}
navigator.clipboard.writeText(message.message).then(() => {
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 2e3);
});
};
const preprocessLatex = (content) => {
return content.replace(/\\\[\s*/g, "$$").replace(/\s*\\\]/g, "$$").replace(/\\\(\s*/g, "$").replace(/\s*\\\)/g, "$");
};
(0, import_react7.useEffect)(() => {
if (contentRef.current && message.sender !== USER_SENDER) {
contentRef.current.innerHTML = "";
if (!componentRef.current) {
componentRef.current = new import_obsidian17.Component();
}
const processedMessage = preprocessLatex(message.message);
import_obsidian17.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]);
(0, import_react7.useEffect)(() => {
if (isEditing && textareaRef.current) {
adjustTextareaHeight(textareaRef.current);
}
}, [isEditing]);
const adjustTextareaHeight = (element) => {
element.style.height = "auto";
element.style.height = `${element.scrollHeight}px`;
};
const handleTextareaChange = (e4) => {
setEditedMessage(e4.target.value);
adjustTextareaHeight(e4.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);
}
};
return /* @__PURE__ */ import_react7.default.createElement("div", { className: "chat-message-container" }, /* @__PURE__ */ import_react7.default.createElement("div", { className: `message ${message.sender === USER_SENDER ? "user-message" : "bot-message"}` }, /* @__PURE__ */ import_react7.default.createElement("div", { className: "message-icon" }, message.sender === USER_SENDER ? /* @__PURE__ */ import_react7.default.createElement(UserIcon, null) : /* @__PURE__ */ import_react7.default.createElement(BotIcon, null)), /* @__PURE__ */ import_react7.default.createElement("div", { className: "message-content-wrapper" }, /* @__PURE__ */ import_react7.default.createElement("div", { className: "message-content" }, message.sender === USER_SENDER && isEditing ? /* @__PURE__ */ import_react7.default.createElement(
"textarea",
{
ref: textareaRef,
value: editedMessage,
onChange: handleTextareaChange,
onKeyDown: handleKeyDown,
onBlur: handleSaveEdit,
autoFocus: true,
className: "edit-textarea"
}
) : message.sender === USER_SENDER ? /* @__PURE__ */ import_react7.default.createElement("span", null, message.message) : /* @__PURE__ */ import_react7.default.createElement("div", { ref: contentRef })), !isStreaming && /* @__PURE__ */ import_react7.default.createElement("div", { className: "message-buttons-wrapper" }, /* @__PURE__ */ import_react7.default.createElement("div", { className: "message-timestamp" }, message.timestamp?.display), /* @__PURE__ */ import_react7.default.createElement(
ChatButtons,
{
message,
onCopy: copyToClipboard,
isCopied,
onInsertAtCursor,
onRegenerate,
onEdit: handleEdit,
onDelete
}
)))));
};
var ChatSingleMessage_default = ChatSingleMessage;
// src/components/ChatComponents/ChatMessages.tsx
var import_react8 = __toESM(require_react());
var ChatMessages = ({
chatHistory,
currentAiMessage,
loading,
app: app2,
onInsertAtCursor,
onRegenerate,
onEdit,
onDelete
}) => {
const [loadingDots, setLoadingDots] = (0, import_react8.useState)("");
const scrollToBottom = () => {
const chatMessagesContainer = document.querySelector(".chat-messages");
if (chatMessagesContainer) {
chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
}
};
(0, import_react8.useEffect)(() => {
if (!loading) {
scrollToBottom();
}
}, [loading]);
(0, import_react8.useEffect)(() => {
let intervalId;
if (loading) {
intervalId = setInterval(() => {
setLoadingDots((dots) => dots.length < 6 ? dots + "." : "");
}, 200);
} else {
setLoadingDots("");
}
return () => clearInterval(intervalId);
}, [loading]);
return /* @__PURE__ */ import_react8.default.createElement("div", { className: "chat-messages" }, chatHistory.map(
(message, index) => message.isVisible && /* @__PURE__ */ import_react8.default.createElement(
ChatSingleMessage_default,
{
key: index,
message,
app: app2,
isStreaming: false,
onInsertAtCursor: () => {
onInsertAtCursor(message.message);
},
onRegenerate: () => onRegenerate(index),
onEdit: (newMessage) => onEdit(index, newMessage),
onDelete: () => onDelete(index)
}
)
), (currentAiMessage || loading) && /* @__PURE__ */ import_react8.default.createElement(
ChatSingleMessage_default,
{
key: `ai_message_${currentAiMessage}`,
message: {
sender: "AI",
message: currentAiMessage || loadingDots,
isVisible: true,
timestamp: null
},
app: app2,
isStreaming: true,
onDelete: () => {
}
}
));
};
var ChatMessages_default = ChatMessages;
// src/context.ts
var React7 = __toESM(require_react());
var AppContext = React7.createContext(void 0);
// src/langchainStream.ts
var getAIResponse = async (userMessage, chainManager, addMessage, updateCurrentAiMessage, updateShouldAbort, options = {}) => {
const abortController = new AbortController();
updateShouldAbort(abortController);
try {
await chainManager.runChain(
userMessage.message,
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/sharedState.ts
var import_react9 = __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_react9.useState)(sharedState.getMessages());
(0, import_react9.useEffect)(() => {
setChatHistory(sharedState.getMessages());
}, []);
const addMessage = (message) => {
sharedState.addMessage(message);
setChatHistory([...sharedState.getMessages()]);
};
const clearMessages = () => {
sharedState.clearChatHistory();
setChatHistory([]);
};
return [chatHistory, addMessage, clearMessages];
}
var sharedState_default = SharedState;
// src/components/Chat.tsx
var import_obsidian18 = require("obsidian");
var import_react10 = __toESM(require_react());
var Chat4 = ({
sharedState,
settings,
chainManager,
emitter,
defaultSaveFolder,
onSaveChat,
updateUserMessageHistory,
plugin,
debug: debug4
}) => {
const [chatHistory, addMessage, clearMessages] = useSharedState(sharedState);
const [currentModelKey, setModelKey, currentChain, setChain, clearChatMemory] = useAIState(chainManager);
const [currentAiMessage, setCurrentAiMessage] = (0, import_react10.useState)("");
const [inputMessage, setInputMessage] = (0, import_react10.useState)("");
const [abortController, setAbortController] = (0, import_react10.useState)(null);
const [loading, setLoading] = (0, import_react10.useState)(false);
const [historyIndex, setHistoryIndex] = (0, import_react10.useState)(-1);
const [chatIsVisible, setChatIsVisible] = (0, import_react10.useState)(false);
(0, import_react10.useEffect)(() => {
const handleChatVisibility = (evt) => {
setChatIsVisible(evt.detail.chatIsVisible);
};
emitter.addEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
return () => {
emitter.removeEventListener(EVENT_NAMES.CHAT_IS_VISIBLE, handleChatVisibility);
};
}, []);
const app2 = plugin.app || (0, import_react10.useContext)(AppContext);
const handleSendMessage = async () => {
if (!inputMessage)
return;
const customPromptProcessor2 = CustomPromptProcessor.getInstance(app2.vault, settings);
const processedUserMessage = await customPromptProcessor2.processCustomPrompt(
inputMessage,
"",
app2.workspace.getActiveFile()
);
const timestamp = formatDateTime(new Date());
const userMessage = {
message: inputMessage,
sender: USER_SENDER,
isVisible: true,
timestamp
};
const promptMessageHidden = {
message: processedUserMessage,
sender: USER_SENDER,
isVisible: false,
timestamp
};
addMessage(userMessage);
addMessage(promptMessageHidden);
updateUserMessageHistory(inputMessage);
setHistoryIndex(-1);
setInputMessage("");
setLoading(true);
await getAIResponse(
promptMessageHidden,
chainManager,
addMessage,
setCurrentAiMessage,
setAbortController,
{ debug: debug4 }
);
setLoading(false);
};
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 = 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_obsidian18.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(defaultSaveFolder);
if (!folder) {
await app2.vault.createFolder(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";
const sanitizedFileName = `${firstTenWords.slice(0, 100)}@${timestampFileName}`.replace(
/\s+/g,
"_"
);
const noteFileName = `${defaultSaveFolder}/${sanitizedFileName}.md`;
const noteContentWithTimestamp = `---
epoch: ${firstMessageEpoch}
modelKey: ${currentModelKey}
tags:
- ${settings.defaultConversationTag}
---
${chatContent}`;
const existingFile = app2.vault.getAbstractFileByPath(noteFileName);
if (existingFile instanceof import_obsidian18.TFile) {
await app2.vault.modify(existingFile, noteContentWithTimestamp);
new import_obsidian18.Notice(`Chat updated in existing note: ${noteFileName}`);
} else {
await app2.vault.create(noteFileName, noteContentWithTimestamp);
new import_obsidian18.Notice(`Chat saved as new note: ${noteFileName}`);
}
if (openNote) {
const file = app2.vault.getAbstractFileByPath(noteFileName);
if (file instanceof import_obsidian18.TFile) {
const leaf = app2.workspace.getLeaf();
leaf.openFile(file);
}
}
} catch (error) {
console.error("Error saving chat as note:", error);
new import_obsidian18.Notice("Failed to save chat as note. Check console for details.");
}
};
const refreshVaultContext = async () => {
if (!app2) {
console.error("App instance is not available.");
return;
}
try {
await plugin.vectorStoreManager.indexVaultToVectorStore();
new import_obsidian18.Notice("Vault index refreshed.");
} catch (error) {
console.error("Error refreshing vault index:", error);
new import_obsidian18.Notice("Failed to refresh vault index. Check console for details.");
}
};
const clearCurrentAiMessage = () => {
setCurrentAiMessage("");
};
const handleStopGenerating = (reason) => {
if (abortController) {
if (plugin.settings.debug) {
console.log(`stopping generation..., reason: ${reason}`);
}
abortController.abort(reason);
setLoading(false);
}
};
const handleRegenerate = async (messageIndex) => {
const lastUserMessageIndex = messageIndex - 1;
if (lastUserMessageIndex < 0 || chatHistory[lastUserMessageIndex].sender !== USER_SENDER) {
new import_obsidian18.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 i4 = 0; i4 < newChatHistory.length; i4 += 2) {
const userMsg = newChatHistory[i4];
const aiMsg = newChatHistory[i4 + 1];
if (userMsg && aiMsg) {
await chainManager.memoryManager.getMemory().saveContext({ input: userMsg.message }, { output: aiMsg.message });
}
}
setLoading(true);
try {
const regeneratedResponse = await chainManager.runChain(
lastUserMessage.message,
new AbortController(),
setCurrentAiMessage,
addMessage,
{ debug: debug4 }
);
if (regeneratedResponse && debug4) {
console.log("Message regenerated successfully");
}
} catch (error) {
console.error("Error regenerating message:", error);
new import_obsidian18.Notice("Failed to regenerate message. Please try again.");
} finally {
setLoading(false);
}
};
const handleEdit = async (messageIndex, newMessage) => {
const oldMessage = chatHistory[messageIndex].message;
if (oldMessage === newMessage) {
return;
}
const newChatHistory = [...chatHistory];
newChatHistory[messageIndex].message = newMessage;
clearMessages();
newChatHistory.forEach(addMessage);
await updateChatMemory(newChatHistory, chainManager.memoryManager);
if (newChatHistory[messageIndex].sender === USER_SENDER && messageIndex < newChatHistory.length - 1) {
handleRegenerate(messageIndex + 1);
}
};
(0, import_react10.useEffect)(() => {
async function handleSelection(event) {
const wordCount = event.detail.selectedText.split(" ").length;
const tokenCount = await chainManager.chatModelManager.countTokens(event.detail.selectedText);
const tokenCountMessage = {
sender: AI_SENDER,
message: `The selected text contains ${wordCount} words and ${tokenCount} tokens.`,
isVisible: true,
timestamp: formatDateTime(new Date())
};
addMessage(tokenCountMessage);
}
emitter.addEventListener("countTokensSelection", handleSelection);
return () => {
emitter.removeEventListener("countTokensSelection", handleSelection);
};
}, []);
const createEffect = (eventType, promptFn, options = {}) => {
return () => {
const {
isVisible = false,
ignoreSystemMessage = true
// Ignore system message by default for commands
} = options;
const handleSelection = async (event) => {
const messageWithPrompt = await promptFn(
event.detail.selectedText,
event.detail.eventSubtype
);
const promptMessage = {
message: messageWithPrompt,
sender: USER_SENDER,
isVisible,
timestamp: formatDateTime(new Date())
};
if (isVisible) {
addMessage(promptMessage);
}
setLoading(true);
await getAIResponse(
promptMessage,
chainManager,
addMessage,
setCurrentAiMessage,
setAbortController,
{
debug: debug4,
ignoreSystemMessage
}
);
setLoading(false);
};
emitter.addEventListener(eventType, handleSelection);
return () => {
emitter.removeEventListener(eventType, handleSelection);
};
};
};
(0, import_react10.useEffect)(createEffect("fixGrammarSpellingSelection", fixGrammarSpellingSelectionPrompt), []);
(0, import_react10.useEffect)(createEffect("summarizeSelection", summarizePrompt), []);
(0, import_react10.useEffect)(createEffect("tocSelection", tocPrompt), []);
(0, import_react10.useEffect)(createEffect("glossarySelection", glossaryPrompt), []);
(0, import_react10.useEffect)(createEffect("simplifySelection", simplifyPrompt), []);
(0, import_react10.useEffect)(createEffect("emojifySelection", emojifyPrompt), []);
(0, import_react10.useEffect)(createEffect("removeUrlsFromSelection", removeUrlsFromSelectionPrompt), []);
(0, import_react10.useEffect)(
createEffect("rewriteTweetSelection", rewriteTweetSelectionPrompt, { custom_temperature: 0.2 }),
[]
);
(0, import_react10.useEffect)(
createEffect("rewriteTweetThreadSelection", rewriteTweetThreadSelectionPrompt, {
custom_temperature: 0.2
}),
[]
);
(0, import_react10.useEffect)(createEffect("rewriteShorterSelection", rewriteShorterSelectionPrompt), []);
(0, import_react10.useEffect)(createEffect("rewriteLongerSelection", rewriteLongerSelectionPrompt), []);
(0, import_react10.useEffect)(createEffect("eli5Selection", eli5SelectionPrompt), []);
(0, import_react10.useEffect)(createEffect("rewritePressReleaseSelection", rewritePressReleaseSelectionPrompt), []);
(0, import_react10.useEffect)(
createEffect(
"translateSelection",
(selectedText, language) => createTranslateSelectionPrompt(language)(selectedText)
),
[]
);
(0, import_react10.useEffect)(
createEffect(
"changeToneSelection",
(selectedText, tone) => createChangeToneSelectionPrompt(tone)(selectedText)
),
[]
);
const customPromptProcessor = CustomPromptProcessor.getInstance(app2.vault, settings);
(0, import_react10.useEffect)(
createEffect(
"applyCustomPrompt",
async (selectedText, customPrompt) => {
if (!customPrompt) {
return selectedText;
}
return await customPromptProcessor.processCustomPrompt(
customPrompt,
selectedText,
app2.workspace.getActiveFile()
);
},
{ isVisible: debug4, ignoreSystemMessage: true, custom_temperature: 0.1 }
),
[]
);
(0, import_react10.useEffect)(
createEffect(
"applyAdhocPrompt",
async (selectedText, customPrompt) => {
if (!customPrompt) {
return selectedText;
}
return await customPromptProcessor.processCustomPrompt(
customPrompt,
selectedText,
app2.workspace.getActiveFile()
);
},
{ isVisible: debug4, ignoreSystemMessage: true, custom_temperature: 0.1 }
),
[]
);
const handleInsertAtCursor = async (message) => {
let leaf = app2.workspace.getMostRecentLeaf();
if (!leaf) {
new import_obsidian18.Notice("No active leaf found.");
return;
}
if (!(leaf.view instanceof import_obsidian18.MarkdownView)) {
leaf = app2.workspace.getLeaf(false);
await leaf.setViewState({ type: "markdown", state: leaf.view.getState() });
}
if (!(leaf.view instanceof import_obsidian18.MarkdownView)) {
new import_obsidian18.Notice("Failed to open a markdown view.");
return;
}
const editor = leaf.view.editor;
const cursor = editor.getCursor();
editor.replaceRange(message, cursor);
new import_obsidian18.Notice("Message inserted into the active note.");
};
(0, import_react10.useEffect)(() => {
if (onSaveChat) {
onSaveChat(handleSaveAsNote);
}
}, [onSaveChat]);
const handleDelete = async (messageIndex) => {
const newChatHistory = [...chatHistory];
newChatHistory.splice(messageIndex, 1);
clearMessages();
newChatHistory.forEach(addMessage);
await updateChatMemory(newChatHistory, chainManager.memoryManager);
};
return /* @__PURE__ */ import_react10.default.createElement("div", { className: "chat-container" }, /* @__PURE__ */ import_react10.default.createElement(
ChatMessages_default,
{
chatHistory,
currentAiMessage,
loading,
app: app2,
onInsertAtCursor: handleInsertAtCursor,
onRegenerate: handleRegenerate,
onEdit: handleEdit,
onDelete: handleDelete
}
), /* @__PURE__ */ import_react10.default.createElement("div", { className: "bottom-container" }, /* @__PURE__ */ import_react10.default.createElement(
ChatIcons_default,
{
currentModelKey,
setCurrentModelKey: setModelKey,
currentChain,
setCurrentChain: setChain,
onNewChat: async (openNote) => {
handleStopGenerating("new-chat" /* NEW_CHAT */);
if (settings.autosaveChat && chatHistory.length > 0) {
await handleSaveAsNote(openNote);
}
clearMessages();
clearChatMemory();
clearCurrentAiMessage();
},
onSaveAsNote: () => handleSaveAsNote(true),
onRefreshVaultContext: refreshVaultContext,
onFindSimilarNotes: (content, activeFilePath) => plugin.findSimilarNotes(content, activeFilePath),
addMessage,
settings,
vault: app2.vault,
vault_qa_strategy: plugin.settings.indexVaultToVectorStore,
debug: debug4
}
), /* @__PURE__ */ import_react10.default.createElement(
ChatInput_default,
{
inputMessage,
setInputMessage,
handleSendMessage,
isGenerating: loading,
onStopGenerating: () => handleStopGenerating("user-stopped" /* USER_STOPPED */),
app: app2,
settings,
navigateHistory,
chatIsVisible
}
)));
};
var Chat_default = Chat4;
// src/components/CopilotView.tsx
var import_obsidian19 = require("obsidian");
var React9 = __toESM(require_react());
var import_client3 = __toESM(require_client15());
var CopilotView = class extends import_obsidian19.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.plugin = plugin;
this.root = null;
this.handleSaveAsNote = null;
this.debug = false;
this.userSystemPrompt = "";
this.sharedState = plugin.sharedState;
this.settings = plugin.settings;
this.app = plugin.app;
this.chainManager = plugin.chainManager;
this.debug = plugin.settings.debug;
this.emitter = new EventTarget();
this.userSystemPrompt = plugin.settings.userSystemPrompt;
this.plugin = plugin;
this.defaultSaveFolder = plugin.settings.defaultSaveFolder;
}
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_client3.createRoot)(this.containerEl.children[1]);
root2.render(
/* @__PURE__ */ React9.createElement(AppContext.Provider, { value: this.app }, /* @__PURE__ */ React9.createElement(React9.StrictMode, null, /* @__PURE__ */ React9.createElement(
Chat_default,
{
sharedState: this.sharedState,
settings: this.settings,
chainManager: this.chainManager,
emitter: this.emitter,
defaultSaveFolder: this.defaultSaveFolder,
updateUserMessageHistory: (newMessage) => {
this.plugin.updateUserMessageHistory(newMessage);
},
plugin: this.plugin,
debug: this.debug,
onSaveChat: (saveFunction) => {
this.handleSaveAsNote = saveFunction;
}
}
)))
);
}
async saveChat() {
if (this.handleSaveAsNote) {
await this.handleSaveAsNote();
}
}
async onClose() {
if (this.root) {
this.root.unmount();
}
}
updateView() {
this.onOpen();
}
};
// src/components/LoadChatHistoryModal.tsx
var import_obsidian20 = require("obsidian");
var LoadChatHistoryModal = class extends import_obsidian20.FuzzySuggestModal {
constructor(app2, chatFiles, onChooseFile) {
super(app2);
this.chatFiles = chatFiles;
this.onChooseFile = onChooseFile;
}
getItems() {
return this.chatFiles.sort((a4, b3) => {
const getEpoch = (file) => {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
return frontmatter && frontmatter.epoch ? frontmatter.epoch : file.stat.ctime;
};
const epochA = getEpoch(a4);
const epochB = getEpoch(b3);
return epochB - epochA;
});
}
getItemText(file) {
const [title] = file.basename.split("@");
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.replace(/_/g, " ").trim()} - ${formattedDateTime.display}`;
}
onChooseItem(file, evt) {
this.onChooseFile(file);
}
};
// src/components/SimilarNotesModal.tsx
var import_obsidian21 = require("obsidian");
var SimilarNotesModal = class extends import_obsidian21.Modal {
constructor(app2, similarChunks) {
super(app2);
this.similarChunks = similarChunks;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Similar Note Blocks to Current Note" });
const containerEl = contentEl.createEl("div", { cls: "similar-notes-container" });
this.similarChunks.forEach((item) => {
const itemEl = containerEl.createEl("div", { cls: "similar-note-item" });
const collapseEl = itemEl.createEl("details");
const summaryEl = collapseEl.createEl("summary");
const titleEl = summaryEl.createEl("a", {
text: `${item.chunk.metadata.title} (Score: ${item.score.toFixed(2)})`,
cls: "similar-note-title"
});
titleEl.addEventListener("click", (event) => {
event.preventDefault();
this.navigateToNote(item.chunk.metadata.path);
});
const contentEl2 = collapseEl.createEl("p");
contentEl2.setText(this.cleanChunkContent(item.chunk.pageContent));
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
navigateToNote(path) {
const file = this.app.vault.getAbstractFileByPath(path);
if (file instanceof import_obsidian21.TFile) {
const leaf = this.app.workspace.getLeaf(false);
if (leaf) {
leaf.openFile(file).then(() => {
this.close();
});
}
}
}
cleanChunkContent(content) {
return content.replace(/^\[\[.*?\]\]\s*---\s*/, "");
}
};
// src/encryptionService.ts
var import_obsidian22 = require("obsidian");
var safeStorage = null;
if (import_obsidian22.Platform.isDesktop) {
safeStorage = require("electron")?.remote?.safeStorage;
}
var _EncryptionService = class {
constructor(settings) {
this.settings = settings;
}
isPlainText(key) {
return !key.startsWith(_EncryptionService.ENCRYPTION_PREFIX) && !key.startsWith(_EncryptionService.DECRYPTION_PREFIX);
}
isDecrypted(keyBuffer) {
return keyBuffer.startsWith(_EncryptionService.DECRYPTION_PREFIX);
}
encryptAllKeys() {
const keysToEncrypt = Object.keys(this.settings).filter(
(key) => key.toLowerCase().includes("apikey".toLowerCase())
);
for (const key of keysToEncrypt) {
const apiKey = this.settings[key];
this.settings[key] = this.getEncryptedKey(apiKey);
}
if (Array.isArray(this.settings.activeModels)) {
this.settings.activeModels = this.settings.activeModels.map((model) => ({
...model,
apiKey: this.getEncryptedKey(model.apiKey || "")
}));
}
}
getEncryptedKey(apiKey) {
if (!apiKey || !this.settings.enableEncryption || apiKey.startsWith(_EncryptionService.ENCRYPTION_PREFIX)) {
return apiKey;
}
if (this.isDecrypted(apiKey)) {
apiKey = apiKey.replace(_EncryptionService.DECRYPTION_PREFIX, "");
}
if (safeStorage && safeStorage.isEncryptionAvailable()) {
const encryptedBuffer = safeStorage.encryptString(apiKey);
return _EncryptionService.ENCRYPTION_PREFIX + encryptedBuffer.toString("base64");
} else {
const encoder = new TextEncoder();
const data = encoder.encode(apiKey);
return _EncryptionService.ENCRYPTION_PREFIX + this.arrayBufferToBase64(data);
}
}
getDecryptedKey(apiKey) {
if (!apiKey || this.isPlainText(apiKey)) {
return apiKey;
}
if (this.isDecrypted(apiKey)) {
return apiKey.replace(_EncryptionService.DECRYPTION_PREFIX, "");
}
const base64Data = apiKey.replace(_EncryptionService.ENCRYPTION_PREFIX, "");
try {
if (safeStorage && safeStorage.isEncryptionAvailable()) {
const buffer = Buffer.from(base64Data, "base64");
return safeStorage.decryptString(buffer);
} else {
const data = this.base64ToArrayBuffer(base64Data);
const decoder = new TextDecoder();
return decoder.decode(data);
}
} catch (err) {
console.error("Decryption failed:", err);
return "Copilot failed to decrypt API keys!";
}
}
arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i4 = 0; i4 < bytes.byteLength; i4++) {
binary += String.fromCharCode(bytes[i4]);
}
return window.btoa(binary);
}
base64ToArrayBuffer(base642) {
const binaryString = window.atob(base642);
const bytes = new Uint8Array(binaryString.length);
for (let i4 = 0; i4 < binaryString.length; i4++) {
bytes[i4] = binaryString.charCodeAt(i4);
}
return bytes.buffer;
}
};
var EncryptionService = _EncryptionService;
EncryptionService.ENCRYPTION_PREFIX = "enc_";
EncryptionService.DECRYPTION_PREFIX = "dec_";
// src/promptUsageStrategy.ts
var TimestampUsageStrategy = class {
constructor(settings, saveSettings) {
this.settings = settings;
this.saveSettings = saveSettings;
this.usageData = {};
this.usageData = { ...settings.promptUsageTimestamps };
}
recordUsage(promptTitle) {
this.usageData[promptTitle] = Date.now();
return this;
}
updateUsage(oldTitle, newTitle) {
this.usageData[newTitle] = this.usageData[oldTitle];
delete this.usageData[oldTitle];
return this;
}
removeUnusedPrompts(existingPromptTitles) {
for (const key in this.usageData) {
if (!existingPromptTitles.contains(key)) {
delete this.usageData[key];
}
}
return this;
}
compare(aKey, bKey) {
return (this.usageData[aKey] || 0) - (this.usageData[bKey] || 0);
}
async save() {
this.settings.promptUsageTimestamps = { ...this.usageData };
await this.saveSettings();
}
};
// src/settings/SettingsPage.tsx
var import_obsidian24 = require("obsidian");
var import_react21 = __toESM(require_react());
var import_client4 = __toESM(require_client15());
// src/settings/components/SettingsMain.tsx
var import_react20 = __toESM(require_react());
// src/settings/contexts/SettingsContext.tsx
var import_react11 = __toESM(require_react());
var SettingsContext = (0, import_react11.createContext)(void 0);
var SettingsProvider = ({ plugin, reloadPlugin, children }) => {
const [settings, setSettings] = (0, import_react11.useState)(plugin.settings);
const updateSettings = (0, import_react11.useCallback)(
async (newSettings) => {
const updatedSettings = { ...settings, ...newSettings };
setSettings(updatedSettings);
plugin.settings = updatedSettings;
await plugin.saveSettings();
if (newSettings.activeModels) {
plugin.chainManager.chatModelManager.buildModelMap(updatedSettings.activeModels);
}
},
[plugin, settings]
);
const saveSettings = (0, import_react11.useCallback)(async () => {
await plugin.saveSettings();
await reloadPlugin();
}, [plugin, reloadPlugin]);
const resetSettings = (0, import_react11.useCallback)(async () => {
const defaultSettingsWithBuiltIns = {
...DEFAULT_SETTINGS,
activeModels: BUILTIN_CHAT_MODELS.map((model) => ({ ...model, enabled: true })),
activeEmbeddingModels: BUILTIN_EMBEDDING_MODELS.map((model) => ({ ...model, enabled: true }))
};
plugin.settings = defaultSettingsWithBuiltIns;
setSettings(defaultSettingsWithBuiltIns);
await plugin.saveSettings();
await reloadPlugin();
}, [plugin, reloadPlugin]);
return /* @__PURE__ */ import_react11.default.createElement(
SettingsContext.Provider,
{
value: { settings, updateSettings, saveSettings, resetSettings, reloadPlugin }
},
children
);
};
var useSettingsContext = () => {
const context = (0, import_react11.useContext)(SettingsContext);
if (context === void 0) {
throw new Error("useSettingsContext must be used within a SettingsProvider");
}
return context;
};
// src/settings/components/AdvancedSettings.tsx
var import_react13 = __toESM(require_react());
// src/settings/components/SettingBlocks.tsx
var import_obsidian23 = require("obsidian");
var import_react12 = __toESM(require_react());
var DropdownComponent = ({
name: name2,
description,
options,
value,
onChange
}) => {
return /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item" }, /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-name" }, name2), /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-description" }, description), /* @__PURE__ */ import_react12.default.createElement(
"select",
{
value,
onChange: (e4) => onChange(e4.target.value),
className: "copilot-setting-item-control"
},
options.map((option, index) => /* @__PURE__ */ import_react12.default.createElement("option", { key: index, value: option }, option))
));
};
var TextComponent = ({
name: name2,
description,
placeholder,
value,
type,
onChange
}) => {
return /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item" }, /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-name" }, name2), /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-description" }, description), /* @__PURE__ */ import_react12.default.createElement(
"input",
{
type: type || "text",
className: "copilot-setting-item-control",
placeholder,
value,
onChange: (e4) => onChange(e4.target.value)
}
));
};
var TextAreaComponent = ({
name: name2,
description,
placeholder,
value,
onChange,
rows = 3
}) => {
return /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item" }, /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-name" }, name2), /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-description" }, description), /* @__PURE__ */ import_react12.default.createElement(
"textarea",
{
className: "copilot-setting-item-control",
placeholder,
value,
onChange: (e4) => onChange(e4.target.value),
rows
}
));
};
var SliderComponent = ({
name: name2,
description,
min,
max,
step,
value,
onChange
}) => {
return /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item" }, /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-name" }, name2), /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-description" }, description), /* @__PURE__ */ import_react12.default.createElement("div", { style: { display: "flex", alignItems: "center" } }, /* @__PURE__ */ import_react12.default.createElement(
"input",
{
type: "range",
className: "copilot-setting-item-control",
min,
max,
step,
value,
onChange: (e4) => onChange(parseFloat(e4.target.value))
}
), /* @__PURE__ */ import_react12.default.createElement(
"span",
{
style: { marginLeft: "20px", fontWeight: "bold", color: "var(--inline-title-color)" }
},
value
)));
};
var ToggleComponent = ({
name: name2,
description,
value,
onChange,
disabled = false
}) => {
return /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item" }, /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-name" }, name2), /* @__PURE__ */ import_react12.default.createElement("div", { className: "copilot-setting-item-description" }, description), /* @__PURE__ */ import_react12.default.createElement("label", { className: `switch ${disabled ? "disabled" : ""}` }, /* @__PURE__ */ import_react12.default.createElement(
"input",
{
type: "checkbox",
checked: value,
onChange: (e4) => onChange(e4.target.checked),
disabled
}
), /* @__PURE__ */ import_react12.default.createElement("span", { className: "slider round" })));
};
var ModelSettingsComponent = ({
activeModels,
onUpdateModels,
providers,
onDeleteModel,
defaultModelKey,
onSetDefaultModelKey,
isEmbeddingModel
}) => {
const emptyModel = {
name: "",
provider: providers.length > 0 ? providers[0] : "",
baseUrl: "",
apiKey: "",
enabled: true,
isBuiltIn: false,
enableCors: false,
isEmbeddingModel
};
const [newModel, setNewModel] = (0, import_react12.useState)(emptyModel);
const [isAddModelOpen, setIsAddModelOpen] = (0, import_react12.useState)(false);
const getModelKey = (model) => `${model.name}|${model.provider}`;
const handleAddModel = () => {
if (newModel.name && newModel.provider) {
const updatedModels = [...activeModels, { ...newModel, enabled: true }];
onUpdateModels(updatedModels);
setNewModel(emptyModel);
} else {
new import_obsidian23.Notice("Please fill in necessary fields!");
}
};
const handleSetDefaultModel = (model) => {
onSetDefaultModelKey(getModelKey(model));
};
return /* @__PURE__ */ import_react12.default.createElement("div", null, /* @__PURE__ */ import_react12.default.createElement("table", { className: "model-settings-table" }, /* @__PURE__ */ import_react12.default.createElement("thead", null, /* @__PURE__ */ import_react12.default.createElement("tr", null, /* @__PURE__ */ import_react12.default.createElement("th", null, "Default"), /* @__PURE__ */ import_react12.default.createElement("th", null, "Model"), /* @__PURE__ */ import_react12.default.createElement("th", null, "Provider"), /* @__PURE__ */ import_react12.default.createElement("th", null, "Enabled"), /* @__PURE__ */ import_react12.default.createElement("th", null, "CORS"), /* @__PURE__ */ import_react12.default.createElement("th", null, "Delete"))), /* @__PURE__ */ import_react12.default.createElement("tbody", null, activeModels.map((model, index) => /* @__PURE__ */ import_react12.default.createElement("tr", { key: getModelKey(model) }, /* @__PURE__ */ import_react12.default.createElement("td", null, /* @__PURE__ */ import_react12.default.createElement(
"input",
{
type: "radio",
name: `selected-${isEmbeddingModel ? "embedding" : "chat"}-model`,
checked: getModelKey(model) === defaultModelKey,
onChange: () => handleSetDefaultModel(model)
}
)), /* @__PURE__ */ import_react12.default.createElement("td", null, model.name), /* @__PURE__ */ import_react12.default.createElement("td", null, model.provider), /* @__PURE__ */ import_react12.default.createElement("td", null, /* @__PURE__ */ import_react12.default.createElement(
ToggleComponent,
{
name: "",
value: model.enabled,
onChange: (value) => {
if (!model.isBuiltIn) {
const updatedModels = [...activeModels];
updatedModels[index].enabled = value;
onUpdateModels(updatedModels);
}
},
disabled: model.isBuiltIn
}
)), /* @__PURE__ */ import_react12.default.createElement("td", null, !model.isBuiltIn && /* @__PURE__ */ import_react12.default.createElement(
ToggleComponent,
{
name: "",
value: model.enableCors || false,
onChange: (value) => {
const updatedModels = [...activeModels];
updatedModels[index].enableCors = value;
onUpdateModels(updatedModels);
}
}
)), /* @__PURE__ */ import_react12.default.createElement("td", null, !model.core && /* @__PURE__ */ import_react12.default.createElement("button", { onClick: () => onDeleteModel(getModelKey(model)) }, "Delete")))))), /* @__PURE__ */ import_react12.default.createElement("div", { className: "add-custom-model" }, /* @__PURE__ */ import_react12.default.createElement("h2", { onClick: () => setIsAddModelOpen(!isAddModelOpen), style: { cursor: "pointer" } }, "Add Custom Model ", isAddModelOpen ? "\u25BC" : "\u25B6"), isAddModelOpen && /* @__PURE__ */ import_react12.default.createElement("div", { className: "add-custom-model-form" }, /* @__PURE__ */ import_react12.default.createElement(
TextComponent,
{
name: "Model Name",
description: `The name of the model, i.e. ${isEmbeddingModel ? "text-embedding-3-small" : "gpt-4o-mini"}`,
value: newModel.name,
placeholder: "Enter model name",
onChange: (value) => {
setNewModel({ ...newModel, name: value });
}
}
), /* @__PURE__ */ import_react12.default.createElement(
DropdownComponent,
{
name: "Provider",
options: providers,
value: newModel.provider,
onChange: (value) => {
setNewModel({ ...newModel, provider: value });
}
}
), /* @__PURE__ */ import_react12.default.createElement(
TextComponent,
{
name: "Base URL (optional)",
description: "For 3rd party OpenAI Format endpoints only. Leave blank for other providers.",
value: newModel.baseUrl || "",
placeholder: "https://api.example.com/v1",
onChange: (value) => setNewModel({ ...newModel, baseUrl: value })
}
), /* @__PURE__ */ import_react12.default.createElement(
TextComponent,
{
name: "API Key (optional)",
description: "API key for the 3rd party provider",
value: newModel.apiKey || "",
placeholder: "Enter API key",
type: "password",
onChange: (value) => setNewModel({ ...newModel, apiKey: value })
}
), /* @__PURE__ */ import_react12.default.createElement("button", { onClick: handleAddModel, className: "add-model-button" }, "Add Model"))));
};
// src/settings/components/AdvancedSettings.tsx
var AdvancedSettings = ({
userSystemPrompt,
setUserSystemPrompt
}) => {
return /* @__PURE__ */ import_react13.default.createElement("div", null, /* @__PURE__ */ import_react13.default.createElement("br", null), /* @__PURE__ */ import_react13.default.createElement("br", null), /* @__PURE__ */ import_react13.default.createElement("h1", null, "Advanced Settings"), /* @__PURE__ */ import_react13.default.createElement(
TextAreaComponent,
{
name: "User System Prompt",
description: "Warning: It will override the default system prompt for all messages!",
value: userSystemPrompt,
onChange: setUserSystemPrompt,
placeholder: userSystemPrompt || "Default: " + DEFAULT_SYSTEM_PROMPT,
rows: 10
}
));
};
var AdvancedSettings_default = AdvancedSettings;
// src/settings/components/ApiSettings.tsx
var import_react16 = __toESM(require_react());
// src/settings/components/ApiSetting.tsx
var import_react14 = __toESM(require_react());
var ApiSetting = ({ title, description, value, setValue, placeholder, type }) => {
return /* @__PURE__ */ import_react14.default.createElement("div", null, /* @__PURE__ */ import_react14.default.createElement(
TextComponent,
{
name: title,
description,
value,
onChange: setValue,
placeholder: placeholder || "",
type: type || "password"
}
));
};
var ApiSetting_default = ApiSetting;
// src/settings/components/Collapsible.tsx
var import_react15 = __toESM(require_react());
var Collapsible = ({ title, children }) => {
const [isOpen, setIsOpen] = (0, import_react15.useState)(false);
const titleStyle = {
fontWeight: "bold",
cursor: "pointer",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
marginBottom: "10px",
borderRadius: "5px"
};
const contentStyle = {
padding: "10px 10px",
borderRadius: "8px",
marginTop: "10px"
};
const ChevronDown = () => /* @__PURE__ */ import_react15.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react15.default.createElement("polyline", { points: "6 9 12 15 18 9" })
);
const ChevronRight = () => /* @__PURE__ */ import_react15.default.createElement(
"svg",
{
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"
},
/* @__PURE__ */ import_react15.default.createElement("polyline", { points: "9 18 15 12 9 6" })
);
return /* @__PURE__ */ import_react15.default.createElement("div", { style: { padding: "20px" } }, /* @__PURE__ */ import_react15.default.createElement("div", { style: titleStyle, onClick: () => setIsOpen(!isOpen) }, title, isOpen ? /* @__PURE__ */ import_react15.default.createElement(ChevronDown, null) : /* @__PURE__ */ import_react15.default.createElement(ChevronRight, null)), isOpen && /* @__PURE__ */ import_react15.default.createElement("div", { style: contentStyle }, children));
};
var Collapsible_default = Collapsible;
// src/settings/components/ApiSettings.tsx
var ApiSettings = ({
openAIApiKey,
setOpenAIApiKey,
openAIOrgId,
setOpenAIOrgId,
googleApiKey,
setGoogleApiKey,
anthropicApiKey,
setAnthropicApiKey,
openRouterAiApiKey,
setOpenRouterAiApiKey,
azureOpenAIApiKey,
setAzureOpenAIApiKey,
azureOpenAIApiInstanceName,
setAzureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName,
setAzureOpenAIApiDeploymentName,
azureOpenAIApiVersion,
setAzureOpenAIApiVersion,
azureOpenAIApiEmbeddingDeploymentName,
setAzureOpenAIApiEmbeddingDeploymentName,
groqApiKey,
setGroqApiKey,
cohereApiKey,
setCohereApiKey
}) => {
return /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement("br", null), /* @__PURE__ */ import_react16.default.createElement("br", null), /* @__PURE__ */ import_react16.default.createElement("h1", null, "API Settings"), /* @__PURE__ */ import_react16.default.createElement("p", null, "All your API keys are stored locally."), /* @__PURE__ */ import_react16.default.createElement("div", { className: "warning-message" }, "Make sure you have access to the model and the correct API key.", /* @__PURE__ */ import_react16.default.createElement("br", null), "If errors occur, please re-enter the API key, save and reload the plugin to see if it resolves the issue."), /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "OpenAI API Key",
value: openAIApiKey,
setValue: setOpenAIApiKey,
placeholder: "Enter OpenAI API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "You can find your API key at", " ", /* @__PURE__ */ import_react16.default.createElement(
"a",
{
href: "https://platform.openai.com/api-keys",
target: "_blank",
rel: "noopener noreferrer"
},
"https://platform.openai.com/api-keys"
)), /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "OpenAI Organization ID (optional)",
value: openAIOrgId,
setValue: setOpenAIOrgId,
placeholder: "Enter OpenAI Organization ID if applicable"
}
)), /* @__PURE__ */ import_react16.default.createElement("div", { className: "warning-message" }, /* @__PURE__ */ import_react16.default.createElement("span", null, "If you are a new user, try "), /* @__PURE__ */ import_react16.default.createElement(
"a",
{
href: "https://platform.openai.com/playground?mode=chat",
target: "_blank",
rel: "noopener noreferrer"
},
"OpenAI playground"
), /* @__PURE__ */ import_react16.default.createElement("span", null, " to see if you have correct API access first."))), /* @__PURE__ */ import_react16.default.createElement("br", null), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "Google API Settings" }, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Google API Key",
value: googleApiKey,
setValue: setGoogleApiKey,
placeholder: "Enter Google API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "If you have Google Cloud, you can get Gemini API key", " ", /* @__PURE__ */ import_react16.default.createElement(
"a",
{
href: "https://makersuite.google.com/app/apikey",
target: "_blank",
rel: "noopener noreferrer"
},
"here"
), ".", /* @__PURE__ */ import_react16.default.createElement("br", null), "Your API key is stored locally and is only used to make requests to Google's services."))), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "Anthropic API Settings" }, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Anthropic API Key",
value: anthropicApiKey,
setValue: setAnthropicApiKey,
placeholder: "Enter Anthropic API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "If you have Anthropic API access, you can get the API key", " ", /* @__PURE__ */ import_react16.default.createElement(
"a",
{
href: "https://console.anthropic.com/settings/keys",
target: "_blank",
rel: "noopener noreferrer"
},
"here"
), ".", /* @__PURE__ */ import_react16.default.createElement("br", null), "Your API key is stored locally and is only used to make requests to Anthropic's services."))), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "OpenRouter.ai API Settings" }, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "OpenRouter AI API Key",
value: openRouterAiApiKey,
setValue: setOpenRouterAiApiKey,
placeholder: "Enter OpenRouter AI API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "You can get your OpenRouterAI key", " ", /* @__PURE__ */ import_react16.default.createElement("a", { href: "https://openrouter.ai/keys", target: "_blank", rel: "noopener noreferrer" }, "here"), ".", /* @__PURE__ */ import_react16.default.createElement("br", null), "Find models", " ", /* @__PURE__ */ import_react16.default.createElement("a", { href: "https://openrouter.ai/models", target: "_blank", rel: "noopener noreferrer" }, "here"), "."))), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "Azure OpenAI API Settings" }, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Azure OpenAI API Key",
value: azureOpenAIApiKey,
setValue: setAzureOpenAIApiKey,
placeholder: "Enter Azure OpenAI API Key"
}
), /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Azure OpenAI API Instance Name",
value: azureOpenAIApiInstanceName,
setValue: setAzureOpenAIApiInstanceName,
placeholder: "Enter Azure OpenAI API Instance Name",
type: "text"
}
), /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Azure OpenAI API Deployment Name",
description: "This is your actual model, no need to pass a model name separately.",
value: azureOpenAIApiDeploymentName,
setValue: setAzureOpenAIApiDeploymentName,
placeholder: "Enter Azure OpenAI API Deployment Name",
type: "text"
}
), /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Azure OpenAI API Version",
value: azureOpenAIApiVersion,
setValue: setAzureOpenAIApiVersion,
placeholder: "Enter Azure OpenAI API Version",
type: "text"
}
), /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Azure OpenAI API Embedding Deployment Name",
description: "(Optional) For embedding provider Azure OpenAI",
value: azureOpenAIApiEmbeddingDeploymentName,
setValue: setAzureOpenAIApiEmbeddingDeploymentName,
placeholder: "Enter Azure OpenAI API Embedding Deployment Name",
type: "text"
}
))), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "Groq API Settings" }, /* @__PURE__ */ import_react16.default.createElement("div", null, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Groq API Key",
value: groqApiKey,
setValue: setGroqApiKey,
placeholder: "Enter Groq API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "If you have Groq API access, you can get the API key", " ", /* @__PURE__ */ import_react16.default.createElement("a", { href: "https://console.groq.com/keys", target: "_blank", rel: "noopener noreferrer" }, "here"), ".", /* @__PURE__ */ import_react16.default.createElement("br", null), "Your API key is stored locally and is only used to make requests to Groq's services."))), /* @__PURE__ */ import_react16.default.createElement(Collapsible_default, { title: "Cohere API Settings" }, /* @__PURE__ */ import_react16.default.createElement(
ApiSetting_default,
{
title: "Cohere API Key",
value: cohereApiKey,
setValue: setCohereApiKey,
placeholder: "Enter Cohere API Key"
}
), /* @__PURE__ */ import_react16.default.createElement("p", null, "Get your free Cohere API key", " ", /* @__PURE__ */ import_react16.default.createElement("a", { href: "https://dashboard.cohere.ai/api-keys", target: "_blank", rel: "noreferrer" }, "here"))));
};
var ApiSettings_default = ApiSettings;
// src/settings/components/GeneralSettings.tsx
var import_react18 = __toESM(require_react());
// src/settings/components/CommandToggleSettings.tsx
var import_react17 = __toESM(require_react());
var CommandToggleSettings = ({
enabledCommands,
setEnabledCommands
}) => {
const [isExpanded, setIsExpanded] = (0, import_react17.useState)(false);
const toggleCommand = (commandId, enabled) => {
setEnabledCommands({
...enabledCommands,
[commandId]: { ...enabledCommands[commandId], enabled }
});
};
return /* @__PURE__ */ import_react17.default.createElement("div", null, /* @__PURE__ */ import_react17.default.createElement("h2", { onClick: () => setIsExpanded(!isExpanded), style: { cursor: "pointer" } }, "Command Settings ", isExpanded ? "\u25BC" : "\u25B6"), isExpanded && /* @__PURE__ */ import_react17.default.createElement("div", null, Object.entries(enabledCommands).map(([commandId, { enabled, name: name2 }]) => /* @__PURE__ */ import_react17.default.createElement(
ToggleComponent,
{
key: commandId,
name: `${name2}`,
value: enabled,
onChange: (value) => toggleCommand(commandId, value)
}
))));
};
var CommandToggleSettings_default = CommandToggleSettings;
// src/settings/components/GeneralSettings.tsx
var GeneralSettings = ({
getLangChainParams,
encryptionService
}) => {
const { settings, updateSettings } = useSettingsContext();
const handleUpdateModels = (models) => {
const updatedActiveModels = models.map((model) => ({
...model,
baseUrl: model.baseUrl || "",
apiKey: model.apiKey || ""
}));
updateSettings({ activeModels: updatedActiveModels });
};
const onSetDefaultModelKey = (modelKey) => {
updateSettings({ defaultModelKey: modelKey });
};
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);
if (newDefaultModel) {
newDefaultModelKey = `${newDefaultModel.name}|${newDefaultModel.provider}`;
} else {
newDefaultModelKey = "";
}
}
updateSettings({
activeModels: updatedActiveModels,
defaultModelKey: newDefaultModelKey
});
};
return /* @__PURE__ */ import_react18.default.createElement("div", null, /* @__PURE__ */ import_react18.default.createElement("h2", null, "General Settings"), /* @__PURE__ */ import_react18.default.createElement(
ModelSettingsComponent,
{
activeModels: settings.activeModels,
onUpdateModels: handleUpdateModels,
providers: Object.values(ChatModelProviders),
onDeleteModel,
defaultModelKey: settings.defaultModelKey,
onSetDefaultModelKey,
isEmbeddingModel: false
}
), /* @__PURE__ */ import_react18.default.createElement("div", { className: "chat-icon-selection-tooltip" }, /* @__PURE__ */ import_react18.default.createElement("div", { className: "select-wrapper" }, /* @__PURE__ */ import_react18.default.createElement("h2", null, "Default Mode"), /* @__PURE__ */ import_react18.default.createElement(
"select",
{
id: "defaultChainSelect",
className: "chat-icon-selection",
value: settings.defaultChainType,
onChange: (e4) => updateSettings({ defaultChainType: e4.target.value })
},
/* @__PURE__ */ import_react18.default.createElement("option", { value: "llm_chain" /* LLM_CHAIN */ }, "Chat"),
/* @__PURE__ */ import_react18.default.createElement("option", { value: "vault_qa" /* VAULT_QA_CHAIN */ }, "Vault QA (Basic)")
), /* @__PURE__ */ import_react18.default.createElement("span", { className: "tooltip-text" }, "Default Mode Selection"))), /* @__PURE__ */ import_react18.default.createElement(
TextComponent,
{
name: "Default Conversation Folder Name",
description: "The default folder name where chat conversations will be saved. Default is 'copilot-conversations'",
placeholder: "copilot-conversations",
value: settings.defaultSaveFolder,
onChange: (value) => updateSettings({ defaultSaveFolder: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
TextComponent,
{
name: "Default Conversation Tag",
description: "The default tag to be used when saving a conversation. Default is 'ai-conversations'",
placeholder: "ai-conversation",
value: settings.defaultConversationTag,
onChange: (value) => updateSettings({ defaultConversationTag: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
ToggleComponent,
{
name: "Autosave Chat",
description: "Automatically save the chat when starting a new one or when the plugin reloads",
value: settings.autosaveChat,
onChange: (value) => updateSettings({ autosaveChat: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
TextComponent,
{
name: "Custom Prompts Folder Name",
description: "The default folder name where custom prompts will be saved. Default is 'copilot-custom-prompts'",
placeholder: "copilot-custom-prompts",
value: settings.customPromptsFolder,
onChange: (value) => updateSettings({ customPromptsFolder: value })
}
), /* @__PURE__ */ import_react18.default.createElement("h6", null, "Please be mindful of the number of tokens and context conversation turns you set here, as they will affect the cost of your API requests."), /* @__PURE__ */ import_react18.default.createElement(
SliderComponent,
{
name: "Temperature",
description: "Default is 0.1. Higher values will result in more creativeness, but also more mistakes. Set to 0 for no randomness.",
min: 0,
max: 2,
step: 0.05,
value: settings.temperature,
onChange: (value) => updateSettings({ temperature: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
SliderComponent,
{
name: "Token limit",
description: /* @__PURE__ */ import_react18.default.createElement(import_react18.default.Fragment, null, /* @__PURE__ */ import_react18.default.createElement("p", null, "The maximum number of ", /* @__PURE__ */ import_react18.default.createElement("em", null, "output tokens"), " to generate. Default is 1000."), /* @__PURE__ */ import_react18.default.createElement("em", null, "This number plus the length of your prompt (input tokens) must be smaller than the context window of the model.")),
min: 0,
max: 16e3,
step: 100,
value: settings.maxTokens,
onChange: (value) => updateSettings({ maxTokens: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
SliderComponent,
{
name: "Conversation turns in context",
description: "The number of previous conversation turns to include in the context. Default is 15 turns, i.e. 30 messages.",
min: 1,
max: 50,
step: 1,
value: settings.contextTurns,
onChange: (value) => updateSettings({ contextTurns: value })
}
), /* @__PURE__ */ import_react18.default.createElement(
CommandToggleSettings_default,
{
enabledCommands: settings.enabledCommands,
setEnabledCommands: (value) => updateSettings({ enabledCommands: value })
}
));
};
var GeneralSettings_default = GeneralSettings;
// src/settings/components/QASettings.tsx
var import_react19 = __toESM(require_react());
var QASettings = ({
indexVaultToVectorStore,
setIndexVaultToVectorStore,
maxSourceChunks,
setMaxSourceChunks
}) => {
const { settings, updateSettings } = useSettingsContext();
const handleUpdateEmbeddingModels = (models) => {
const updatedActiveEmbeddingModels = models.map((model) => ({
...model,
baseUrl: model.baseUrl || "",
apiKey: model.apiKey || ""
}));
updateSettings({ activeEmbeddingModels: updatedActiveEmbeddingModels });
};
const handleSetEmbeddingModelKey = (modelKey) => {
updateSettings({ embeddingModelKey: modelKey });
};
return /* @__PURE__ */ import_react19.default.createElement("div", null, /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("h1", null, "QA Settings"), /* @__PURE__ */ import_react19.default.createElement("p", null, "QA mode relies on a ", /* @__PURE__ */ import_react19.default.createElement("em", null, "local"), " vector index."), /* @__PURE__ */ import_react19.default.createElement("h2", null, "Local Embedding Model"), /* @__PURE__ */ import_react19.default.createElement("p", null, "Check the", " ", /* @__PURE__ */ import_react19.default.createElement("a", { href: "https://github.com/logancyang/obsidian-copilot/blob/master/local_copilot.md" }, "local copilot"), " ", "setup guide to setup Ollama's local embedding model (requires Ollama v0.1.26 or above)."), /* @__PURE__ */ import_react19.default.createElement("h2", null, "Embedding Models"), /* @__PURE__ */ import_react19.default.createElement(
ModelSettingsComponent,
{
activeModels: settings.activeEmbeddingModels,
onUpdateModels: handleUpdateEmbeddingModels,
providers: Object.values(EmbeddingModelProviders),
onDeleteModel: (modelKey) => {
const updatedActiveEmbeddingModels = settings.activeEmbeddingModels.filter(
(model) => `${model.name}|${model.provider}` !== modelKey
);
updateSettings({ activeEmbeddingModels: updatedActiveEmbeddingModels });
},
defaultModelKey: settings.embeddingModelKey,
onSetDefaultModelKey: handleSetEmbeddingModelKey,
isEmbeddingModel: true
}
), /* @__PURE__ */ import_react19.default.createElement("h1", null, "Auto-Index Strategy"), /* @__PURE__ */ import_react19.default.createElement("div", { className: "warning-message" }, "If you are using a paid embedding provider, beware of costs for large vaults!"), /* @__PURE__ */ import_react19.default.createElement("p", null, "When you switch to ", /* @__PURE__ */ import_react19.default.createElement("strong", null, "Vault QA"), " mode, your vault is indexed", " ", /* @__PURE__ */ import_react19.default.createElement("em", null, "based on the auto-index strategy you select below"), ".", /* @__PURE__ */ import_react19.default.createElement("br", null)), /* @__PURE__ */ import_react19.default.createElement(
DropdownComponent,
{
name: "Auto-index vault strategy",
description: "Decide when you want the vault to be indexed.",
value: indexVaultToVectorStore,
onChange: setIndexVaultToVectorStore,
options: VAULT_VECTOR_STORE_STRATEGIES
}
), /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("p", null, /* @__PURE__ */ import_react19.default.createElement("strong", null, "NEVER"), ": Notes are never indexed to the vector store unless users run the command ", /* @__PURE__ */ import_react19.default.createElement("em", null, "Index vault for QA"), " explicitly, or hit the ", /* @__PURE__ */ import_react19.default.createElement("em", null, "Refresh Index"), " button.", /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("strong", null, "ON STARTUP"), ": Vault index is refreshed on plugin load/reload.", /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("strong", null, "ON MODE SWITCH (Recommended)"), ": Vault index is refreshed when switching to Vault QA mode.", /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("br", null), 'By "refreshed", it means the vault index is not rebuilt from scratch but rather updated incrementally with new/modified notes since the last index. If you need a complete rebuild, run the commands "Clear vector store" and "Force re-index for QA" manually. This helps reduce costs when using paid embedding models.', /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement("br", null), "Beware of the cost if you are using a paid embedding model and have a large vault! You can run Copilot command ", /* @__PURE__ */ import_react19.default.createElement("em", null, "Count total tokens in your vault"), " and refer to your selected embedding model pricing to estimate indexing costs."), /* @__PURE__ */ import_react19.default.createElement("br", null), /* @__PURE__ */ import_react19.default.createElement(
SliderComponent,
{
name: "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: 10,
step: 1,
value: maxSourceChunks,
onChange: async (value) => {
setMaxSourceChunks(value);
}
}
), /* @__PURE__ */ import_react19.default.createElement(
SliderComponent,
{
name: "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) => updateSettings({ embeddingRequestsPerSecond: value })
}
), /* @__PURE__ */ import_react19.default.createElement(
TextAreaComponent,
{
name: "Indexing Exclusions",
description: "Comma separated list of paths, tags, note titles or file extension, e.g. folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]], *.jpg, *.excallidraw.md etc, to be excluded from the indexing process. 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.",
placeholder: "folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]], *.jpg, *.excallidraw.md",
value: settings.qaExclusions,
onChange: (value) => updateSettings({ qaExclusions: value })
}
));
};
var QASettings_default = QASettings;
// src/settings/components/SettingsMain.tsx
var SettingsMain = ({
plugin,
reloadPlugin
}) => {
const { settings, updateSettings, saveSettings, resetSettings } = useSettingsContext();
return /* @__PURE__ */ import_react20.default.createElement(import_react20.default.Fragment, null, /* @__PURE__ */ import_react20.default.createElement("h2", null, "Copilot Settings"), /* @__PURE__ */ import_react20.default.createElement("div", { className: "button-container" }, /* @__PURE__ */ import_react20.default.createElement("button", { className: "mod-cta", onClick: saveSettings }, "Save and Reload"), /* @__PURE__ */ import_react20.default.createElement("button", { className: "mod-cta", onClick: resetSettings }, "Reset to Default Settings")), /* @__PURE__ */ import_react20.default.createElement("div", { className: "warning-message" }, "Please Save and Reload the plugin when you change any setting below!"), /* @__PURE__ */ import_react20.default.createElement(
GeneralSettings_default,
{
getLangChainParams: plugin.getLangChainParams.bind(plugin),
encryptionService: plugin.getEncryptionService()
}
), /* @__PURE__ */ import_react20.default.createElement(
ApiSettings_default,
{
...settings,
setOpenAIApiKey: (value) => updateSettings({ openAIApiKey: value }),
setOpenAIOrgId: (value) => updateSettings({ openAIOrgId: value }),
setGoogleApiKey: (value) => updateSettings({ googleApiKey: value }),
setAnthropicApiKey: (value) => updateSettings({ anthropicApiKey: value }),
setOpenRouterAiApiKey: (value) => updateSettings({ openRouterAiApiKey: value }),
setAzureOpenAIApiKey: (value) => updateSettings({ azureOpenAIApiKey: value }),
setAzureOpenAIApiInstanceName: (value) => updateSettings({ azureOpenAIApiInstanceName: value }),
setAzureOpenAIApiDeploymentName: (value) => updateSettings({ azureOpenAIApiDeploymentName: value }),
setAzureOpenAIApiVersion: (value) => updateSettings({ azureOpenAIApiVersion: value }),
setAzureOpenAIApiEmbeddingDeploymentName: (value) => updateSettings({ azureOpenAIApiEmbeddingDeploymentName: value }),
setGroqApiKey: (value) => updateSettings({ groqApiKey: value }),
setCohereApiKey: (value) => updateSettings({ cohereApiKey: value })
}
), /* @__PURE__ */ import_react20.default.createElement(
QASettings_default,
{
...settings,
setHuggingfaceApiKey: (value) => updateSettings({ huggingfaceApiKey: value }),
setIndexVaultToVectorStore: (value) => updateSettings({ indexVaultToVectorStore: value }),
setMaxSourceChunks: (value) => updateSettings({ maxSourceChunks: value })
}
), /* @__PURE__ */ import_react20.default.createElement(
AdvancedSettings_default,
{
...settings,
setUserSystemPrompt: (value) => updateSettings({ userSystemPrompt: value })
}
));
};
var SettingsMain_default = import_react20.default.memo(SettingsMain);
// src/settings/SettingsPage.tsx
var CopilotSettingTab = class extends import_obsidian24.PluginSettingTab {
constructor(app2, plugin) {
super(app2, plugin);
this.plugin = plugin;
}
async reloadPlugin() {
try {
await this.plugin.saveSettings();
const chatView = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0]?.view;
if (chatView && this.plugin.settings.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_obsidian24.Notice("Plugin reloaded successfully.");
} catch (error) {
new import_obsidian24.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_client4.createRoot)(div);
sections.render(
/* @__PURE__ */ import_react21.default.createElement(SettingsProvider, { plugin: this.plugin, reloadPlugin: this.reloadPlugin.bind(this) }, /* @__PURE__ */ import_react21.default.createElement(SettingsMain_default, { plugin: this.plugin, reloadPlugin: this.reloadPlugin.bind(this) }))
);
const devModeHeader = containerEl.createEl("h1", { text: "Additional Settings" });
devModeHeader.style.marginTop = "40px";
new import_obsidian24.Setting(containerEl).setName("Enable Encryption").setDesc(
createFragment((frag) => {
frag.appendText("Enable encryption for the API keys.");
})
).addToggle(
(toggle) => toggle.setValue(this.plugin.settings.enableEncryption).onChange(async (value) => {
this.plugin.settings.enableEncryption = value;
await this.plugin.saveSettings();
})
);
new import_obsidian24.Setting(containerEl).setName("Debug mode").setDesc(
createFragment((frag) => {
frag.appendText("Debug mode will log all API requests and prompts to the console.");
})
).addToggle(
(toggle) => toggle.setValue(this.plugin.settings.debug).onChange(async (value) => {
this.plugin.settings.debug = value;
await this.plugin.saveSettings();
})
);
}
};
// src/main.ts
var import_obsidian25 = require("obsidian");
var CopilotPlugin = class extends import_obsidian25.Plugin {
constructor() {
super(...arguments);
this.activateViewPromise = null;
this.chatIsVisible = false;
this.userMessageHistory = [];
this.isChatVisible = () => this.chatIsVisible;
this.handleContextMenu = (menu, editor) => {
this.addContextMenu(menu, editor, this);
};
this.addContextMenu = (menu, editor, plugin) => {
menu.addItem((item) => {
item.setTitle("Copilot: Summarize Selection").setIcon("bot").onClick(async (e4) => {
plugin.processSelection(editor, "summarizeSelection");
});
});
};
}
async onload() {
await this.loadSettings();
this.addSettingTab(new CopilotSettingTab(this.app, this));
this.sharedState = new sharedState_default();
this.encryptionService = new EncryptionService(this.settings);
this.vectorStoreManager = new VectorStoreManager_default(
this.app,
this.settings,
this.encryptionService,
() => this.getLangChainParams()
);
if (this.settings.enableEncryption) {
await this.saveSettings();
}
vectorDBManager_default.initialize({
getEmbeddingRequestsPerSecond: () => this.settings.embeddingRequestsPerSecond,
debug: this.settings.debug
});
this.mergeAllActiveModelsWithCoreModels();
this.chainManager = new ChainManager(
this.app,
() => this.getLangChainParams(),
this.encryptionService,
this.settings,
this.vectorStoreManager
);
this.registerView(CHAT_VIEWTYPE, (leaf) => new CopilotView(leaf, this));
this.initActiveLeafChangeHandler();
this.addCommand({
id: "chat-toggle-window",
name: "Toggle Copilot Chat Window",
callback: () => {
this.toggleView();
}
});
this.addCommand({
id: "chat-toggle-window-note-area",
name: "Toggle Copilot Chat Window in Note Area",
callback: () => {
this.toggleViewNoteArea();
}
});
this.addRibbonIcon("message-square", "Copilot Chat", (evt) => {
this.toggleView();
});
registerBuiltInCommands(this);
const promptProcessor = CustomPromptProcessor.getInstance(
this.app.vault,
this.settings,
new TimestampUsageStrategy(this.settings, () => this.saveSettings())
);
this.addCommand({
id: "add-custom-prompt",
name: "Add custom prompt",
callback: () => {
new AddPromptModal(this.app, async (title, prompt) => {
try {
await promptProcessor.savePrompt(title, prompt);
new import_obsidian25.Notice("Custom prompt saved successfully.");
} catch (e4) {
new import_obsidian25.Notice("Error saving custom prompt. Please check if the title already exists.");
console.error(e4);
}
}).open();
}
});
this.addCommand({
id: "apply-custom-prompt",
name: "Apply custom prompt",
callback: async () => {
const prompts = await promptProcessor.getAllPrompts();
const promptTitles = prompts.map((p4) => p4.title);
new ListPromptModal(this.app, promptTitles, async (promptTitle) => {
if (!promptTitle) {
new import_obsidian25.Notice("Please select a prompt title.");
return;
}
try {
const prompt = await promptProcessor.getPrompt(promptTitle);
if (!prompt) {
new import_obsidian25.Notice(`No prompt found with the title "${promptTitle}".`);
return;
}
this.processCustomPrompt("applyCustomPrompt", prompt.content);
} catch (err) {
console.error(err);
new import_obsidian25.Notice("An error occurred.");
}
}).open();
}
});
this.addCommand({
id: "apply-adhoc-prompt",
name: "Apply ad-hoc custom prompt",
callback: async () => {
const modal = new AdhocPromptModal(this.app, async (adhocPrompt) => {
try {
this.processCustomPrompt("applyAdhocPrompt", adhocPrompt);
} catch (err) {
console.error(err);
new import_obsidian25.Notice("An error occurred.");
}
});
modal.open();
}
});
this.addCommand({
id: "delete-custom-prompt",
name: "Delete custom prompt",
checkCallback: (checking) => {
if (checking) {
return true;
}
promptProcessor.getAllPrompts().then((prompts) => {
const promptTitles = prompts.map((p4) => p4.title);
new ListPromptModal(this.app, promptTitles, async (promptTitle) => {
if (!promptTitle) {
new import_obsidian25.Notice("Please select a prompt title.");
return;
}
try {
await promptProcessor.deletePrompt(promptTitle);
new import_obsidian25.Notice(`Prompt "${promptTitle}" has been deleted.`);
} catch (err) {
console.error(err);
new import_obsidian25.Notice("An error occurred while deleting the prompt.");
}
}).open();
});
return true;
}
});
this.addCommand({
id: "edit-custom-prompt",
name: "Edit custom prompt",
checkCallback: (checking) => {
if (checking) {
return true;
}
promptProcessor.getAllPrompts().then((prompts) => {
const promptTitles = prompts.map((p4) => p4.title);
new ListPromptModal(this.app, promptTitles, async (promptTitle) => {
if (!promptTitle) {
new import_obsidian25.Notice("Please select a prompt title.");
return;
}
try {
const prompt = await promptProcessor.getPrompt(promptTitle);
if (prompt) {
new AddPromptModal(
this.app,
async (title, newPrompt) => {
try {
await promptProcessor.updatePrompt(promptTitle, title, newPrompt);
new import_obsidian25.Notice(`Prompt "${title}" has been updated.`);
} catch (err) {
console.error(err);
if (err instanceof CustomError) {
new import_obsidian25.Notice(err.msg);
} else {
new import_obsidian25.Notice("An error occurred.");
}
}
},
prompt.title,
prompt.content,
false
).open();
} else {
new import_obsidian25.Notice(`No prompt found with the title "${promptTitle}".`);
}
} catch (err) {
console.error(err);
new import_obsidian25.Notice("An error occurred.");
}
}).open();
});
return true;
}
});
this.addCommand({
id: "clear-local-vector-store",
name: "Clear local vector store",
callback: async () => {
await this.vectorStoreManager.clearVectorStore();
}
});
this.addCommand({
id: "garbage-collect-vector-store",
name: "Garbage collect vector store (remove files that no longer exist in vault)",
callback: async () => {
await this.vectorStoreManager.garbageCollectVectorStore();
}
});
this.addCommand({
id: "index-vault-to-vector-store",
name: "Index (refresh) vault for QA",
callback: async () => {
try {
const indexedFileCount = await this.vectorStoreManager.indexVaultToVectorStore();
new import_obsidian25.Notice(`${indexedFileCount} vault files indexed to vector store.`);
console.log(`${indexedFileCount} vault files indexed to vector store.`);
} catch (err) {
console.error("Error indexing vault to vector store:", err);
new import_obsidian25.Notice("An error occurred while indexing vault to vector store.");
}
}
});
this.addCommand({
id: "force-reindex-vault-to-vector-store",
name: "Force re-index vault for QA",
callback: async () => {
try {
await this.vectorStoreManager.clearVectorStore();
const indexedFileCount = await this.vectorStoreManager.indexVaultToVectorStore(true);
new import_obsidian25.Notice(`${indexedFileCount} vault files re-indexed to vector store.`);
console.log(`${indexedFileCount} vault files re-indexed to vector store.`);
} catch (err) {
console.error("Error re-indexing vault to vector store:", err);
new import_obsidian25.Notice("An error occurred while re-indexing vault to vector store.");
}
}
});
this.addCommand({
id: "load-copilot-chat-conversation",
name: "Load Copilot Chat conversation",
callback: () => {
this.loadCopilotChatHistory();
}
});
this.addCommand({
id: "find-similar-notes",
name: "Find similar notes to active note",
callback: async () => {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile) {
new import_obsidian25.Notice("No active file");
return;
}
const activeNoteContent = await this.app.vault.cachedRead(activeFile);
const similarChunks = await this.findSimilarNotes(activeNoteContent, activeFile.path);
new SimilarNotesModal(this.app, similarChunks).open();
}
});
this.registerEvent(
this.app.vault.on("delete", async (file) => {
await this.vectorStoreManager.removeDocs(file.path);
})
);
if (this.settings.indexVaultToVectorStore === "ON STARTUP" /* ON_STARTUP */) {
try {
await this.vectorStoreManager.indexVaultToVectorStore();
} catch (err) {
console.error("Error saving vault to vector store:", err);
new import_obsidian25.Notice("An error occurred while saving vault to vector store.");
}
}
this.registerEvent(this.app.workspace.on("editor-menu", this.handleContextMenu));
}
updateUserMessageHistory(newMessage) {
this.userMessageHistory = [...this.userMessageHistory, newMessage];
}
async autosaveCurrentChat() {
if (this.settings.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.emitter.dispatchEvent(event);
}
}, 0);
}
processSelection(editor, eventType, eventSubtype) {
this.processText(editor, eventType, eventSubtype);
}
processChatIsVisible(chatIsVisible) {
if (this.chatIsVisible === chatIsVisible) {
return;
}
this.chatIsVisible = chatIsVisible;
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, {
detail: { chatIsVisible: this.chatIsVisible }
});
activeCopilotView.emitter.dispatchEvent(event);
}
}
initActiveLeafChangeHandler() {
this.registerEvent(
this.app.workspace.on("active-leaf-change", (leaf) => {
if (!leaf) {
return;
}
this.processChatIsVisible(leaf.getViewState().type === CHAT_VIEWTYPE);
})
);
}
getCurrentEditorOrDummy() {
const activeView = this.app.workspace.getActiveViewOfType(import_obsidian25.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);
leaves.length > 0 ? this.deactivateView() : this.activateView();
}
async activateView() {
this.app.workspace.detachLeavesOfType(CHAT_VIEWTYPE);
this.activateViewPromise = this.app.workspace.getRightLeaf(false).setViewState({
type: CHAT_VIEWTYPE,
active: true
});
await this.activateViewPromise;
this.app.workspace.revealLeaf(this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0]);
this.processChatIsVisible(true);
}
async deactivateView() {
this.app.workspace.detachLeavesOfType(CHAT_VIEWTYPE);
this.processChatIsVisible(false);
}
async toggleViewNoteArea() {
const leaves = this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE);
leaves.length > 0 ? this.deactivateView() : this.activateViewNoteArea();
}
async activateViewNoteArea() {
this.app.workspace.detachLeavesOfType(CHAT_VIEWTYPE);
this.activateViewPromise = this.app.workspace.getLeaf(true).setViewState({
type: CHAT_VIEWTYPE,
active: true
});
await this.activateViewPromise;
this.app.workspace.revealLeaf(this.app.workspace.getLeavesOfType(CHAT_VIEWTYPE)[0]);
this.processChatIsVisible(true);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.mergeAllActiveModelsWithCoreModels();
}
mergeActiveModels(existingActiveModels, builtInModels) {
const modelMap = /* @__PURE__ */ new Map();
const getModelKey = (model) => `${model.name}|${model.provider}`;
builtInModels.filter((model) => model.core).forEach((model) => {
modelMap.set(getModelKey(model), { ...model, core: true });
});
existingActiveModels.forEach((model) => {
const key = getModelKey(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());
}
mergeAllActiveModelsWithCoreModels() {
this.settings.activeModels = this.mergeActiveModels(
this.settings.activeModels,
BUILTIN_CHAT_MODELS
);
this.settings.activeEmbeddingModels = this.mergeActiveModels(
this.settings.activeEmbeddingModels,
BUILTIN_EMBEDDING_MODELS
);
}
async saveSettings() {
if (this.settings.enableEncryption) {
this.encryptionService.encryptAllKeys();
}
this.mergeAllActiveModelsWithCoreModels();
await this.saveData(this.settings);
}
async countTotalTokens() {
try {
const allContent = await getAllNotesContent(this.app.vault);
const totalTokens = await this.chainManager.chatModelManager.countTokens(allContent);
return totalTokens;
} catch (error) {
console.error("Error counting tokens: ", error);
return 0;
}
}
getLangChainParams() {
if (!this.settings) {
throw new Error("Settings are not loaded");
}
const {
openAIApiKey,
openAIOrgId,
huggingfaceApiKey,
cohereApiKey,
anthropicApiKey,
azureOpenAIApiKey,
azureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName,
azureOpenAIApiVersion,
azureOpenAIApiEmbeddingDeploymentName,
googleApiKey,
openRouterAiApiKey,
embeddingModelKey,
temperature,
maxTokens,
contextTurns,
groqApiKey
} = sanitizeSettings(this.settings);
return {
openAIApiKey,
openAIOrgId,
huggingfaceApiKey,
cohereApiKey,
anthropicApiKey,
groqApiKey,
azureOpenAIApiKey,
azureOpenAIApiInstanceName,
azureOpenAIApiDeploymentName,
azureOpenAIApiVersion,
azureOpenAIApiEmbeddingDeploymentName,
googleApiKey,
openRouterAiApiKey,
modelKey: this.settings.defaultModelKey,
embeddingModelKey: embeddingModelKey || DEFAULT_SETTINGS.embeddingModelKey,
temperature: Number(temperature),
maxTokens: Number(maxTokens),
systemMessage: this.settings.userSystemPrompt || DEFAULT_SYSTEM_PROMPT,
chatContextTurns: Number(contextTurns),
chainType: "llm_chain" /* LLM_CHAIN */,
// Set LLM_CHAIN as default ChainType
options: { forceNewCreation: true, debug: this.settings.debug },
openAIProxyBaseUrl: this.settings.openAIProxyBaseUrl,
openAIEmbeddingProxyBaseUrl: this.settings.openAIEmbeddingProxyBaseUrl
};
}
getEncryptionService() {
return this.encryptionService;
}
async loadCopilotChatHistory() {
const chatFiles = await this.getChatHistoryFiles();
if (chatFiles.length === 0) {
new import_obsidian25.Notice("No chat history found.");
return;
}
new LoadChatHistoryModal(this.app, chatFiles, this.loadChatHistory.bind(this)).open();
}
async getChatHistoryFiles() {
const folder = this.app.vault.getAbstractFileByPath(this.settings.defaultSaveFolder);
if (!(folder instanceof import_obsidian25.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 findSimilarNotes(content, activeFilePath) {
await this.vectorStoreManager.waitForInitialization();
const db = this.vectorStoreManager.getDb();
const singleDoc = await search2(db, {
term: "",
limit: 1
});
if (singleDoc.hits.length === 0) {
new import_obsidian25.Notice("Index does not exist, indexing vault for similarity search...");
await this.vectorStoreManager.indexVaultToVectorStore();
}
const hybridRetriever = new HybridRetriever(
db,
this.app.vault,
this.chainManager.chatModelManager.getChatModel(),
this.vectorStoreManager.getEmbeddingsManager().getEmbeddingsAPI(),
{
minSimilarityScore: 0.3,
maxK: 20
},
this.settings.debug
);
const truncatedContent = content.length > CHUNK_SIZE ? content.slice(0, CHUNK_SIZE) : content;
const similarDocs = await hybridRetriever.getRelevantDocuments(truncatedContent, {
runName: "no_hyde"
});
return similarDocs.filter((doc) => doc.metadata.path !== activeFilePath).map((doc) => ({
chunk: doc,
score: doc.metadata.score || 0
})).sort((a4, b3) => b3.score - a4.score);
}
};
/*! 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
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
@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
*)
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> *)
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/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.
*)
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
*)
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
*)
@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 */