diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json index 5e67b72..2ec43a3 100644 --- a/.obsidian/community-plugins.json +++ b/.obsidian/community-plugins.json @@ -13,5 +13,6 @@ "pdf-plus", "better-export-pdf", "ai-image-analyzer", - "obsidian-tasks-plugin" + "obsidian-tasks-plugin", + "obsidian-git" ] \ No newline at end of file diff --git a/.obsidian/graph.json b/.obsidian/graph.json index fdf7e71..b33cdc9 100644 --- a/.obsidian/graph.json +++ b/.obsidian/graph.json @@ -17,6 +17,6 @@ "repelStrength": 11.9270833333333, "linkStrength": 1, "linkDistance": 188, - "scale": 0.8211076128271817, + "scale": 1.4420199290482825, "close": true } \ No newline at end of file diff --git a/.obsidian/plugins/copilot/main.js b/.obsidian/plugins/copilot/main.js index 40f1b1c..c388801 100644 --- a/.obsidian/plugins/copilot/main.js +++ b/.obsidian/plugins/copilot/main.js @@ -3,21116 +3,66 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// node_modules/zod/lib/index.mjs -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === errorMap ? void 0 : errorMap - // then global default map - ].filter((x2) => !!x2) - }); - ctx.common.issues.push(issue); -} -function __classPrivateFieldGet(receiver, state, kind4, f3) { - if (kind4 === "a" && !f3) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind4 === "m" ? f3 : kind4 === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver); -} -function __classPrivateFieldSet(receiver, state, value, kind4, f3) { - if (kind4 === "m") - throw new TypeError("Private method is not writable"); - if (kind4 === "a" && !f3) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind4 === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value; -} -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - var _a5, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a5 = message !== null && message !== void 0 ? message : required_error) !== null && _a5 !== void 0 ? _a5 : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -function timeRegexSource(args) { - let regex2 = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; - if (args.precision) { - regex2 = `${regex2}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - regex2 = `${regex2}(\\.\\d+)?`; - } - return regex2; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex2 = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex2 = `${regex2}(${opts.join("|")})`; - return new RegExp(`^${regex2}$`); -} -function isValidIP(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base642)); - if (typeof decoded !== "object" || decoded === null) - return false; - if (!decoded.typ || !decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch (_a5) { - return false; - } -} -function isValidCidr(ip, version2) { - if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -function floatSafeRemainder(val2, step) { - const valDecCount = (val2.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val2.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / Math.pow(10, decCount); -} -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -function mergeValues(a3, b3) { - const aType = getParsedType(a3); - const bType = getParsedType(b3); - if (a3 === b3) { - return { valid: true, data: a3 }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b3); - const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a3, ...b3 }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a3[key], b3[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a3.length !== b3.length) { - return { valid: false }; - } - const newArray = []; - for (let index2 = 0; index2 < a3.length; index2++) { - const itemA = a3[index2]; - const itemB = b3[index2]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b3) { - return { valid: true, data: a3 }; - } else { - return { valid: false }; - } -} -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -function custom(check, params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a5, _b; - if (!check(data)) { - const p3 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const _fatal = (_b = (_a5 = p3.fatal) !== null && _a5 !== void 0 ? _a5 : fatal) !== null && _b !== void 0 ? _b : true; - const p22 = typeof p3 === "string" ? { message: p3 } : p3; - ctx.addIssue({ code: "custom", ...p22, fatal: _fatal }); - } - }); - return ZodAny.create(); -} -var util, objectUtil, ZodParsedType, getParsedType, ZodIssueCode, quotelessJson, ZodError, errorMap, overrideErrorMap, makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache, ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER, z; -var init_lib = __esm({ - "node_modules/zod/lib/index.mjs"() { - (function(util2) { - util2.assertEqual = (val2) => val2; - function assertIs(_arg) { - } - util2.assertIs = assertIs; - function assertNever2(_x) { - throw new Error(); - } - util2.assertNever = assertNever2; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); - const filtered = {}; - for (const k3 of validKeys) { - filtered[k3] = obj[k3]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e3) { - return obj[e3]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr2, checker) => { - for (const item of arr2) { - if (checker(item)) - return item; - } - return void 0; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && isFinite(val2) && Math.floor(val2) === val2; - function joinValues(array, separator = " | ") { - return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); - } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_2, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; - })(util || (util = {})); - (function(objectUtil2) { - objectUtil2.mergeShapes = (first, second2) => { - return { - ...first, - ...second2 - // second overwrites first - }; - }; - })(objectUtil || (objectUtil = {})); - ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" - ]); - getParsedType = (data) => { - const t3 = typeof data; - switch (t3) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } - }; - ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" - ]); - quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); - }; - ZodError = class extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i3 = 0; - while (i3 < issue.path.length) { - const el = issue.path[i3]; - const terminal = i3 === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i3++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } - }; - ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; - }; - errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; - }; - overrideErrorMap = errorMap; - makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m3) => !!m3).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; - }; - EMPTY_PATH = []; - ParseStatus = class { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s4 of results) { - if (s4.status === "aborted") - return INVALID; - if (s4.status === "dirty") - status.dirty(); - arrayValue.push(s4.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } - }; - INVALID = Object.freeze({ - status: "aborted" - }); - DIRTY = (value) => ({ status: "dirty", value }); - OK = (value) => ({ status: "valid", value }); - isAborted = (x2) => x2.status === "aborted"; - isDirty = (x2) => x2.status === "dirty"; - isValid = (x2) => x2.status === "valid"; - isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; - (function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; - })(errorUtil || (errorUtil = {})); - ParseInputLazyPath = class { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } - }; - handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } - }; - ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a5; - const ctx = { - common: { - issues: [], - async: (_a5 = params === null || params === void 0 ? void 0 : params.async) !== null && _a5 !== void 0 ? _a5 : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - var _a5, _b; - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if ((_b = (_a5 = err === null || err === void 0 ? void 0 : err.message) === null || _a5 === void 0 ? void 0 : _a5.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val2) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val2); - } else { - return message; - } - }; - return this._refinement((val2, ctx) => { - const result = check(val2); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val2) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val2, ctx) => { - if (!check(val2)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } - }; - cuidRegex = /^c[^\s-]{8,}$/i; - cuid2Regex = /^[0-9a-z]+$/; - ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; - uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; - nanoidRegex = /^[a-z0-9_-]{21}$/i; - jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; - durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; - _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; - ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; - ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; - dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; - dateRegex = new RegExp(`^${dateRegexSource}$`); - ZodString = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch (_a5) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex2 = datetimeRegex(check); - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex2 = dateRegex; - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex2 = timeRegex(check); - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex2, validation, message) { - return this.refinement((data) => regex2.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - var _a5, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a5 = options === null || options === void 0 ? void 0 : options.offset) !== null && _a5 !== void 0 ? _a5 : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex2, message) { - return this._addCheck({ - kind: "regex", - regex: regex2, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min2 === null || ch.value > min2) - min2 = ch.value; - } - } - return min2; - } - get maxLength() { - let max2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max2 === null || ch.value < max2) - max2 = ch.value; - } - } - return max2; - } - }; - ZodString.create = (params) => { - var _a5; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false, - ...processCreateParams(params) - }); - }; - ZodNumber = class extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind4, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind: kind4, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min2 === null || ch.value > min2) - min2 = ch.value; - } - } - return min2; - } - get maxValue() { - let max2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max2 === null || ch.value < max2) - max2 = ch.value; - } - } - return max2; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max2 = null, min2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min2 === null || ch.value > min2) - min2 = ch.value; - } else if (ch.kind === "max") { - if (max2 === null || ch.value < max2) - max2 = ch.value; - } - } - return Number.isFinite(min2) && Number.isFinite(max2); - } - }; - ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params) - }); - }; - ZodBigInt = class extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch (_a5) { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind4, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind: kind4, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min2 === null || ch.value > min2) - min2 = ch.value; - } - } - return min2; - } - get maxValue() { - let max2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max2 === null || ch.value < max2) - max2 = ch.value; - } - } - return max2; - } - }; - ZodBigInt.create = (params) => { - var _a5; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a5 = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a5 !== void 0 ? _a5 : false, - ...processCreateParams(params) - }); - }; - ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params) - }); - }; - ZodDate = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min2 === null || ch.value > min2) - min2 = ch.value; - } - } - return min2 != null ? new Date(min2) : null; - } - get maxDate() { - let max2 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max2 === null || ch.value < max2) - max2 = ch.value; - } - } - return max2 != null ? new Date(max2) : null; - } - }; - ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); - }; - ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); - }; - ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); - }; - ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); - }; - ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } - }; - ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); - }; - ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } - }; - ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); - }; - ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } - }; - ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); - }; - ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); - }; - ZodArray = class extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i3) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i3)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i3) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i3)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } - }; - ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); - }; - ZodObject = class extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return this._cached = { shape, keys }; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") - ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - var _a5, _b, _c, _d; - const defaultError = (_c = (_b = (_a5 = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a5, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, 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>, - // 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( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index2) { - return new ZodObject({ - ...this._def, - catchall: index2 - }); - } - pick(mask) { - const shape = {}; - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } - }; - ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); - }; - ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); - }; - ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); - }; - ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } - }; - ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); - }; - getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } - }; - ZodDiscriminatedUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } - }; - ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } - }; - ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); - }; - ZodTuple = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x2) => !!x2); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest - }); - } - }; - ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); - }; - ZodRecord = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second2, third) { - if (second2 instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second2, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second2) - }); - } - }; - ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index2) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } - }; - ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); - }; - ZodSet = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i3) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i3))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size4, message) { - return this.min(size4, message).max(size4, message); - } - nonempty(message) { - return this.min(1, message); - } - }; - ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); - }; - ZodFunction = class extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap - ].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap - ].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e3) => { - error.addIssue(makeArgsIssue(args, e3)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e3) => { - error.addIssue(makeReturnsIssue(result, e3)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } - }; - ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } - }; - ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); - }; - ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } - }; - ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); - }; - ZodEnum = class extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); - } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val2 of this._def.values) { - enumValues[val2] = val2; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val2 of this._def.values) { - enumValues[val2] = val2; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val2 of this._def.values) { - enumValues[val2] = val2; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } - }; - _ZodEnum_cache = /* @__PURE__ */ new WeakMap(); - ZodEnum.create = createZodEnum; - ZodNativeEnum = class extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } - }; - _ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap(); - ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); - }; - ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } - }; - ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); - }; - ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } - } - util.assertNever(effect); - } - }; - ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); - }; - ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); - }; - ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - }; - ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); - }; - ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - }; - ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); - }; - ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } - }; - ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); - }; - ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } - }; - ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); - }; - ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - }; - ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); - }; - BRAND = Symbol("zod_brand"); - ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } - }; - ZodPipeline = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a3, b3) { - return new ZodPipeline({ - in: a3, - out: b3, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } - }; - ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } - }; - ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); - }; - late = { - object: ZodObject.lazycreate - }; - (function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; - })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); - instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` - }) => custom((data) => data instanceof cls, params); - stringType = ZodString.create; - numberType = ZodNumber.create; - nanType = ZodNaN.create; - bigIntType = ZodBigInt.create; - booleanType = ZodBoolean.create; - dateType = ZodDate.create; - symbolType = ZodSymbol.create; - undefinedType = ZodUndefined.create; - nullType = ZodNull.create; - anyType = ZodAny.create; - unknownType = ZodUnknown.create; - neverType = ZodNever.create; - voidType = ZodVoid.create; - arrayType = ZodArray.create; - objectType = ZodObject.create; - strictObjectType = ZodObject.strictCreate; - unionType = ZodUnion.create; - discriminatedUnionType = ZodDiscriminatedUnion.create; - intersectionType = ZodIntersection.create; - tupleType = ZodTuple.create; - recordType = ZodRecord.create; - mapType = ZodMap.create; - setType = ZodSet.create; - functionType = ZodFunction.create; - lazyType = ZodLazy.create; - literalType = ZodLiteral.create; - enumType = ZodEnum.create; - nativeEnumType = ZodNativeEnum.create; - promiseType = ZodPromise.create; - effectsType = ZodEffects.create; - optionalType = ZodOptional.create; - nullableType = ZodNullable.create; - preprocessType = ZodEffects.createWithPreprocess; - pipelineType = ZodPipeline.create; - ostring = () => stringType().optional(); - onumber = () => numberType().optional(); - oboolean = () => booleanType().optional(); - coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) - }; - NEVER = INVALID; - z = /* @__PURE__ */ Object.freeze({ - __proto__: null, - defaultErrorMap: errorMap, - setErrorMap, - getErrorMap, - makeIssue, - EMPTY_PATH, - addIssueToContext, - ParseStatus, - INVALID, - DIRTY, - OK, - isAborted, - isDirty, - isValid, - isAsync, - get util() { - return util; - }, - get objectUtil() { - return objectUtil; - }, - ZodParsedType, - getParsedType, - ZodType, - datetimeRegex, - ZodString, - ZodNumber, - ZodBigInt, - ZodBoolean, - ZodDate, - ZodSymbol, - ZodUndefined, - ZodNull, - ZodAny, - ZodUnknown, - ZodNever, - ZodVoid, - ZodArray, - ZodObject, - ZodUnion, - ZodDiscriminatedUnion, - ZodIntersection, - ZodTuple, - ZodRecord, - ZodMap, - ZodSet, - ZodFunction, - ZodLazy, - ZodLiteral, - ZodEnum, - ZodNativeEnum, - ZodPromise, - ZodEffects, - ZodTransformer: ZodEffects, - ZodOptional, - ZodNullable, - ZodDefault, - ZodCatch, - ZodNaN, - BRAND, - ZodBranded, - ZodPipeline, - ZodReadonly, - custom, - Schema: ZodType, - ZodSchema: ZodType, - late, - get ZodFirstPartyTypeKind() { - return ZodFirstPartyTypeKind; - }, - coerce, - any: anyType, - array: arrayType, - bigint: bigIntType, - boolean: booleanType, - date: dateType, - discriminatedUnion: discriminatedUnionType, - effect: effectsType, - "enum": enumType, - "function": functionType, - "instanceof": instanceOfType, - intersection: intersectionType, - lazy: lazyType, - literal: literalType, - map: mapType, - nan: nanType, - nativeEnum: nativeEnumType, - never: neverType, - "null": nullType, - nullable: nullableType, - number: numberType, - object: objectType, - oboolean, - onumber, - optional: optionalType, - ostring, - pipeline: pipelineType, - preprocess: preprocessType, - promise: promiseType, - record: recordType, - set: setType, - strictObject: strictObjectType, - string: stringType, - symbol: symbolType, - transformer: effectsType, - tuple: tupleType, - "undefined": undefinedType, - union: unionType, - unknown: unknownType, - "void": voidType, - NEVER, - ZodIssueCode, - quotelessJson, - ZodError - }); - } -}); - -// node_modules/retry/lib/retry_operation.js -var require_retry_operation = __commonJS({ - "node_modules/retry/lib/retry_operation.js"(exports, module2) { - function RetryOperation(timeouts, options) { - if (typeof options === "boolean") { - options = { forever: options }; - } - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } - } - module2.exports = RetryOperation; - RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); - }; - RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } - this._timeouts = []; - this._cachedTimeouts = null; - }; - RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error("RetryOperation timeout occurred")); - return false; - } - this._errors.push(err); - var timeout = this._timeouts.shift(); - if (timeout === void 0) { - if (this._cachedTimeouts) { - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } - var self2 = this; - this._timer = setTimeout(function() { - self2._attempts++; - if (self2._operationTimeoutCb) { - self2._timeout = setTimeout(function() { - self2._operationTimeoutCb(self2._attempts); - }, self2._operationTimeout); - if (self2._options.unref) { - self2._timeout.unref(); - } - } - self2._fn(self2._attempts); - }, timeout); - if (this._options.unref) { - this._timer.unref(); - } - return true; - }; - RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - var self2 = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self2._operationTimeoutCb(); - }, self2._operationTimeout); - } - this._operationStart = new Date().getTime(); - this._fn(this._attempts); - }; - RetryOperation.prototype.try = function(fn) { - console.log("Using RetryOperation.try() is deprecated"); - this.attempt(fn); - }; - RetryOperation.prototype.start = function(fn) { - console.log("Using RetryOperation.start() is deprecated"); - this.attempt(fn); - }; - RetryOperation.prototype.start = RetryOperation.prototype.try; - RetryOperation.prototype.errors = function() { - return this._errors; - }; - RetryOperation.prototype.attempts = function() { - return this._attempts; - }; - RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - for (var i3 = 0; i3 < this._errors.length; i3++) { - var error = this._errors[i3]; - var message = error.message; - var count5 = (counts[message] || 0) + 1; - counts[message] = count5; - if (count5 >= mainErrorCount) { - mainError = error; - mainErrorCount = count5; - } - } - return mainError; - }; - } -}); - -// node_modules/retry/lib/retry.js -var require_retry = __commonJS({ - "node_modules/retry/lib/retry.js"(exports) { - var RetryOperation = require_retry_operation(); - exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); - }; - exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1e3, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - if (opts.minTimeout > opts.maxTimeout) { - throw new Error("minTimeout is greater than maxTimeout"); - } - var timeouts = []; - for (var i3 = 0; i3 < opts.retries; i3++) { - timeouts.push(this.createTimeout(i3, opts)); - } - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i3, opts)); - } - timeouts.sort(function(a3, b3) { - return a3 - b3; - }); - return timeouts; - }; - exports.createTimeout = function(attempt, opts) { - var random = opts.randomize ? Math.random() + 1 : 1; - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - return timeout; - }; - exports.wrap = function(obj, options, methods2) { - if (options instanceof Array) { - methods2 = options; - options = null; - } - if (!methods2) { - methods2 = []; - for (var key in obj) { - if (typeof obj[key] === "function") { - methods2.push(key); - } - } - } - for (var i3 = 0; i3 < methods2.length; i3++) { - var method = methods2[i3]; - var original = obj[method]; - obj[method] = function retryWrapper2(original2) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - op.attempt(function() { - original2.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } - }; - } -}); - -// node_modules/retry/index.js -var require_retry2 = __commonJS({ - "node_modules/retry/index.js"(exports, module2) { - module2.exports = require_retry(); - } -}); - -// node_modules/p-retry/index.js -var require_p_retry = __commonJS({ - "node_modules/p-retry/index.js"(exports, module2) { - "use strict"; - var retry = require_retry2(); - var networkErrorMsgs = [ - "Failed to fetch", - // Chrome - "NetworkError when attempting to fetch resource.", - // Firefox - "The Internet connection appears to be offline.", - // Safari - "Network request failed" - // `cross-fetch` - ]; - var AbortError = class extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({ message } = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - this.name = "AbortError"; - this.message = message; - } - }; - var decorateErrorWithCounts = (error, attemptNumber, options) => { - const retriesLeft = options.retries - (attemptNumber - 1); - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; - }; - var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); - var pRetry4 = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => { - }, - retries: 10, - ...options - }; - const operation = retry.operation(options); - operation.attempt(async (attemptNumber) => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - try { - await options.onFailedAttempt(error); - } catch (error2) { - reject(error2); - return; - } - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); - }); - module2.exports = pRetry4; - module2.exports.default = pRetry4; - module2.exports.AbortError = AbortError; - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/regex.js -var regex_default; -var init_regex = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/regex.js"() { - regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/validate.js -function validate(uuid) { - return typeof uuid === "string" && regex_default.test(uuid); -} -var validate_default; -var init_validate = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/validate.js"() { - init_regex(); - validate_default = validate; - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/stringify.js -function unsafeStringify(arr2, offset5 = 0) { - return (byteToHex[arr2[offset5 + 0]] + byteToHex[arr2[offset5 + 1]] + byteToHex[arr2[offset5 + 2]] + byteToHex[arr2[offset5 + 3]] + "-" + byteToHex[arr2[offset5 + 4]] + byteToHex[arr2[offset5 + 5]] + "-" + byteToHex[arr2[offset5 + 6]] + byteToHex[arr2[offset5 + 7]] + "-" + byteToHex[arr2[offset5 + 8]] + byteToHex[arr2[offset5 + 9]] + "-" + byteToHex[arr2[offset5 + 10]] + byteToHex[arr2[offset5 + 11]] + byteToHex[arr2[offset5 + 12]] + byteToHex[arr2[offset5 + 13]] + byteToHex[arr2[offset5 + 14]] + byteToHex[arr2[offset5 + 15]]).toLowerCase(); -} -var byteToHex, i3; -var init_stringify = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/stringify.js"() { - byteToHex = []; - for (i3 = 0; i3 < 256; ++i3) { - byteToHex.push((i3 + 256).toString(16).slice(1)); - } - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/rng.js -function rng() { - if (!getRandomValues) { - getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); - if (!getRandomValues) { - throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); - } - } - return getRandomValues(rnds8); -} -var getRandomValues, rnds8; -var init_rng = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/rng.js"() { - rnds8 = new Uint8Array(16); - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/native.js -var randomUUID, native_default; -var init_native = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/native.js"() { - randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); - native_default = { - randomUUID - }; - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/v4.js -function v4(options, buf, offset5) { - if (native_default.randomUUID && !buf && !options) { - return native_default.randomUUID(); - } - options = options || {}; - var rnds = options.random || (options.rng || rng)(); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - offset5 = offset5 || 0; - for (var i3 = 0; i3 < 16; ++i3) { - buf[offset5 + i3] = rnds[i3]; - } - return buf; - } - return unsafeStringify(rnds); -} -var v4_default; -var init_v4 = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/v4.js"() { - init_native(); - init_rng(); - init_stringify(); - v4_default = v4; - } -}); - -// node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/index.js -var init_esm_browser = __esm({ - "node_modules/@langchain/core/node_modules/uuid/dist/esm-browser/index.js"() { - init_v4(); - init_validate(); - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/regex.js -var regex_default2; -var init_regex2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/regex.js"() { - regex_default2 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/validate.js -function validate2(uuid) { - return typeof uuid === "string" && regex_default2.test(uuid); -} -var validate_default2; -var init_validate2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/validate.js"() { - init_regex2(); - validate_default2 = validate2; - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js -function unsafeStringify2(arr2, offset5 = 0) { - return (byteToHex2[arr2[offset5 + 0]] + byteToHex2[arr2[offset5 + 1]] + byteToHex2[arr2[offset5 + 2]] + byteToHex2[arr2[offset5 + 3]] + "-" + byteToHex2[arr2[offset5 + 4]] + byteToHex2[arr2[offset5 + 5]] + "-" + byteToHex2[arr2[offset5 + 6]] + byteToHex2[arr2[offset5 + 7]] + "-" + byteToHex2[arr2[offset5 + 8]] + byteToHex2[arr2[offset5 + 9]] + "-" + byteToHex2[arr2[offset5 + 10]] + byteToHex2[arr2[offset5 + 11]] + byteToHex2[arr2[offset5 + 12]] + byteToHex2[arr2[offset5 + 13]] + byteToHex2[arr2[offset5 + 14]] + byteToHex2[arr2[offset5 + 15]]).toLowerCase(); -} -var byteToHex2, i3; -var init_stringify2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/stringify.js"() { - byteToHex2 = []; - for (i3 = 0; i3 < 256; ++i3) { - byteToHex2.push((i3 + 256).toString(16).slice(1)); - } - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/rng.js -function rng2() { - if (!getRandomValues2) { - getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); - if (!getRandomValues2) { - throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); - } - } - return getRandomValues2(rnds82); -} -var getRandomValues2, rnds82; -var init_rng2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/rng.js"() { - rnds82 = new Uint8Array(16); - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/native.js -var randomUUID2, native_default2; -var init_native2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/native.js"() { - randomUUID2 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); - native_default2 = { - randomUUID: randomUUID2 - }; - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/v4.js -function v42(options, buf, offset5) { - if (native_default2.randomUUID && !buf && !options) { - return native_default2.randomUUID(); - } - options = options || {}; - var rnds = options.random || (options.rng || rng2)(); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - offset5 = offset5 || 0; - for (var i3 = 0; i3 < 16; ++i3) { - buf[offset5 + i3] = rnds[i3]; - } - return buf; - } - return unsafeStringify2(rnds); -} -var v4_default2; -var init_v42 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/v4.js"() { - init_native2(); - init_rng2(); - init_stringify2(); - v4_default2 = v42; - } -}); - -// node_modules/langsmith/node_modules/uuid/dist/esm-browser/index.js -var init_esm_browser2 = __esm({ - "node_modules/langsmith/node_modules/uuid/dist/esm-browser/index.js"() { - init_v42(); - init_validate2(); - } -}); - -// node_modules/eventemitter3/index.js -var require_eventemitter3 = __commonJS({ - "node_modules/eventemitter3/index.js"(exports, module2) { - "use strict"; - var has2 = Object.prototype.hasOwnProperty; - var prefix = "~"; - function Events() { - } - if (Object.create) { - Events.prototype = /* @__PURE__ */ Object.create(null); - if (!new Events().__proto__) - prefix = false; - } - function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; - } - function addListener(emitter, event, fn, context, once) { - if (typeof fn !== "function") { - throw new TypeError("The listener must be a function"); - } - var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; - if (!emitter._events[evt]) - emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) - emitter._events[evt].push(listener); - else - emitter._events[evt] = [emitter._events[evt], listener]; - return emitter; - } - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) - emitter._events = new Events(); - else - delete emitter._events[evt]; - } - function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; - } - EventEmitter.prototype.eventNames = function eventNames() { - var names = [], events, name; - if (this._eventsCount === 0) - return names; - for (name in events = this._events) { - if (has2.call(events, name)) - names.push(prefix ? name.slice(1) : name); - } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - return names; - }; - EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event, handlers = this._events[evt]; - if (!handlers) - return []; - if (handlers.fn) - return [handlers.fn]; - for (var i3 = 0, l4 = handlers.length, ee = new Array(l4); i3 < l4; i3++) { - ee[i3] = handlers[i3].fn; - } - return ee; - }; - EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event, listeners = this._events[evt]; - if (!listeners) - return 0; - if (listeners.fn) - return 1; - return listeners.length; - }; - EventEmitter.prototype.emit = function emit(event, a1, a22, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) - return false; - var listeners = this._events[evt], len = arguments.length, args, i3; - if (listeners.fn) { - if (listeners.once) - this.removeListener(event, listeners.fn, void 0, true); - switch (len) { - case 1: - return listeners.fn.call(listeners.context), true; - case 2: - return listeners.fn.call(listeners.context, a1), true; - case 3: - return listeners.fn.call(listeners.context, a1, a22), true; - case 4: - return listeners.fn.call(listeners.context, a1, a22, a3), true; - case 5: - return listeners.fn.call(listeners.context, a1, a22, a3, a4), true; - case 6: - return listeners.fn.call(listeners.context, a1, a22, a3, a4, a5), true; - } - for (i3 = 1, args = new Array(len - 1); i3 < len; i3++) { - args[i3 - 1] = arguments[i3]; - } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length, j3; - for (i3 = 0; i3 < length; i3++) { - if (listeners[i3].once) - this.removeListener(event, listeners[i3].fn, void 0, true); - switch (len) { - case 1: - listeners[i3].fn.call(listeners[i3].context); - break; - case 2: - listeners[i3].fn.call(listeners[i3].context, a1); - break; - case 3: - listeners[i3].fn.call(listeners[i3].context, a1, a22); - break; - case 4: - listeners[i3].fn.call(listeners[i3].context, a1, a22, a3); - break; - default: - if (!args) - for (j3 = 1, args = new Array(len - 1); j3 < len; j3++) { - args[j3 - 1] = arguments[j3]; - } - listeners[i3].fn.apply(listeners[i3].context, args); - } - } - } - return true; - }; - EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); - }; - EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); - }; - EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) - return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - var listeners = this._events[evt]; - if (listeners.fn) { - if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { - clearEvent(this, evt); - } - } else { - for (var i3 = 0, events = [], length = listeners.length; i3 < length; i3++) { - if (listeners[i3].fn !== fn || once && !listeners[i3].once || context && listeners[i3].context !== context) { - events.push(listeners[i3]); - } - } - if (events.length) - this._events[evt] = events.length === 1 ? events[0] : events; - else - clearEvent(this, evt); - } - return this; - }; - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) - clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - return this; - }; - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - EventEmitter.prefixed = prefix; - EventEmitter.EventEmitter = EventEmitter; - if ("undefined" !== typeof module2) { - module2.exports = EventEmitter; - } - } -}); - -// node_modules/p-finally/index.js -var require_p_finally = __commonJS({ - "node_modules/p-finally/index.js"(exports, module2) { - "use strict"; - module2.exports = (promise, onFinally) => { - onFinally = onFinally || (() => { - }); - return promise.then( - (val2) => new Promise((resolve) => { - resolve(onFinally()); - }).then(() => val2), - (err) => new Promise((resolve) => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); - }; - } -}); - -// node_modules/p-timeout/index.js -var require_p_timeout = __commonJS({ - "node_modules/p-timeout/index.js"(exports, module2) { - "use strict"; - var pFinally = require_p_finally(); - var TimeoutError = class extends Error { - constructor(message) { - super(message); - this.name = "TimeoutError"; - } - }; - var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== "number" || milliseconds < 0) { - throw new TypeError("Expected `milliseconds` to be a positive number"); - } - if (milliseconds === Infinity) { - resolve(promise); - return; - } - const timer = setTimeout(() => { - if (typeof fallback === "function") { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } - return; - } - const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); - if (typeof promise.cancel === "function") { - promise.cancel(); - } - reject(timeoutError); - }, milliseconds); - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); - }); - module2.exports = pTimeout; - module2.exports.default = pTimeout; - module2.exports.TimeoutError = TimeoutError; - } -}); - -// node_modules/p-queue/dist/lower-bound.js -var require_lower_bound = __commonJS({ - "node_modules/p-queue/dist/lower-bound.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - function lowerBound(array, value, comparator) { - let first = 0; - let count5 = array.length; - while (count5 > 0) { - const step = count5 / 2 | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count5 -= step + 1; - } else { - count5 = step; - } - } - return first; - } - exports.default = lowerBound; - } -}); - -// node_modules/p-queue/dist/priority-queue.js -var require_priority_queue = __commonJS({ - "node_modules/p-queue/dist/priority-queue.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var lower_bound_1 = require_lower_bound(); - var PriorityQueue = class { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index2 = lower_bound_1.default(this._queue, element, (a3, b3) => b3.priority - a3.priority); - this._queue.splice(index2, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } - }; - exports.default = PriorityQueue; - } -}); - -// node_modules/p-queue/dist/index.js -var require_dist = __commonJS({ - "node_modules/p-queue/dist/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var EventEmitter = require_eventemitter3(); - var p_timeout_1 = require_p_timeout(); - var priority_queue_1 = require_priority_queue(); - var empty = () => { - }; - var timeoutError = new p_timeout_1.TimeoutError(); - var PQueue = class extends EventEmitter { - constructor(options) { - var _a5, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a5 = options.intervalCap) === null || _a5 === void 0 ? void 0 : _a5.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); - } - if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; - } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; - } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit("next"); - } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit("idle"); - } - } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = void 0; - } - _isIntervalPaused() { - const now3 = Date.now(); - if (this._intervalId === void 0) { - const delay = this._intervalEnd - now3; - if (delay < 0) { - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - } else { - if (this._timeoutId === void 0) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = void 0; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit("active"); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; - } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== void 0) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = void 0; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - while (this._tryToStartAnother()) { - } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => { - if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return void 0; - }); - resolve(await operation); - } catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit("add"); - }); - } - /** - Same as `.add()`, but accepts an array of sync or async functions. - - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; - } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); - } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. - - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - if (this._queue.size === 0) { - return; - } - return new Promise((resolve) => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - if (this._pendingCount === 0 && this._queue.size === 0) { - return; - } - return new Promise((resolve) => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. - - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; - } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; - } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; - } - }; - exports.default = PQueue; - } -}); - -// node_modules/langsmith/dist/singletons/fetch.js -var DEFAULT_FETCH_IMPLEMENTATION, LANGSMITH_FETCH_IMPLEMENTATION_KEY, _getFetchImplementation; -var init_fetch = __esm({ - "node_modules/langsmith/dist/singletons/fetch.js"() { - DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); - LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); - _getFetchImplementation = () => { - return globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION; - }; - } -}); - -// node_modules/langsmith/dist/utils/async_caller.js -var import_p_retry, import_p_queue, STATUS_NO_RETRY, STATUS_IGNORE, AsyncCaller; -var init_async_caller = __esm({ - "node_modules/langsmith/dist/utils/async_caller.js"() { - import_p_retry = __toESM(require_p_retry(), 1); - import_p_queue = __toESM(require_dist(), 1); - init_fetch(); - STATUS_NO_RETRY = [ - 400, - // Bad Request - 401, - // Unauthorized - 403, - // Forbidden - 404, - // Not Found - 405, - // Method Not Allowed - 406, - // Not Acceptable - 407, - // Proxy Authentication Required - 408 - // Request Timeout - ]; - STATUS_IGNORE = [ - 409 - // Conflict - ]; - AsyncCaller = class { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedResponseHook", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - if ("default" in import_p_queue.default) { - this.queue = new import_p_queue.default.default({ - concurrency: this.maxConcurrency - }); - } else { - this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency }); - } - this.onFailedResponseHook = params?.onFailedResponseHook; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - const onFailedResponseHook = this.onFailedResponseHook; - return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => { - if (error instanceof Error) { - throw error; - } else { - throw new Error(error); - } - }), { - async onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) { - throw error; - } - if (error?.code === "ECONNABORTED") { - throw error; - } - const response = error?.response; - const status = response?.status; - if (status) { - if (STATUS_NO_RETRY.includes(+status)) { - throw error; - } else if (STATUS_IGNORE.includes(+status)) { - return; - } - if (onFailedResponseHook) { - await onFailedResponseHook(response); - } - } - }, - // If needed we can change some of the defaults here, - // but they're quite sensible. - retries: this.maxRetries, - randomize: true - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_2, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }) - ]); - } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => _getFetchImplementation()(...args).then((res) => res.ok ? res : Promise.reject(res))); - } - }; - } -}); - -// node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage(message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content } - }; - if (message?.additional_kwargs && Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; -} -var init_messages = __esm({ - "node_modules/langsmith/dist/utils/messages.js"() { - } -}); - -// node_modules/langsmith/dist/utils/_uuid.js -function assertUuid(str2, which) { - if (!validate_default2(str2)) { - const msg = which !== void 0 ? `Invalid UUID for ${which}: ${str2}` : `Invalid UUID: ${str2}`; - throw new Error(msg); - } - return str2; -} -var init_uuid = __esm({ - "node_modules/langsmith/dist/utils/_uuid.js"() { - init_esm_browser2(); - } -}); - -// node_modules/langsmith/dist/utils/warn.js -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; - } -} -var warnedMessages; -var init_warn = __esm({ - "node_modules/langsmith/dist/utils/warn.js"() { - warnedMessages = {}; - } -}); - -// node_modules/semver/internal/constants.js -var require_constants = __commonJS({ - "node_modules/semver/internal/constants.js"(exports, module2) { - var SEMVER_SPEC_VERSION = "2.0.0"; - var MAX_LENGTH = 256; - var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ - 9007199254740991; - var MAX_SAFE_COMPONENT_LENGTH = 16; - var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; - var RELEASE_TYPES = [ - "major", - "premajor", - "minor", - "preminor", - "patch", - "prepatch", - "prerelease" - ]; - module2.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 1, - FLAG_LOOSE: 2 - }; - } -}); - -// node_modules/semver/internal/debug.js -var require_debug = __commonJS({ - "node_modules/semver/internal/debug.js"(exports, module2) { - var debug4 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { - }; - module2.exports = debug4; - } -}); - -// node_modules/semver/internal/re.js -var require_re = __commonJS({ - "node_modules/semver/internal/re.js"(exports, module2) { - var { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH - } = require_constants(); - var debug4 = require_debug(); - exports = module2.exports = {}; - var re = exports.re = []; - var safeRe = exports.safeRe = []; - var src = exports.src = []; - var t3 = exports.t = {}; - var R = 0; - var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; - var safeRegexReplacements = [ - ["\\s", 1], - ["\\d", MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] - ]; - var makeSafeRegex = (value) => { - for (const [token, max2] of safeRegexReplacements) { - value = value.split(`${token}*`).join(`${token}{0,${max2}}`).split(`${token}+`).join(`${token}{1,${max2}}`); - } - return value; - }; - var createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value); - const index2 = R++; - debug4(name, index2, value); - t3[name] = index2; - src[index2] = value; - re[index2] = new RegExp(value, isGlobal ? "g" : void 0); - safeRe[index2] = new RegExp(safe, isGlobal ? "g" : void 0); - }; - createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); - createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); - createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); - createToken("MAINVERSION", `(${src[t3.NUMERICIDENTIFIER]})\\.(${src[t3.NUMERICIDENTIFIER]})\\.(${src[t3.NUMERICIDENTIFIER]})`); - createToken("MAINVERSIONLOOSE", `(${src[t3.NUMERICIDENTIFIERLOOSE]})\\.(${src[t3.NUMERICIDENTIFIERLOOSE]})\\.(${src[t3.NUMERICIDENTIFIERLOOSE]})`); - createToken("PRERELEASEIDENTIFIER", `(?:${src[t3.NUMERICIDENTIFIER]}|${src[t3.NONNUMERICIDENTIFIER]})`); - createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t3.NUMERICIDENTIFIERLOOSE]}|${src[t3.NONNUMERICIDENTIFIER]})`); - createToken("PRERELEASE", `(?:-(${src[t3.PRERELEASEIDENTIFIER]}(?:\\.${src[t3.PRERELEASEIDENTIFIER]})*))`); - createToken("PRERELEASELOOSE", `(?:-?(${src[t3.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t3.PRERELEASEIDENTIFIERLOOSE]})*))`); - createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); - createToken("BUILD", `(?:\\+(${src[t3.BUILDIDENTIFIER]}(?:\\.${src[t3.BUILDIDENTIFIER]})*))`); - createToken("FULLPLAIN", `v?${src[t3.MAINVERSION]}${src[t3.PRERELEASE]}?${src[t3.BUILD]}?`); - createToken("FULL", `^${src[t3.FULLPLAIN]}$`); - createToken("LOOSEPLAIN", `[v=\\s]*${src[t3.MAINVERSIONLOOSE]}${src[t3.PRERELEASELOOSE]}?${src[t3.BUILD]}?`); - createToken("LOOSE", `^${src[t3.LOOSEPLAIN]}$`); - createToken("GTLT", "((?:<|>)?=?)"); - createToken("XRANGEIDENTIFIERLOOSE", `${src[t3.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); - createToken("XRANGEIDENTIFIER", `${src[t3.NUMERICIDENTIFIER]}|x|X|\\*`); - createToken("XRANGEPLAIN", `[v=\\s]*(${src[t3.XRANGEIDENTIFIER]})(?:\\.(${src[t3.XRANGEIDENTIFIER]})(?:\\.(${src[t3.XRANGEIDENTIFIER]})(?:${src[t3.PRERELEASE]})?${src[t3.BUILD]}?)?)?`); - createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t3.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t3.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t3.XRANGEIDENTIFIERLOOSE]})(?:${src[t3.PRERELEASELOOSE]})?${src[t3.BUILD]}?)?)?`); - createToken("XRANGE", `^${src[t3.GTLT]}\\s*${src[t3.XRANGEPLAIN]}$`); - createToken("XRANGELOOSE", `^${src[t3.GTLT]}\\s*${src[t3.XRANGEPLAINLOOSE]}$`); - createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); - createToken("COERCE", `${src[t3.COERCEPLAIN]}(?:$|[^\\d])`); - createToken("COERCEFULL", src[t3.COERCEPLAIN] + `(?:${src[t3.PRERELEASE]})?(?:${src[t3.BUILD]})?(?:$|[^\\d])`); - createToken("COERCERTL", src[t3.COERCE], true); - createToken("COERCERTLFULL", src[t3.COERCEFULL], true); - createToken("LONETILDE", "(?:~>?)"); - createToken("TILDETRIM", `(\\s*)${src[t3.LONETILDE]}\\s+`, true); - exports.tildeTrimReplace = "$1~"; - createToken("TILDE", `^${src[t3.LONETILDE]}${src[t3.XRANGEPLAIN]}$`); - createToken("TILDELOOSE", `^${src[t3.LONETILDE]}${src[t3.XRANGEPLAINLOOSE]}$`); - createToken("LONECARET", "(?:\\^)"); - createToken("CARETTRIM", `(\\s*)${src[t3.LONECARET]}\\s+`, true); - exports.caretTrimReplace = "$1^"; - createToken("CARET", `^${src[t3.LONECARET]}${src[t3.XRANGEPLAIN]}$`); - createToken("CARETLOOSE", `^${src[t3.LONECARET]}${src[t3.XRANGEPLAINLOOSE]}$`); - createToken("COMPARATORLOOSE", `^${src[t3.GTLT]}\\s*(${src[t3.LOOSEPLAIN]})$|^$`); - createToken("COMPARATOR", `^${src[t3.GTLT]}\\s*(${src[t3.FULLPLAIN]})$|^$`); - createToken("COMPARATORTRIM", `(\\s*)${src[t3.GTLT]}\\s*(${src[t3.LOOSEPLAIN]}|${src[t3.XRANGEPLAIN]})`, true); - exports.comparatorTrimReplace = "$1$2$3"; - createToken("HYPHENRANGE", `^\\s*(${src[t3.XRANGEPLAIN]})\\s+-\\s+(${src[t3.XRANGEPLAIN]})\\s*$`); - createToken("HYPHENRANGELOOSE", `^\\s*(${src[t3.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t3.XRANGEPLAINLOOSE]})\\s*$`); - createToken("STAR", "(<|>)?=?\\s*\\*"); - createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); - createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); - } -}); - -// node_modules/semver/internal/parse-options.js -var require_parse_options = __commonJS({ - "node_modules/semver/internal/parse-options.js"(exports, module2) { - var looseOption = Object.freeze({ loose: true }); - var emptyOpts = Object.freeze({}); - var parseOptions = (options) => { - if (!options) { - return emptyOpts; - } - if (typeof options !== "object") { - return looseOption; - } - return options; - }; - module2.exports = parseOptions; - } -}); - -// node_modules/semver/internal/identifiers.js -var require_identifiers = __commonJS({ - "node_modules/semver/internal/identifiers.js"(exports, module2) { - var numeric = /^[0-9]+$/; - var compareIdentifiers = (a3, b3) => { - const anum = numeric.test(a3); - const bnum = numeric.test(b3); - if (anum && bnum) { - a3 = +a3; - b3 = +b3; - } - return a3 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a3 < b3 ? -1 : 1; - }; - var rcompareIdentifiers = (a3, b3) => compareIdentifiers(b3, a3); - module2.exports = { - compareIdentifiers, - rcompareIdentifiers - }; - } -}); - -// node_modules/semver/classes/semver.js -var require_semver = __commonJS({ - "node_modules/semver/classes/semver.js"(exports, module2) { - var debug4 = require_debug(); - var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); - var { safeRe: re, t: t3 } = require_re(); - var parseOptions = require_parse_options(); - var { compareIdentifiers } = require_identifiers(); - var SemVer = class { - constructor(version2, options) { - options = parseOptions(options); - if (version2 instanceof SemVer) { - if (version2.loose === !!options.loose && version2.includePrerelease === !!options.includePrerelease) { - return version2; - } else { - version2 = version2.version; - } - } else if (typeof version2 !== "string") { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`); - } - if (version2.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ); - } - debug4("SemVer", version2, options); - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - const m3 = version2.trim().match(options.loose ? re[t3.LOOSE] : re[t3.FULL]); - if (!m3) { - throw new TypeError(`Invalid Version: ${version2}`); - } - this.raw = version2; - this.major = +m3[1]; - this.minor = +m3[2]; - this.patch = +m3[3]; - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError("Invalid major version"); - } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError("Invalid minor version"); - } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError("Invalid patch version"); - } - if (!m3[4]) { - this.prerelease = []; - } else { - this.prerelease = m3[4].split(".").map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num; - } - } - return id; - }); - } - this.build = m3[5] ? m3[5].split(".") : []; - this.format(); - } - format() { - this.version = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease.length) { - this.version += `-${this.prerelease.join(".")}`; - } - return this.version; - } - toString() { - return this.version; - } - compare(other) { - debug4("SemVer.compare", this.version, this.options, other); - if (!(other instanceof SemVer)) { - if (typeof other === "string" && other === this.version) { - return 0; - } - other = new SemVer(other, this.options); - } - if (other.version === this.version) { - return 0; - } - return this.compareMain(other) || this.comparePre(other); - } - compareMain(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); - } - comparePre(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - if (this.prerelease.length && !other.prerelease.length) { - return -1; - } else if (!this.prerelease.length && other.prerelease.length) { - return 1; - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0; - } - let i3 = 0; - do { - const a3 = this.prerelease[i3]; - const b3 = other.prerelease[i3]; - debug4("prerelease compare", i3, a3, b3); - if (a3 === void 0 && b3 === void 0) { - return 0; - } else if (b3 === void 0) { - return 1; - } else if (a3 === void 0) { - return -1; - } else if (a3 === b3) { - continue; - } else { - return compareIdentifiers(a3, b3); - } - } while (++i3); - } - compareBuild(other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options); - } - let i3 = 0; - do { - const a3 = this.build[i3]; - const b3 = other.build[i3]; - debug4("build compare", i3, a3, b3); - if (a3 === void 0 && b3 === void 0) { - return 0; - } else if (b3 === void 0) { - return 1; - } else if (a3 === void 0) { - return -1; - } else if (a3 === b3) { - continue; - } else { - return compareIdentifiers(a3, b3); - } - } while (++i3); - } - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc(release, identifier, identifierBase) { - switch (release) { - case "premajor": - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc("pre", identifier, identifierBase); - break; - case "preminor": - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc("pre", identifier, identifierBase); - break; - case "prepatch": - this.prerelease.length = 0; - this.inc("patch", identifier, identifierBase); - this.inc("pre", identifier, identifierBase); - break; - case "prerelease": - if (this.prerelease.length === 0) { - this.inc("patch", identifier, identifierBase); - } - this.inc("pre", identifier, identifierBase); - break; - case "major": - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { - this.major++; - } - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case "minor": - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++; - } - this.patch = 0; - this.prerelease = []; - break; - case "patch": - if (this.prerelease.length === 0) { - this.patch++; - } - this.prerelease = []; - break; - case "pre": { - const base = Number(identifierBase) ? 1 : 0; - if (!identifier && identifierBase === false) { - throw new Error("invalid increment argument: identifier is empty"); - } - if (this.prerelease.length === 0) { - this.prerelease = [base]; - } else { - let i3 = this.prerelease.length; - while (--i3 >= 0) { - if (typeof this.prerelease[i3] === "number") { - this.prerelease[i3]++; - i3 = -2; - } - } - if (i3 === -1) { - if (identifier === this.prerelease.join(".") && identifierBase === false) { - throw new Error("invalid increment argument: identifier already exists"); - } - this.prerelease.push(base); - } - } - if (identifier) { - let prerelease = [identifier, base]; - if (identifierBase === false) { - prerelease = [identifier]; - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease; - } - } else { - this.prerelease = prerelease; - } - } - break; - } - default: - throw new Error(`invalid increment argument: ${release}`); - } - this.raw = this.format(); - if (this.build.length) { - this.raw += `+${this.build.join(".")}`; - } - return this; - } - }; - module2.exports = SemVer; - } -}); - -// node_modules/semver/functions/parse.js -var require_parse = __commonJS({ - "node_modules/semver/functions/parse.js"(exports, module2) { - var SemVer = require_semver(); - var parse6 = (version2, options, throwErrors = false) => { - if (version2 instanceof SemVer) { - return version2; - } - try { - return new SemVer(version2, options); - } catch (er) { - if (!throwErrors) { - return null; - } - throw er; - } - }; - module2.exports = parse6; - } -}); - -// node_modules/semver/functions/valid.js -var require_valid = __commonJS({ - "node_modules/semver/functions/valid.js"(exports, module2) { - var parse6 = require_parse(); - var valid = (version2, options) => { - const v5 = parse6(version2, options); - return v5 ? v5.version : null; - }; - module2.exports = valid; - } -}); - -// node_modules/semver/functions/clean.js -var require_clean = __commonJS({ - "node_modules/semver/functions/clean.js"(exports, module2) { - var parse6 = require_parse(); - var clean = (version2, options) => { - const s4 = parse6(version2.trim().replace(/^[=v]+/, ""), options); - return s4 ? s4.version : null; - }; - module2.exports = clean; - } -}); - -// node_modules/semver/functions/inc.js -var require_inc = __commonJS({ - "node_modules/semver/functions/inc.js"(exports, module2) { - var SemVer = require_semver(); - var inc = (version2, release, options, identifier, identifierBase) => { - if (typeof options === "string") { - identifierBase = identifier; - identifier = options; - options = void 0; - } - try { - return new SemVer( - version2 instanceof SemVer ? version2.version : version2, - options - ).inc(release, identifier, identifierBase).version; - } catch (er) { - return null; - } - }; - module2.exports = inc; - } -}); - -// node_modules/semver/functions/diff.js -var require_diff = __commonJS({ - "node_modules/semver/functions/diff.js"(exports, module2) { - var parse6 = require_parse(); - var diff = (version1, version2) => { - const v1 = parse6(version1, null, true); - const v22 = parse6(version2, null, true); - const comparison = v1.compare(v22); - if (comparison === 0) { - return null; - } - const v1Higher = comparison > 0; - const highVersion = v1Higher ? v1 : v22; - const lowVersion = v1Higher ? v22 : v1; - const highHasPre = !!highVersion.prerelease.length; - const lowHasPre = !!lowVersion.prerelease.length; - if (lowHasPre && !highHasPre) { - if (!lowVersion.patch && !lowVersion.minor) { - return "major"; - } - if (highVersion.patch) { - return "patch"; - } - if (highVersion.minor) { - return "minor"; - } - return "major"; - } - const prefix = highHasPre ? "pre" : ""; - if (v1.major !== v22.major) { - return prefix + "major"; - } - if (v1.minor !== v22.minor) { - return prefix + "minor"; - } - if (v1.patch !== v22.patch) { - return prefix + "patch"; - } - return "prerelease"; - }; - module2.exports = diff; - } -}); - -// node_modules/semver/functions/major.js -var require_major = __commonJS({ - "node_modules/semver/functions/major.js"(exports, module2) { - var SemVer = require_semver(); - var major = (a3, loose) => new SemVer(a3, loose).major; - module2.exports = major; - } -}); - -// node_modules/semver/functions/minor.js -var require_minor = __commonJS({ - "node_modules/semver/functions/minor.js"(exports, module2) { - var SemVer = require_semver(); - var minor = (a3, loose) => new SemVer(a3, loose).minor; - module2.exports = minor; - } -}); - -// node_modules/semver/functions/patch.js -var require_patch = __commonJS({ - "node_modules/semver/functions/patch.js"(exports, module2) { - var SemVer = require_semver(); - var patch = (a3, loose) => new SemVer(a3, loose).patch; - module2.exports = patch; - } -}); - -// node_modules/semver/functions/prerelease.js -var require_prerelease = __commonJS({ - "node_modules/semver/functions/prerelease.js"(exports, module2) { - var parse6 = require_parse(); - var prerelease = (version2, options) => { - const parsed = parse6(version2, options); - return parsed && parsed.prerelease.length ? parsed.prerelease : null; - }; - module2.exports = prerelease; - } -}); - -// node_modules/semver/functions/compare.js -var require_compare = __commonJS({ - "node_modules/semver/functions/compare.js"(exports, module2) { - var SemVer = require_semver(); - var compare2 = (a3, b3, loose) => new SemVer(a3, loose).compare(new SemVer(b3, loose)); - module2.exports = compare2; - } -}); - -// node_modules/semver/functions/rcompare.js -var require_rcompare = __commonJS({ - "node_modules/semver/functions/rcompare.js"(exports, module2) { - var compare2 = require_compare(); - var rcompare = (a3, b3, loose) => compare2(b3, a3, loose); - module2.exports = rcompare; - } -}); - -// node_modules/semver/functions/compare-loose.js -var require_compare_loose = __commonJS({ - "node_modules/semver/functions/compare-loose.js"(exports, module2) { - var compare2 = require_compare(); - var compareLoose = (a3, b3) => compare2(a3, b3, true); - module2.exports = compareLoose; - } -}); - -// node_modules/semver/functions/compare-build.js -var require_compare_build = __commonJS({ - "node_modules/semver/functions/compare-build.js"(exports, module2) { - var SemVer = require_semver(); - var compareBuild = (a3, b3, loose) => { - const versionA = new SemVer(a3, loose); - const versionB = new SemVer(b3, loose); - return versionA.compare(versionB) || versionA.compareBuild(versionB); - }; - module2.exports = compareBuild; - } -}); - -// node_modules/semver/functions/sort.js -var require_sort = __commonJS({ - "node_modules/semver/functions/sort.js"(exports, module2) { - var compareBuild = require_compare_build(); - var sort = (list, loose) => list.sort((a3, b3) => compareBuild(a3, b3, loose)); - module2.exports = sort; - } -}); - -// node_modules/semver/functions/rsort.js -var require_rsort = __commonJS({ - "node_modules/semver/functions/rsort.js"(exports, module2) { - var compareBuild = require_compare_build(); - var rsort = (list, loose) => list.sort((a3, b3) => compareBuild(b3, a3, loose)); - module2.exports = rsort; - } -}); - -// node_modules/semver/functions/gt.js -var require_gt = __commonJS({ - "node_modules/semver/functions/gt.js"(exports, module2) { - var compare2 = require_compare(); - var gt = (a3, b3, loose) => compare2(a3, b3, loose) > 0; - module2.exports = gt; - } -}); - -// node_modules/semver/functions/lt.js -var require_lt = __commonJS({ - "node_modules/semver/functions/lt.js"(exports, module2) { - var compare2 = require_compare(); - var lt = (a3, b3, loose) => compare2(a3, b3, loose) < 0; - module2.exports = lt; - } -}); - -// node_modules/semver/functions/eq.js -var require_eq = __commonJS({ - "node_modules/semver/functions/eq.js"(exports, module2) { - var compare2 = require_compare(); - var eq = (a3, b3, loose) => compare2(a3, b3, loose) === 0; - module2.exports = eq; - } -}); - -// node_modules/semver/functions/neq.js -var require_neq = __commonJS({ - "node_modules/semver/functions/neq.js"(exports, module2) { - var compare2 = require_compare(); - var neq = (a3, b3, loose) => compare2(a3, b3, loose) !== 0; - module2.exports = neq; - } -}); - -// node_modules/semver/functions/gte.js -var require_gte = __commonJS({ - "node_modules/semver/functions/gte.js"(exports, module2) { - var compare2 = require_compare(); - var gte = (a3, b3, loose) => compare2(a3, b3, loose) >= 0; - module2.exports = gte; - } -}); - -// node_modules/semver/functions/lte.js -var require_lte = __commonJS({ - "node_modules/semver/functions/lte.js"(exports, module2) { - var compare2 = require_compare(); - var lte = (a3, b3, loose) => compare2(a3, b3, loose) <= 0; - module2.exports = lte; - } -}); - -// node_modules/semver/functions/cmp.js -var require_cmp = __commonJS({ - "node_modules/semver/functions/cmp.js"(exports, module2) { - var eq = require_eq(); - var neq = require_neq(); - var gt = require_gt(); - var gte = require_gte(); - var lt = require_lt(); - var lte = require_lte(); - var cmp = (a3, op, b3, loose) => { - switch (op) { - case "===": - if (typeof a3 === "object") { - a3 = a3.version; - } - if (typeof b3 === "object") { - b3 = b3.version; - } - return a3 === b3; - case "!==": - if (typeof a3 === "object") { - a3 = a3.version; - } - if (typeof b3 === "object") { - b3 = b3.version; - } - return a3 !== b3; - case "": - case "=": - case "==": - return eq(a3, b3, loose); - case "!=": - return neq(a3, b3, loose); - case ">": - return gt(a3, b3, loose); - case ">=": - return gte(a3, b3, loose); - case "<": - return lt(a3, b3, loose); - case "<=": - return lte(a3, b3, loose); - default: - throw new TypeError(`Invalid operator: ${op}`); - } - }; - module2.exports = cmp; - } -}); - -// node_modules/semver/functions/coerce.js -var require_coerce = __commonJS({ - "node_modules/semver/functions/coerce.js"(exports, module2) { - var SemVer = require_semver(); - var parse6 = require_parse(); - var { safeRe: re, t: t3 } = require_re(); - var coerce2 = (version2, options) => { - if (version2 instanceof SemVer) { - return version2; - } - if (typeof version2 === "number") { - version2 = String(version2); - } - if (typeof version2 !== "string") { - return null; - } - options = options || {}; - let match2 = null; - if (!options.rtl) { - match2 = version2.match(options.includePrerelease ? re[t3.COERCEFULL] : re[t3.COERCE]); - } else { - const coerceRtlRegex = options.includePrerelease ? re[t3.COERCERTLFULL] : re[t3.COERCERTL]; - let next; - while ((next = coerceRtlRegex.exec(version2)) && (!match2 || match2.index + match2[0].length !== version2.length)) { - if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) { - match2 = next; - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; - } - coerceRtlRegex.lastIndex = -1; - } - if (match2 === null) { - return null; - } - const major = match2[2]; - const minor = match2[3] || "0"; - const patch = match2[4] || "0"; - const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : ""; - const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : ""; - return parse6(`${major}.${minor}.${patch}${prerelease}${build}`, options); - }; - module2.exports = coerce2; - } -}); - -// node_modules/semver/internal/lrucache.js -var require_lrucache = __commonJS({ - "node_modules/semver/internal/lrucache.js"(exports, module2) { - var LRUCache = class { - constructor() { - this.max = 1e3; - this.map = /* @__PURE__ */ new Map(); - } - get(key) { - const value = this.map.get(key); - if (value === void 0) { - return void 0; - } else { - this.map.delete(key); - this.map.set(key, value); - return value; - } - } - delete(key) { - return this.map.delete(key); - } - set(key, value) { - const deleted = this.delete(key); - if (!deleted && value !== void 0) { - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value; - this.delete(firstKey); - } - this.map.set(key, value); - } - return this; - } - }; - module2.exports = LRUCache; - } -}); - -// node_modules/semver/classes/range.js -var require_range = __commonJS({ - "node_modules/semver/classes/range.js"(exports, module2) { - var SPACE_CHARACTERS = /\s+/g; - var Range2 = class { - constructor(range, options) { - options = parseOptions(options); - if (range instanceof Range2) { - if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { - return range; - } else { - return new Range2(range.raw, options); - } - } - if (range instanceof Comparator) { - this.raw = range.value; - this.set = [[range]]; - this.formatted = void 0; - return this; - } - this.options = options; - this.loose = !!options.loose; - this.includePrerelease = !!options.includePrerelease; - this.raw = range.trim().replace(SPACE_CHARACTERS, " "); - this.set = this.raw.split("||").map((r4) => this.parseRange(r4.trim())).filter((c4) => c4.length); - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`); - } - if (this.set.length > 1) { - const first = this.set[0]; - this.set = this.set.filter((c4) => !isNullSet(c4[0])); - if (this.set.length === 0) { - this.set = [first]; - } else if (this.set.length > 1) { - for (const c4 of this.set) { - if (c4.length === 1 && isAny2(c4[0])) { - this.set = [c4]; - break; - } - } - } - } - this.formatted = void 0; - } - get range() { - if (this.formatted === void 0) { - this.formatted = ""; - for (let i3 = 0; i3 < this.set.length; i3++) { - if (i3 > 0) { - this.formatted += "||"; - } - const comps = this.set[i3]; - for (let k3 = 0; k3 < comps.length; k3++) { - if (k3 > 0) { - this.formatted += " "; - } - this.formatted += comps[k3].toString().trim(); - } - } - } - return this.formatted; - } - format() { - return this.range; - } - toString() { - return this.range; - } - parseRange(range) { - const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); - const memoKey = memoOpts + ":" + range; - const cached = cache2.get(memoKey); - if (cached) { - return cached; - } - const loose = this.options.loose; - const hr = loose ? re[t3.HYPHENRANGELOOSE] : re[t3.HYPHENRANGE]; - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug4("hyphen replace", range); - range = range.replace(re[t3.COMPARATORTRIM], comparatorTrimReplace); - debug4("comparator trim", range); - range = range.replace(re[t3.TILDETRIM], tildeTrimReplace); - debug4("tilde trim", range); - range = range.replace(re[t3.CARETTRIM], caretTrimReplace); - debug4("caret trim", range); - let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); - if (loose) { - rangeList = rangeList.filter((comp) => { - debug4("loose invalid filter", comp, this.options); - return !!comp.match(re[t3.COMPARATORLOOSE]); - }); - } - debug4("range list", rangeList); - const rangeMap = /* @__PURE__ */ new Map(); - const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp]; - } - rangeMap.set(comp.value, comp); - } - if (rangeMap.size > 1 && rangeMap.has("")) { - rangeMap.delete(""); - } - const result = [...rangeMap.values()]; - cache2.set(memoKey, result); - return result; - } - intersects(range, options) { - if (!(range instanceof Range2)) { - throw new TypeError("a Range is required"); - } - return this.set.some((thisComparators) => { - return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { - return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options); - }); - }); - }); - }); - } - // if ANY of the sets match ALL of its comparators, then pass - test(version2) { - if (!version2) { - return false; - } - if (typeof version2 === "string") { - try { - version2 = new SemVer(version2, this.options); - } catch (er) { - return false; - } - } - for (let i3 = 0; i3 < this.set.length; i3++) { - if (testSet(this.set[i3], version2, this.options)) { - return true; - } - } - return false; - } - }; - module2.exports = Range2; - var LRU = require_lrucache(); - var cache2 = new LRU(); - var parseOptions = require_parse_options(); - var Comparator = require_comparator(); - var debug4 = require_debug(); - var SemVer = require_semver(); - var { - safeRe: re, - t: t3, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace - } = require_re(); - var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); - var isNullSet = (c4) => c4.value === "<0.0.0-0"; - var isAny2 = (c4) => c4.value === ""; - var isSatisfiable = (comparators, options) => { - let result = true; - const remainingComparators = comparators.slice(); - let testComparator = remainingComparators.pop(); - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options); - }); - testComparator = remainingComparators.pop(); - } - return result; - }; - var parseComparator = (comp, options) => { - debug4("comp", comp, options); - comp = replaceCarets(comp, options); - debug4("caret", comp); - comp = replaceTildes(comp, options); - debug4("tildes", comp); - comp = replaceXRanges(comp, options); - debug4("xrange", comp); - comp = replaceStars(comp, options); - debug4("stars", comp); - return comp; - }; - var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; - var replaceTildes = (comp, options) => { - return comp.trim().split(/\s+/).map((c4) => replaceTilde(c4, options)).join(" "); - }; - var replaceTilde = (comp, options) => { - const r4 = options.loose ? re[t3.TILDELOOSE] : re[t3.TILDE]; - return comp.replace(r4, (_2, M, m3, p3, pr) => { - debug4("tilde", comp, _2, M, m3, p3, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m3)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; - } else if (isX(p3)) { - ret = `>=${M}.${m3}.0 <${M}.${+m3 + 1}.0-0`; - } else if (pr) { - debug4("replaceTilde pr", pr); - ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${+m3 + 1}.0-0`; - } else { - ret = `>=${M}.${m3}.${p3} <${M}.${+m3 + 1}.0-0`; - } - debug4("tilde return", ret); - return ret; - }); - }; - var replaceCarets = (comp, options) => { - return comp.trim().split(/\s+/).map((c4) => replaceCaret(c4, options)).join(" "); - }; - var replaceCaret = (comp, options) => { - debug4("caret", comp, options); - const r4 = options.loose ? re[t3.CARETLOOSE] : re[t3.CARET]; - const z3 = options.includePrerelease ? "-0" : ""; - return comp.replace(r4, (_2, M, m3, p3, pr) => { - debug4("caret", comp, _2, M, m3, p3, pr); - let ret; - if (isX(M)) { - ret = ""; - } else if (isX(m3)) { - ret = `>=${M}.0.0${z3} <${+M + 1}.0.0-0`; - } else if (isX(p3)) { - if (M === "0") { - ret = `>=${M}.${m3}.0${z3} <${M}.${+m3 + 1}.0-0`; - } else { - ret = `>=${M}.${m3}.0${z3} <${+M + 1}.0.0-0`; - } - } else if (pr) { - debug4("replaceCaret pr", pr); - if (M === "0") { - if (m3 === "0") { - ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${m3}.${+p3 + 1}-0`; - } else { - ret = `>=${M}.${m3}.${p3}-${pr} <${M}.${+m3 + 1}.0-0`; - } - } else { - ret = `>=${M}.${m3}.${p3}-${pr} <${+M + 1}.0.0-0`; - } - } else { - debug4("no pr"); - if (M === "0") { - if (m3 === "0") { - ret = `>=${M}.${m3}.${p3}${z3} <${M}.${m3}.${+p3 + 1}-0`; - } else { - ret = `>=${M}.${m3}.${p3}${z3} <${M}.${+m3 + 1}.0-0`; - } - } else { - ret = `>=${M}.${m3}.${p3} <${+M + 1}.0.0-0`; - } - } - debug4("caret return", ret); - return ret; - }); - }; - var replaceXRanges = (comp, options) => { - debug4("replaceXRanges", comp, options); - return comp.split(/\s+/).map((c4) => replaceXRange(c4, options)).join(" "); - }; - var replaceXRange = (comp, options) => { - comp = comp.trim(); - const r4 = options.loose ? re[t3.XRANGELOOSE] : re[t3.XRANGE]; - return comp.replace(r4, (ret, gtlt, M, m3, p3, pr) => { - debug4("xRange", comp, ret, gtlt, M, m3, p3, pr); - const xM = isX(M); - const xm = xM || isX(m3); - const xp = xm || isX(p3); - const anyX = xp; - if (gtlt === "=" && anyX) { - gtlt = ""; - } - pr = options.includePrerelease ? "-0" : ""; - if (xM) { - if (gtlt === ">" || gtlt === "<") { - ret = "<0.0.0-0"; - } else { - ret = "*"; - } - } else if (gtlt && anyX) { - if (xm) { - m3 = 0; - } - p3 = 0; - if (gtlt === ">") { - gtlt = ">="; - if (xm) { - M = +M + 1; - m3 = 0; - p3 = 0; - } else { - m3 = +m3 + 1; - p3 = 0; - } - } else if (gtlt === "<=") { - gtlt = "<"; - if (xm) { - M = +M + 1; - } else { - m3 = +m3 + 1; - } - } - if (gtlt === "<") { - pr = "-0"; - } - ret = `${gtlt + M}.${m3}.${p3}${pr}`; - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; - } else if (xp) { - ret = `>=${M}.${m3}.0${pr} <${M}.${+m3 + 1}.0-0`; - } - debug4("xRange return", ret); - return ret; - }); - }; - var replaceStars = (comp, options) => { - debug4("replaceStars", comp, options); - return comp.trim().replace(re[t3.STAR], ""); - }; - var replaceGTE0 = (comp, options) => { - debug4("replaceGTE0", comp, options); - return comp.trim().replace(re[options.includePrerelease ? t3.GTE0PRE : t3.GTE0], ""); - }; - var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = ""; - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? "-0" : ""}`; - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; - } else if (fpr) { - from = `>=${from}`; - } else { - from = `>=${from}${incPr ? "-0" : ""}`; - } - if (isX(tM)) { - to = ""; - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0`; - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0`; - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}`; - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0`; - } else { - to = `<=${to}`; - } - return `${from} ${to}`.trim(); - }; - var testSet = (set, version2, options) => { - for (let i3 = 0; i3 < set.length; i3++) { - if (!set[i3].test(version2)) { - return false; - } - } - if (version2.prerelease.length && !options.includePrerelease) { - for (let i3 = 0; i3 < set.length; i3++) { - debug4(set[i3].semver); - if (set[i3].semver === Comparator.ANY) { - continue; - } - if (set[i3].semver.prerelease.length > 0) { - const allowed = set[i3].semver; - if (allowed.major === version2.major && allowed.minor === version2.minor && allowed.patch === version2.patch) { - return true; - } - } - } - return false; - } - return true; - }; - } -}); - -// node_modules/semver/classes/comparator.js -var require_comparator = __commonJS({ - "node_modules/semver/classes/comparator.js"(exports, module2) { - var ANY = Symbol("SemVer ANY"); - var Comparator = class { - static get ANY() { - return ANY; - } - constructor(comp, options) { - options = parseOptions(options); - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp; - } else { - comp = comp.value; - } - } - comp = comp.trim().split(/\s+/).join(" "); - debug4("comparator", comp, options); - this.options = options; - this.loose = !!options.loose; - this.parse(comp); - if (this.semver === ANY) { - this.value = ""; - } else { - this.value = this.operator + this.semver.version; - } - debug4("comp", this); - } - parse(comp) { - const r4 = this.options.loose ? re[t3.COMPARATORLOOSE] : re[t3.COMPARATOR]; - const m3 = comp.match(r4); - if (!m3) { - throw new TypeError(`Invalid comparator: ${comp}`); - } - this.operator = m3[1] !== void 0 ? m3[1] : ""; - if (this.operator === "=") { - this.operator = ""; - } - if (!m3[2]) { - this.semver = ANY; - } else { - this.semver = new SemVer(m3[2], this.options.loose); - } - } - toString() { - return this.value; - } - test(version2) { - debug4("Comparator.test", version2, this.options.loose); - if (this.semver === ANY || version2 === ANY) { - return true; - } - if (typeof version2 === "string") { - try { - version2 = new SemVer(version2, this.options); - } catch (er) { - return false; - } - } - return cmp(version2, this.operator, this.semver, this.options); - } - intersects(comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError("a Comparator is required"); - } - if (this.operator === "") { - if (this.value === "") { - return true; - } - return new Range2(comp.value, options).test(this.value); - } else if (comp.operator === "") { - if (comp.value === "") { - return true; - } - return new Range2(this.value, options).test(comp.semver); - } - options = parseOptions(options); - if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { - return false; - } - if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { - return false; - } - if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { - return true; - } - if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { - return true; - } - if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { - return true; - } - if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { - return true; - } - if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { - return true; - } - return false; - } - }; - module2.exports = Comparator; - var parseOptions = require_parse_options(); - var { safeRe: re, t: t3 } = require_re(); - var cmp = require_cmp(); - var debug4 = require_debug(); - var SemVer = require_semver(); - var Range2 = require_range(); - } -}); - -// node_modules/semver/functions/satisfies.js -var require_satisfies = __commonJS({ - "node_modules/semver/functions/satisfies.js"(exports, module2) { - var Range2 = require_range(); - var satisfies = (version2, range, options) => { - try { - range = new Range2(range, options); - } catch (er) { - return false; - } - return range.test(version2); - }; - module2.exports = satisfies; - } -}); - -// node_modules/semver/ranges/to-comparators.js -var require_to_comparators = __commonJS({ - "node_modules/semver/ranges/to-comparators.js"(exports, module2) { - var Range2 = require_range(); - var toComparators = (range, options) => new Range2(range, options).set.map((comp) => comp.map((c4) => c4.value).join(" ").trim().split(" ")); - module2.exports = toComparators; - } -}); - -// node_modules/semver/ranges/max-satisfying.js -var require_max_satisfying = __commonJS({ - "node_modules/semver/ranges/max-satisfying.js"(exports, module2) { - var SemVer = require_semver(); - var Range2 = require_range(); - var maxSatisfying = (versions, range, options) => { - let max2 = null; - let maxSV = null; - let rangeObj = null; - try { - rangeObj = new Range2(range, options); - } catch (er) { - return null; - } - versions.forEach((v5) => { - if (rangeObj.test(v5)) { - if (!max2 || maxSV.compare(v5) === -1) { - max2 = v5; - maxSV = new SemVer(max2, options); - } - } - }); - return max2; - }; - module2.exports = maxSatisfying; - } -}); - -// node_modules/semver/ranges/min-satisfying.js -var require_min_satisfying = __commonJS({ - "node_modules/semver/ranges/min-satisfying.js"(exports, module2) { - var SemVer = require_semver(); - var Range2 = require_range(); - var minSatisfying = (versions, range, options) => { - let min2 = null; - let minSV = null; - let rangeObj = null; - try { - rangeObj = new Range2(range, options); - } catch (er) { - return null; - } - versions.forEach((v5) => { - if (rangeObj.test(v5)) { - if (!min2 || minSV.compare(v5) === 1) { - min2 = v5; - minSV = new SemVer(min2, options); - } - } - }); - return min2; - }; - module2.exports = minSatisfying; - } -}); - -// node_modules/semver/ranges/min-version.js -var require_min_version = __commonJS({ - "node_modules/semver/ranges/min-version.js"(exports, module2) { - var SemVer = require_semver(); - var Range2 = require_range(); - var gt = require_gt(); - var minVersion = (range, loose) => { - range = new Range2(range, loose); - let minver = new SemVer("0.0.0"); - if (range.test(minver)) { - return minver; - } - minver = new SemVer("0.0.0-0"); - if (range.test(minver)) { - return minver; - } - minver = null; - for (let i3 = 0; i3 < range.set.length; ++i3) { - const comparators = range.set[i3]; - let setMin = null; - comparators.forEach((comparator) => { - const compver = new SemVer(comparator.semver.version); - switch (comparator.operator) { - case ">": - if (compver.prerelease.length === 0) { - compver.patch++; - } else { - compver.prerelease.push(0); - } - compver.raw = compver.format(); - case "": - case ">=": - if (!setMin || gt(compver, setMin)) { - setMin = compver; - } - break; - case "<": - case "<=": - break; - default: - throw new Error(`Unexpected operation: ${comparator.operator}`); - } - }); - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin; - } - } - if (minver && range.test(minver)) { - return minver; - } - return null; - }; - module2.exports = minVersion; - } -}); - -// node_modules/semver/ranges/valid.js -var require_valid2 = __commonJS({ - "node_modules/semver/ranges/valid.js"(exports, module2) { - var Range2 = require_range(); - var validRange = (range, options) => { - try { - return new Range2(range, options).range || "*"; - } catch (er) { - return null; - } - }; - module2.exports = validRange; - } -}); - -// node_modules/semver/ranges/outside.js -var require_outside = __commonJS({ - "node_modules/semver/ranges/outside.js"(exports, module2) { - var SemVer = require_semver(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var Range2 = require_range(); - var satisfies = require_satisfies(); - var gt = require_gt(); - var lt = require_lt(); - var lte = require_lte(); - var gte = require_gte(); - var outside = (version2, range, hilo, options) => { - version2 = new SemVer(version2, options); - range = new Range2(range, options); - let gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case ">": - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = ">"; - ecomp = ">="; - break; - case "<": - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = "<"; - ecomp = "<="; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - if (satisfies(version2, range, options)) { - return false; - } - for (let i3 = 0; i3 < range.set.length; ++i3) { - const comparators = range.set[i3]; - let high = null; - let low = null; - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator(">=0.0.0"); - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator; - } - }); - if (high.operator === comp || high.operator === ecomp) { - return false; - } - if ((!low.operator || low.operator === comp) && ltefn(version2, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version2, low.semver)) { - return false; - } - } - return true; - }; - module2.exports = outside; - } -}); - -// node_modules/semver/ranges/gtr.js -var require_gtr = __commonJS({ - "node_modules/semver/ranges/gtr.js"(exports, module2) { - var outside = require_outside(); - var gtr = (version2, range, options) => outside(version2, range, ">", options); - module2.exports = gtr; - } -}); - -// node_modules/semver/ranges/ltr.js -var require_ltr = __commonJS({ - "node_modules/semver/ranges/ltr.js"(exports, module2) { - var outside = require_outside(); - var ltr = (version2, range, options) => outside(version2, range, "<", options); - module2.exports = ltr; - } -}); - -// node_modules/semver/ranges/intersects.js -var require_intersects = __commonJS({ - "node_modules/semver/ranges/intersects.js"(exports, module2) { - var Range2 = require_range(); - var intersects = (r1, r22, options) => { - r1 = new Range2(r1, options); - r22 = new Range2(r22, options); - return r1.intersects(r22, options); - }; - module2.exports = intersects; - } -}); - -// node_modules/semver/ranges/simplify.js -var require_simplify = __commonJS({ - "node_modules/semver/ranges/simplify.js"(exports, module2) { - var satisfies = require_satisfies(); - var compare2 = require_compare(); - module2.exports = (versions, range, options) => { - const set = []; - let first = null; - let prev = null; - const v5 = versions.sort((a3, b3) => compare2(a3, b3, options)); - for (const version2 of v5) { - const included = satisfies(version2, range, options); - if (included) { - prev = version2; - if (!first) { - first = version2; - } - } else { - if (prev) { - set.push([first, prev]); - } - prev = null; - first = null; - } - } - if (first) { - set.push([first, null]); - } - const ranges = []; - for (const [min2, max2] of set) { - if (min2 === max2) { - ranges.push(min2); - } else if (!max2 && min2 === v5[0]) { - ranges.push("*"); - } else if (!max2) { - ranges.push(`>=${min2}`); - } else if (min2 === v5[0]) { - ranges.push(`<=${max2}`); - } else { - ranges.push(`${min2} - ${max2}`); - } - } - const simplified = ranges.join(" || "); - const original = typeof range.raw === "string" ? range.raw : String(range); - return simplified.length < original.length ? simplified : range; - }; - } -}); - -// node_modules/semver/ranges/subset.js -var require_subset = __commonJS({ - "node_modules/semver/ranges/subset.js"(exports, module2) { - var Range2 = require_range(); - var Comparator = require_comparator(); - var { ANY } = Comparator; - var satisfies = require_satisfies(); - var compare2 = require_compare(); - var subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true; - } - sub = new Range2(sub, options); - dom = new Range2(dom, options); - let sawNonNull = false; - OUTER: - for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options); - sawNonNull = sawNonNull || isSub !== null; - if (isSub) { - continue OUTER; - } - } - if (sawNonNull) { - return false; - } - } - return true; - }; - var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; - var minimumVersion = [new Comparator(">=0.0.0")]; - var simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true; - } - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true; - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease; - } else { - sub = minimumVersion; - } - } - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true; - } else { - dom = minimumVersion; - } - } - const eqSet = /* @__PURE__ */ new Set(); - let gt, lt; - for (const c4 of sub) { - if (c4.operator === ">" || c4.operator === ">=") { - gt = higherGT(gt, c4, options); - } else if (c4.operator === "<" || c4.operator === "<=") { - lt = lowerLT(lt, c4, options); - } else { - eqSet.add(c4.semver); - } - } - if (eqSet.size > 1) { - return null; - } - let gtltComp; - if (gt && lt) { - gtltComp = compare2(gt.semver, lt.semver, options); - if (gtltComp > 0) { - return null; - } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { - return null; - } - } - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null; - } - if (lt && !satisfies(eq, String(lt), options)) { - return null; - } - for (const c4 of dom) { - if (!satisfies(eq, String(c4), options)) { - return false; - } - } - return true; - } - let higher, lower; - let hasDomLT, hasDomGT; - let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; - let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false; - } - for (const c4 of dom) { - hasDomGT = hasDomGT || c4.operator === ">" || c4.operator === ">="; - hasDomLT = hasDomLT || c4.operator === "<" || c4.operator === "<="; - if (gt) { - if (needDomGTPre) { - if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomGTPre.major && c4.semver.minor === needDomGTPre.minor && c4.semver.patch === needDomGTPre.patch) { - needDomGTPre = false; - } - } - if (c4.operator === ">" || c4.operator === ">=") { - higher = higherGT(gt, c4, options); - if (higher === c4 && higher !== gt) { - return false; - } - } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c4), options)) { - return false; - } - } - if (lt) { - if (needDomLTPre) { - if (c4.semver.prerelease && c4.semver.prerelease.length && c4.semver.major === needDomLTPre.major && c4.semver.minor === needDomLTPre.minor && c4.semver.patch === needDomLTPre.patch) { - needDomLTPre = false; - } - } - if (c4.operator === "<" || c4.operator === "<=") { - lower = lowerLT(lt, c4, options); - if (lower === c4 && lower !== lt) { - return false; - } - } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c4), options)) { - return false; - } - } - if (!c4.operator && (lt || gt) && gtltComp !== 0) { - return false; - } - } - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false; - } - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false; - } - if (needDomGTPre || needDomLTPre) { - return false; - } - return true; - }; - var higherGT = (a3, b3, options) => { - if (!a3) { - return b3; - } - const comp = compare2(a3.semver, b3.semver, options); - return comp > 0 ? a3 : comp < 0 ? b3 : b3.operator === ">" && a3.operator === ">=" ? b3 : a3; - }; - var lowerLT = (a3, b3, options) => { - if (!a3) { - return b3; - } - const comp = compare2(a3.semver, b3.semver, options); - return comp < 0 ? a3 : comp > 0 ? b3 : b3.operator === "<" && a3.operator === "<=" ? b3 : a3; - }; - module2.exports = subset; - } -}); - -// node_modules/semver/index.js -var require_semver2 = __commonJS({ - "node_modules/semver/index.js"(exports, module2) { - var internalRe = require_re(); - var constants = require_constants(); - var SemVer = require_semver(); - var identifiers = require_identifiers(); - var parse6 = require_parse(); - var valid = require_valid(); - var clean = require_clean(); - var inc = require_inc(); - var diff = require_diff(); - var major = require_major(); - var minor = require_minor(); - var patch = require_patch(); - var prerelease = require_prerelease(); - var compare2 = require_compare(); - var rcompare = require_rcompare(); - var compareLoose = require_compare_loose(); - var compareBuild = require_compare_build(); - var sort = require_sort(); - var rsort = require_rsort(); - var gt = require_gt(); - var lt = require_lt(); - var eq = require_eq(); - var neq = require_neq(); - var gte = require_gte(); - var lte = require_lte(); - var cmp = require_cmp(); - var coerce2 = require_coerce(); - var Comparator = require_comparator(); - var Range2 = require_range(); - var satisfies = require_satisfies(); - var toComparators = require_to_comparators(); - var maxSatisfying = require_max_satisfying(); - var minSatisfying = require_min_satisfying(); - var minVersion = require_min_version(); - var validRange = require_valid2(); - var outside = require_outside(); - var gtr = require_gtr(); - var ltr = require_ltr(); - var intersects = require_intersects(); - var simplifyRange = require_simplify(); - var subset = require_subset(); - module2.exports = { - parse: parse6, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare: compare2, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce: coerce2, - Comparator, - Range: Range2, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers - }; - } -}); - -// node_modules/langsmith/dist/utils/prompts.js -function parsePromptIdentifier(identifier) { - if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return [owner, name, commit]; - } else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return ["-", ownerNamePart, commit]; - } -} -var import_semver; -var init_prompts = __esm({ - "node_modules/langsmith/dist/utils/prompts.js"() { - import_semver = __toESM(require_semver2(), 1); - } -}); - -// node_modules/langsmith/dist/utils/error.js -async function raiseForStatus(response, context, consume) { - let errorBody; - if (response.ok) { - if (consume) { - errorBody = await response.text(); - } - return; - } - errorBody = await response.text(); - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); - } - throw new Error(fullMessage); -} -var LangSmithConflictError; -var init_error = __esm({ - "node_modules/langsmith/dist/utils/error.js"() { - LangSmithConflictError = class extends Error { - constructor(message) { - super(message); - this.name = "LangSmithConflictError"; - } - }; - } -}); - -// node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -function defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - }; -} -function stringify(obj, replacer, spacer, options) { - try { - return JSON.stringify(obj, replacer, spacer); - } catch (e3) { - if (!e3.message?.includes("Converting circular structure to JSON")) { - console.warn("[WARNING]: LangSmith received unserializable value."); - return "[Unserializable]"; - } - console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."); - if (typeof options === "undefined") { - options = defaultOptions(); - } - decirc(obj, "", 0, [], void 0, 0, options); - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); - } - } catch (_2) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } finally { - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } else { - part[0][part[1]] = part[2]; - } - } - } - return res; - } -} -function setReplace(replace, val2, k3, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k3); - if (propertyDescriptor.get !== void 0) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k3, { value: replace }); - arr.push([parent, k3, val2, propertyDescriptor]); - } else { - replacerStack.push([val2, k3, replace]); - } - } else { - parent[k3] = replace; - arr.push([parent, k3, val2]); - } -} -function decirc(val2, k3, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i3; - if (typeof val2 === "object" && val2 !== null) { - for (i3 = 0; i3 < stack.length; i3++) { - if (stack[i3] === val2) { - setReplace(CIRCULAR_REPLACE_NODE, val2, k3, parent); - return; - } - } - if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val2, k3, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val2, k3, parent); - return; - } - stack.push(val2); - if (Array.isArray(val2)) { - for (i3 = 0; i3 < val2.length; i3++) { - decirc(val2[i3], i3, i3, stack, val2, depth, options); - } - } else { - var keys = Object.keys(val2); - for (i3 = 0; i3 < keys.length; i3++) { - var key = keys[i3]; - decirc(val2[key], key, i3, stack, val2, depth, options); - } - } - stack.pop(); - } -} -function replaceGetterValues(replacer) { - replacer = typeof replacer !== "undefined" ? replacer : function(k3, v5) { - return v5; - }; - return function(key, val2) { - if (replacerStack.length > 0) { - for (var i3 = 0; i3 < replacerStack.length; i3++) { - var part = replacerStack[i3]; - if (part[1] === key && part[0] === val2) { - val2 = part[2]; - replacerStack.splice(i3, 1); - break; - } - } - } - return replacer.call(this, key, val2); - }; -} -var LIMIT_REPLACE_NODE, CIRCULAR_REPLACE_NODE, arr, replacerStack; -var init_fast_safe_stringify = __esm({ - "node_modules/langsmith/dist/utils/fast-safe-stringify/index.js"() { - LIMIT_REPLACE_NODE = "[...]"; - CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; - arr = []; - replacerStack = []; - } -}); - -// node_modules/langsmith/dist/client.js -function mergeRuntimeEnvIntoRunCreate(run) { - const runtimeEnv = getRuntimeEnvironment(); - const envVars = getLangChainEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime - }, - metadata: { - ...envVars, - ...envVars.revision_id || run.revision_id ? { revision_id: run.revision_id ?? envVars.revision_id } : {}, - ...metadata - } - }; - return run; -} -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str2) { - if (str2 === void 0) { - return void 0; - } - return str2.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"); -} -var getTracingSamplingRate, isLocalhost, handle429, AutoBatchQueue, DEFAULT_BATCH_SIZE_LIMIT_BYTES, SERVER_INFO_REQUEST_TIMEOUT, Client; -var init_client = __esm({ - "node_modules/langsmith/dist/client.js"() { - init_esm_browser2(); - init_async_caller(); - init_messages(); - init_env(); - init_dist(); - init_uuid(); - init_warn(); - init_prompts(); - init_error(); - init_fetch(); - init_fast_safe_stringify(); - getTracingSamplingRate = () => { - const samplingRateStr = getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === void 0) { - return void 0; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; - }; - isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; - }; - handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1e3; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - return true; - } - } - return false; - }; - AutoBatchQueue = class { - constructor() { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - } - peek() { - return this.items[0]; - } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - itemPromiseResolve = resolve; - }); - const size4 = stringify(item.item).length; - this.items.push({ - action: item.action, - payload: item.item, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve, - itemPromise, - size: size4 - }); - this.sizeBytes += size4; - return itemPromise; - } - pop(upToSizeBytes) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - } - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - return [ - popped.map((it) => ({ action: it.action, item: it.payload })), - () => popped.forEach((it) => it.itemPromiseResolve()) - ]; - } - }; - DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520; - SERVER_INFO_REQUEST_TIMEOUT = 2500; - Client = class { - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: /* @__PURE__ */ new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: new AutoBatchQueue() - }); - Object.defineProperty(this, "autoBatchTimeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { - enumerable: true, - configurable: true, - writable: true, - value: 250 - }); - Object.defineProperty(this, "batchSizeBytesLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchOptions", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "settings", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" - }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 - }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); - } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); - } - this.timeout_ms = config.timeout_ms ?? 9e4; - this.caller = new AsyncCaller(config.callerOptions ?? {}); - this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); - } - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 2, - maxConcurrency: this.traceBatchConcurrency, - ...config.callerOptions ?? {}, - onFailedResponseHook: handle429 - }); - this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; - } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? "https://api.smith.langchain.com"; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl, - apiKey, - webUrl: void 0, - hideInputs, - hideOutputs - }; - } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; - } else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; - } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; - } else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; - } else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; - } else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; - } - } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}` - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; - } - return headers; - } - processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; - } - if (this.hideInputs === true) { - return {}; - } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); - } - return inputs; - } - processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; - } - if (this.hideOutputs === true) { - return {}; - } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); - } - return outputs; - } - prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== void 0) { - runParams.inputs = this.processInputs(runParams.inputs); - } - if (runParams.outputs !== void 0) { - runParams.outputs = this.processOutputs(runParams.outputs); - } - return runParams; - } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - return response; - } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); - } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset5 = Number(queryParams.get("offset")) || 0; - const limit2 = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset5)); - queryParams.set("limit", String(limit2)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = transform ? transform(await response.json()) : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit2) { - break; - } - offset5 += items.length; - } - } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: JSON.stringify(bodyParams) - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; - } - if (!cursors.next) { - break; - } - bodyParams.cursor = cursors.next; - } - } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === void 0) { - return runs; - } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.id)) { - sampled.push(run); - } else { - this.filteredPostUuids.delete(run.id); - } - } - return sampled; - } else { - const sampled = []; - for (const run of runs) { - if (run.id !== run.trace_id && !this.filteredPostUuids.has(run.trace_id) || Math.random() < this.tracingSampleRate) { - sampled.push(run); - } else { - this.filteredPostUuids.add(run.id); - } - } - return sampled; - } - } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_BATCH_SIZE_LIMIT_BYTES; - } - async _getMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false; - } - drainAutoBatchQueue(batchSizeLimit) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); - if (!batch.length) { - done(); - break; - } - const batchPromise = this._processBatch(batch, done).catch(console.error); - promises.push(batchPromise); - } - return Promise.all(promises); - } - async _processBatch(batch, done) { - if (!batch.length) { - done(); - return; - } - try { - const ingestParams = { - runCreates: batch.filter((item) => item.action === "create").map((item) => item.item), - runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item) - }; - const serverInfo = await this._ensureServerInfo(); - if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { - await this.multipartIngestRuns(ingestParams); - } else { - await this.batchIngestRuns(ingestParams); - } - } finally { - done(); - } - } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = void 0; - if (item.action === "create") { - item.item = mergeRuntimeEnvIntoRunCreate(item.item); - } - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - return itemPromise; - } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { - void this.drainAutoBatchQueue(sizeLimitBytes); - } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = void 0; - void this.drainAutoBatchQueue(sizeLimitBytes); - }, this.autoBatchAggregationDelayMs); - } - return itemPromise; - } - async _getServerInfo() { - const response = await _getFetchImplementation()(`${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), - ...this.fetchOptions - }); - await raiseForStatus(response, "get server info"); - return response.json(); - } - async _ensureServerInfo() { - if (this._getServerInfoPromise === void 0) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === void 0) { - try { - this._serverInfo = await this._getServerInfo(); - } catch (e3) { - console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.`); - } - } - return this._serverInfo ?? {}; - })(); - } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === void 0) { - this._getServerInfoPromise = void 0; - } - return serverInfo; - }); - } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); - } - return await this.settings; - } - /** - * Flushes current queued traces. - */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - await this.drainAutoBatchQueue(sizeLimitBytes); - } - async createRun(run) { - if (!this._filterForSampling([run]).length) { - return; - } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now() - }); - if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) { - void this.processRunOperation({ - action: "create", - item: runCreate - }).catch(console.error); - return; - } - const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs`, { - method: "POST", - headers, - body: stringify(mergedRunCreateParam), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create run", true); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async batchIngestRuns({ runCreates, runUpdates }) { - if (runCreates === void 0 && runUpdates === void 0) { - return; - } - let preparedCreateParams = runCreates?.map((create9) => this.prepareRunCreateOrUpdateInputs(create9)) ?? []; - let preparedUpdateParams = runUpdates?.map((update2) => this.prepareRunCreateOrUpdateInputs(update2)) ?? []; - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== void 0 && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam - }; - } else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - const rawBatch = { - post: this._filterForSampling(preparedCreateParams), - patch: this._filterForSampling(preparedUpdateParams, true) - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { - return; - } - const batchChunks = { - post: [], - patch: [] - }; - for (const k3 of ["post", "patch"]) { - const key = k3; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== void 0) { - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } - } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - await this._postBatchIngestRuns(stringify(batchChunks)); - } - } - async _postBatchIngestRuns(body) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json" - }; - const response = await this.batchIngestCaller.call(_getFetchImplementation(), `${this.apiUrl}/runs/batch`, { - method: "POST", - headers, - body, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "batch create run", true); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async multipartIngestRuns({ runCreates, runUpdates }) { - if (runCreates === void 0 && runUpdates === void 0) { - return; - } - const allAttachments = {}; - let preparedCreateParams = []; - for (const create9 of runCreates ?? []) { - const preparedCreate = this.prepareRunCreateOrUpdateInputs(create9); - if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; - } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); - } - let preparedUpdateParams = []; - for (const update2 of runUpdates ?? []) { - preparedUpdateParams.push(this.prepareRunCreateOrUpdateInputs(update2)); - } - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0; - }); - if (invalidRunCreate !== void 0) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); - } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0; - }); - if (invalidRunUpdate !== void 0) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); - } - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== void 0 && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam - }; - } else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) { - return; - } - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams] - ]) { - for (const originalPayload of payloads) { - const { inputs, outputs, events, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events }; - const stringifiedPayload = stringify(payload); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}` - // encoding=gzip - }) - }); - for (const [key, value] of Object.entries(fields)) { - if (value === void 0) { - continue; - } - const stringifiedValue = stringify(value); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}` - }) - }); - } - if (payload.id !== void 0) { - const attachments2 = allAttachments[payload.id]; - if (attachments2) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments2)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } else { - contentType = attachment.mimeType; - content = attachment.data; - } - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}` - }) - }); - } - } - } - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); - } - } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; ")); - } - async _sendMultipartRequest(parts, context) { - try { - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const chunks = []; - for (const part of parts) { - chunks.push(new Blob([`--${boundary}\r -`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r -`, - `Content-Type: ${part.payload.type}\r +var s8t=Object.create;var _$=Object.defineProperty;var u8t=Object.getOwnPropertyDescriptor;var l8t=Object.getOwnPropertyNames;var c8t=Object.getPrototypeOf,d8t=Object.prototype.hasOwnProperty;var f8t=(e,t,r)=>t in e?_$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kd=(e,t)=>{for(var r in t)_$(e,r,{get:t[r],enumerable:!0})},B1e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of l8t(t))!d8t.call(e,o)&&o!==r&&_$(e,o,{get:()=>t[o],enumerable:!(n=u8t(t,o))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?s8t(c8t(e)):{},B1e(t||!e||!e.__esModule?_$(r,"default",{value:e,enumerable:!0}):r,e)),il=e=>B1e(_$({},"__esModule",{value:!0}),e);var Nl=(e,t,r)=>f8t(e,typeof t!="symbol"?t+"":t,r);function h8t(e){U1e=e}function g6(){return U1e}function He(e,t){let r=g6(),n=y6({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===bD?void 0:bD].filter(o=>!!o)});e.common.issues.push(n)}function b6(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}function z1e(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function gr(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,s)=>{var u,l;let{message:c}=e;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:(u=c??n)!==null&&u!==void 0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void 0?l:s.defaultError}},description:o}}function V1e(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function R8t(e){return new RegExp(`^${V1e(e)}$`)}function W1e(e){let t=`${H1e}T${V1e(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function D8t(e,t){return!!((t==="v4"||!t)&&O8t.test(e)||(t==="v6"||!t)&&P8t.test(e))}function j8t(e,t){if(!w8t.test(e))return!1;try{let[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function N8t(e,t){return!!((t==="v4"||!t)&&E8t.test(e)||(t==="v6"||!t)&&T8t.test(e))}function L8t(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}function gD(e){if(e instanceof Zd){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Yd.create(gD(n))}return new Zd({...e._def,shape:()=>t})}else return e instanceof hS?new hS({...e._def,type:gD(e.element)}):e instanceof Yd?Yd.create(gD(e.unwrap())):e instanceof Qg?Qg.create(gD(e.unwrap())):e instanceof Xg?Xg.create(e.items.map(t=>gD(t))):e}function xae(e,t){let r=fS(e),n=fS(t);if(e===t)return{valid:!0,data:e};if(r===Qe.object&&n===Qe.object){let o=Sn.objectKeys(t),i=Sn.objectKeys(e).filter(s=>o.indexOf(s)!==-1),a={...e,...t};for(let s of i){let u=xae(e[s],t[s]);if(!u.valid)return{valid:!1};a[s]=u.data}return{valid:!0,data:a}}else if(r===Qe.array&&n===Qe.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i{var i,a;if(!e(n)){let s=typeof t=="function"?t(n):typeof t=="string"?{message:t}:t,u=(a=(i=s.fatal)!==null&&i!==void 0?i:r)!==null&&a!==void 0?a:!0,l=typeof s=="string"?{message:s}:s;o.addIssue({code:"custom",...l,fatal:u})}}):lO.create()}var Sn,vae,Qe,fS,ve,p8t,Yf,bD,U1e,y6,m8t,Ic,$t,yD,yd,wae,Sae,hM,S$,mt,v$,w$,Gp,$1e,yr,g8t,y8t,b8t,_8t,v8t,w8t,S8t,x8t,C8t,_ae,O8t,E8t,P8t,T8t,M8t,I8t,H1e,A8t,uO,mM,gM,yM,bM,_D,_M,vM,lO,pS,Rm,vD,hS,Zd,wM,dS,_6,SM,Xg,v6,wD,SD,w6,xM,CM,OM,EM,cO,Zf,Yd,Qg,PM,TM,xD,F8t,x$,C$,MM,k8t,re,B8t,K1e,Y1e,$8t,q8t,Z1e,U8t,z8t,H8t,V8t,W8t,J8t,G8t,K8t,Y8t,Z8t,X8t,Q8t,eHt,tHt,rHt,nHt,oHt,iHt,aHt,sHt,uHt,lHt,cHt,dHt,q1e,fHt,pHt,hHt,mHt,gHt,yHt,bHt,_Ht,vHt,Er,bd=C(()=>{(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},e.getValidEnumValues=o=>{let i=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(let s of i)a[s]=o[s];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(let a of o)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(Sn||(Sn={}));(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(vae||(vae={}));Qe=Sn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),fS=e=>{switch(typeof e){case"undefined":return Qe.undefined;case"string":return Qe.string;case"number":return isNaN(e)?Qe.nan:Qe.number;case"boolean":return Qe.boolean;case"function":return Qe.function;case"bigint":return Qe.bigint;case"symbol":return Qe.symbol;case"object":return Array.isArray(e)?Qe.array:e===null?Qe.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Qe.promise:typeof Map<"u"&&e instanceof Map?Qe.map:typeof Set<"u"&&e instanceof Set?Qe.set:typeof Date<"u"&&e instanceof Date?Qe.date:Qe.object;default:return Qe.unknown}},ve=Sn.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"]),p8t=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Yf=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let s=n,u=0;for(;ur.message){let r={},n=[];for(let o of this.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Yf.create=e=>new Yf(e);bD=(e,t)=>{let r;switch(e.code){case ve.invalid_type:e.received===Qe.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ve.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Sn.jsonStringifyReplacer)}`;break;case ve.unrecognized_keys:r=`Unrecognized key(s) in object: ${Sn.joinValues(e.keys,", ")}`;break;case ve.invalid_union:r="Invalid input";break;case ve.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Sn.joinValues(e.options)}`;break;case ve.invalid_enum_value:r=`Invalid enum value. Expected ${Sn.joinValues(e.options)}, received '${e.received}'`;break;case ve.invalid_arguments:r="Invalid function arguments";break;case ve.invalid_return_type:r="Invalid function return type";break;case ve.invalid_date:r="Invalid date";break;case ve.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Sn.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ve.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ve.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ve.custom:r="Invalid input";break;case ve.invalid_intersection_types:r="Intersection results could not be merged";break;case ve.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ve.not_finite:r="Number must be finite";break;default:r=t.defaultError,Sn.assertNever(e)}return{message:r}},U1e=bD;y6=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let s="",u=n.filter(l=>!!l).slice().reverse();for(let l of u)s=l(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}},m8t=[];Ic=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let o of r){if(o.status==="aborted")return $t;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let i=await o.key,a=await o.value;n.push({key:i,value:a})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return $t;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[i.value]=a.value)}return{status:t.value,value:n}}},$t=Object.freeze({status:"aborted"}),yD=e=>({status:"dirty",value:e}),yd=e=>({status:"valid",value:e}),wae=e=>e.status==="aborted",Sae=e=>e.status==="dirty",hM=e=>e.status==="valid",S$=e=>typeof Promise<"u"&&e instanceof Promise;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(mt||(mt={}));Gp=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$1e=(e,t)=>{if(hM(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Yf(e.common.issues);return this._error=r,this._error}}};yr=class{get description(){return this._def.description}_getType(t){return fS(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:fS(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ic,ctx:{common:t.parent.common,data:t.data,parsedType:fS(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(S$(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){var n;let o={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fS(t)},i=this._parseSync({data:t,path:o.path,parent:o});return $1e(o,i)}"~validate"(t){var r,n;let o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fS(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:o});return hM(i)?{value:i.value}:{issues:o.common.issues}}catch(i){!((n=(r=i?.message)===null||r===void 0?void 0:r.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:o}).then(i=>hM(i)?{value:i.value}:{issues:o.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:fS(t)},o=this._parse({data:t,path:n.path,parent:n}),i=await(S$(o)?o:Promise.resolve(o));return $1e(n,i)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let a=t(o),s=()=>i.addIssue({code:ve.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Zf({schema:this,typeName:re.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Yd.create(this,this._def)}nullable(){return Qg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hS.create(this)}promise(){return cO.create(this,this._def)}or(t){return wM.create([this,t],this._def)}and(t){return SM.create(this,t,this._def)}transform(t){return new Zf({...gr(this._def),schema:this,typeName:re.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new PM({...gr(this._def),innerType:this,defaultValue:r,typeName:re.ZodDefault})}brand(){return new x$({typeName:re.ZodBranded,type:this,...gr(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new TM({...gr(this._def),innerType:this,catchValue:r,typeName:re.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return C$.create(this,t)}readonly(){return MM.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},g8t=/^c[^\s-]{8,}$/i,y8t=/^[0-9a-z]+$/,b8t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_8t=/^[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,v8t=/^[a-z0-9_-]{21}$/i,w8t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,S8t=/^[-+]?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)?)??$/,x8t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,C8t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",O8t=/^(?:(?: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])$/,E8t=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,P8t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,T8t=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,M8t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,I8t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H1e="((\\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])))",A8t=new RegExp(`^${H1e}$`);uO=class e extends yr{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Qe.string){let i=this._getOrReturnCtx(t);return He(i,{code:ve.invalid_type,expected:Qe.string,received:i.parsedType}),$t}let n=new Ic,o;for(let i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),He(o,{code:ve.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let a=t.data.length>i.value,s=t.data.lengtht.test(o),{validation:r,code:ve.invalid_string,...mt.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...mt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...mt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...mt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...mt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...mt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...mt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...mt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...mt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...mt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...mt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...mt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...mt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...mt.errToObj(t)})}datetime(t){var r,n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(r=t?.offset)!==null&&r!==void 0?r:!1,local:(n=t?.local)!==null&&n!==void 0?n:!1,...mt.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...mt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...mt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...mt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...mt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...mt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...mt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...mt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...mt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...mt.errToObj(r)})}nonempty(t){return this.min(1,mt.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value{var t;return new uO({checks:[],typeName:re.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...gr(e)})};mM=class e extends yr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Qe.number){let i=this._getOrReturnCtx(t);return He(i,{code:ve.invalid_type,expected:Qe.number,received:i.parsedType}),$t}let n,o=new Ic;for(let i of this._def.checks)i.kind==="int"?Sn.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),He(n,{code:ve.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),He(n,{code:ve.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?L8t(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),He(n,{code:ve.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),He(n,{code:ve.not_finite,message:i.message}),o.dirty()):Sn.assertNever(i);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,mt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,mt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,mt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,mt.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:mt.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:mt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:mt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:mt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:mt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:mt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:mt.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&Sn.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.valuenew mM({checks:[],typeName:re.ZodNumber,coerce:e?.coerce||!1,...gr(e)});gM=class e extends yr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Qe.bigint)return this._getInvalidInput(t);let n,o=new Ic;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),He(n,{code:ve.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),He(n,{code:ve.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):Sn.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return He(r,{code:ve.invalid_type,expected:Qe.bigint,received:r.parsedType}),$t}gte(t,r){return this.setLimit("min",t,!0,mt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,mt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,mt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,mt.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:mt.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:mt.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value{var t;return new gM({checks:[],typeName:re.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...gr(e)})};yM=class extends yr{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Qe.boolean){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.boolean,received:n.parsedType}),$t}return yd(t.data)}};yM.create=e=>new yM({typeName:re.ZodBoolean,coerce:e?.coerce||!1,...gr(e)});bM=class e extends yr{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Qe.date){let i=this._getOrReturnCtx(t);return He(i,{code:ve.invalid_type,expected:Qe.date,received:i.parsedType}),$t}if(isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return He(i,{code:ve.invalid_date}),$t}let n=new Ic,o;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),He(o,{code:ve.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Sn.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:mt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:mt.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew bM({checks:[],coerce:e?.coerce||!1,typeName:re.ZodDate,...gr(e)});_D=class extends yr{_parse(t){if(this._getType(t)!==Qe.symbol){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.symbol,received:n.parsedType}),$t}return yd(t.data)}};_D.create=e=>new _D({typeName:re.ZodSymbol,...gr(e)});_M=class extends yr{_parse(t){if(this._getType(t)!==Qe.undefined){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.undefined,received:n.parsedType}),$t}return yd(t.data)}};_M.create=e=>new _M({typeName:re.ZodUndefined,...gr(e)});vM=class extends yr{_parse(t){if(this._getType(t)!==Qe.null){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.null,received:n.parsedType}),$t}return yd(t.data)}};vM.create=e=>new vM({typeName:re.ZodNull,...gr(e)});lO=class extends yr{constructor(){super(...arguments),this._any=!0}_parse(t){return yd(t.data)}};lO.create=e=>new lO({typeName:re.ZodAny,...gr(e)});pS=class extends yr{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yd(t.data)}};pS.create=e=>new pS({typeName:re.ZodUnknown,...gr(e)});Rm=class extends yr{_parse(t){let r=this._getOrReturnCtx(t);return He(r,{code:ve.invalid_type,expected:Qe.never,received:r.parsedType}),$t}};Rm.create=e=>new Rm({typeName:re.ZodNever,...gr(e)});vD=class extends yr{_parse(t){if(this._getType(t)!==Qe.undefined){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.void,received:n.parsedType}),$t}return yd(t.data)}};vD.create=e=>new vD({typeName:re.ZodVoid,...gr(e)});hS=class e extends yr{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==Qe.array)return He(r,{code:ve.invalid_type,expected:Qe.array,received:r.parsedType}),$t;if(o.exactLength!==null){let a=r.data.length>o.exactLength.value,s=r.data.lengtho.maxLength.value&&(He(r,{code:ve.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,s)=>o.type._parseAsync(new Gp(r,a,r.path,s)))).then(a=>Ic.mergeArray(n,a));let i=[...r.data].map((a,s)=>o.type._parseSync(new Gp(r,a,r.path,s)));return Ic.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:mt.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:mt.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:mt.toString(r)}})}nonempty(t){return this.min(1,t)}};hS.create=(e,t)=>new hS({type:e,minLength:null,maxLength:null,exactLength:null,typeName:re.ZodArray,...gr(t)});Zd=class e extends yr{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Sn.objectKeys(t);return this._cached={shape:t,keys:r}}_parse(t){if(this._getType(t)!==Qe.object){let l=this._getOrReturnCtx(t);return He(l,{code:ve.invalid_type,expected:Qe.object,received:l.parsedType}),$t}let{status:n,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Rm&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||s.push(l);let u=[];for(let l of a){let c=i[l],d=o.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Gp(o,d,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Rm){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of s)u.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(l==="strict")s.length>0&&(He(o,{code:ve.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of s){let d=o.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Gp(o,d,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let c of u){let d=await c.key,f=await c.value;l.push({key:d,value:f,alwaysSet:c.alwaysSet})}return l}).then(l=>Ic.mergeObjectSync(n,l)):Ic.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(t){return mt.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var o,i,a,s;let u=(a=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,r,n).message)!==null&&a!==void 0?a:n.defaultError;return r.code==="unrecognized_keys"?{message:(s=mt.errToObj(t).message)!==null&&s!==void 0?s:u}:{message:u}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:re.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};return Sn.objectKeys(t).forEach(n=>{t[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}omit(t){let r={};return Sn.objectKeys(this.shape).forEach(n=>{t[n]||(r[n]=this.shape[n])}),new e({...this._def,shape:()=>r})}deepPartial(){return gD(this)}partial(t){let r={};return Sn.objectKeys(this.shape).forEach(n=>{let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}),new e({...this._def,shape:()=>r})}required(t){let r={};return Sn.objectKeys(this.shape).forEach(n=>{if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Yd;)i=i._def.innerType;r[n]=i}}),new e({...this._def,shape:()=>r})}keyof(){return J1e(Sn.objectKeys(this.shape))}};Zd.create=(e,t)=>new Zd({shape:()=>e,unknownKeys:"strip",catchall:Rm.create(),typeName:re.ZodObject,...gr(t)});Zd.strictCreate=(e,t)=>new Zd({shape:()=>e,unknownKeys:"strict",catchall:Rm.create(),typeName:re.ZodObject,...gr(t)});Zd.lazycreate=(e,t)=>new Zd({shape:e,unknownKeys:"strip",catchall:Rm.create(),typeName:re.ZodObject,...gr(t)});wM=class extends yr{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(i){for(let s of i)if(s.result.status==="valid")return s.result;for(let s of i)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(s=>new Yf(s.ctx.common.issues));return He(r,{code:ve.invalid_union,unionErrors:a}),$t}if(r.common.async)return Promise.all(n.map(async i=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of n){let l={...r,common:{...r.common,issues:[]},parent:null},c=u._parseSync({data:r.data,path:r.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!i&&(i={result:c,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let s=a.map(u=>new Yf(u));return He(r,{code:ve.invalid_union,unionErrors:s}),$t}}get options(){return this._def.options}};wM.create=(e,t)=>new wM({options:e,typeName:re.ZodUnion,...gr(t)});dS=e=>e instanceof xM?dS(e.schema):e instanceof Zf?dS(e.innerType()):e instanceof CM?[e.value]:e instanceof OM?e.options:e instanceof EM?Sn.objectValues(e.enum):e instanceof PM?dS(e._def.innerType):e instanceof _M?[void 0]:e instanceof vM?[null]:e instanceof Yd?[void 0,...dS(e.unwrap())]:e instanceof Qg?[null,...dS(e.unwrap())]:e instanceof x$||e instanceof MM?dS(e.unwrap()):e instanceof TM?dS(e._def.innerType):[],_6=class e extends yr{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Qe.object)return He(r,{code:ve.invalid_type,expected:Qe.object,received:r.parsedType}),$t;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(He(r,{code:ve.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),$t)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let i of r){let a=dS(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of a){if(o.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);o.set(s,i)}}return new e({typeName:re.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...gr(n)})}};SM=class extends yr{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(i,a)=>{if(wae(i)||wae(a))return $t;let s=xae(i.value,a.value);return s.valid?((Sae(i)||Sae(a))&&r.dirty(),{status:r.value,value:s.data}):(He(n,{code:ve.invalid_intersection_types}),$t)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};SM.create=(e,t,r)=>new SM({left:e,right:t,typeName:re.ZodIntersection,...gr(r)});Xg=class e extends yr{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Qe.array)return He(n,{code:ve.invalid_type,expected:Qe.array,received:n.parsedType}),$t;if(n.data.lengththis._def.items.length&&(He(n,{code:ve.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((a,s)=>{let u=this._def.items[s]||this._def.rest;return u?u._parse(new Gp(n,a,n.path,s)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>Ic.mergeArray(r,a)):Ic.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Xg.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xg({items:e,typeName:re.ZodTuple,rest:null,...gr(t)})};v6=class e extends yr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Qe.object)return He(n,{code:ve.invalid_type,expected:Qe.object,received:n.parsedType}),$t;let o=[],i=this._def.keyType,a=this._def.valueType;for(let s in n.data)o.push({key:i._parse(new Gp(n,s,n.path,s)),value:a._parse(new Gp(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?Ic.mergeObjectAsync(r,o):Ic.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof yr?new e({keyType:t,valueType:r,typeName:re.ZodRecord,...gr(n)}):new e({keyType:uO.create(),valueType:t,typeName:re.ZodRecord,...gr(r)})}},wD=class extends yr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Qe.map)return He(n,{code:ve.invalid_type,expected:Qe.map,received:n.parsedType}),$t;let o=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([s,u],l)=>({key:o._parse(new Gp(n,s,n.path,[l,"key"])),value:i._parse(new Gp(n,u,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,c=await u.value;if(l.status==="aborted"||c.status==="aborted")return $t;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),s.set(l.value,c.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let u of a){let l=u.key,c=u.value;if(l.status==="aborted"||c.status==="aborted")return $t;(l.status==="dirty"||c.status==="dirty")&&r.dirty(),s.set(l.value,c.value)}return{status:r.value,value:s}}}};wD.create=(e,t,r)=>new wD({valueType:t,keyType:e,typeName:re.ZodMap,...gr(r)});SD=class e extends yr{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Qe.set)return He(n,{code:ve.invalid_type,expected:Qe.set,received:n.parsedType}),$t;let o=this._def;o.minSize!==null&&n.data.sizeo.maxSize.value&&(He(n,{code:ve.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let c of u){if(c.status==="aborted")return $t;c.status==="dirty"&&r.dirty(),l.add(c.value)}return{status:r.value,value:l}}let s=[...n.data.values()].map((u,l)=>i._parse(new Gp(n,u,n.path,l)));return n.common.async?Promise.all(s).then(u=>a(u)):a(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:mt.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:mt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};SD.create=(e,t)=>new SD({valueType:e,minSize:null,maxSize:null,typeName:re.ZodSet,...gr(t)});w6=class e extends yr{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Qe.function)return He(r,{code:ve.invalid_type,expected:Qe.function,received:r.parsedType}),$t;function n(s,u){return y6({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,g6(),bD].filter(l=>!!l),issueData:{code:ve.invalid_arguments,argumentsError:u}})}function o(s,u){return y6({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,g6(),bD].filter(l=>!!l),issueData:{code:ve.invalid_return_type,returnTypeError:u}})}let i={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof cO){let s=this;return yd(async function(...u){let l=new Yf([]),c=await s._def.args.parseAsync(u,i).catch(p=>{throw l.addIssue(n(u,p)),l}),d=await Reflect.apply(a,this,c);return await s._def.returns._def.type.parseAsync(d,i).catch(p=>{throw l.addIssue(o(d,p)),l})})}else{let s=this;return yd(function(...u){let l=s._def.args.safeParse(u,i);if(!l.success)throw new Yf([n(u,l.error)]);let c=Reflect.apply(a,this,l.data),d=s._def.returns.safeParse(c,i);if(!d.success)throw new Yf([o(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Xg.create(t).rest(pS.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||Xg.create([]).rest(pS.create()),returns:r||pS.create(),typeName:re.ZodFunction,...gr(n)})}},xM=class extends yr{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};xM.create=(e,t)=>new xM({getter:e,typeName:re.ZodLazy,...gr(t)});CM=class extends yr{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return He(r,{received:r.data,code:ve.invalid_literal,expected:this._def.value}),$t}return{status:"valid",value:t.data}}get value(){return this._def.value}};CM.create=(e,t)=>new CM({value:e,typeName:re.ZodLiteral,...gr(t)});OM=class e extends yr{constructor(){super(...arguments),v$.set(this,void 0)}_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return He(r,{expected:Sn.joinValues(n),received:r.parsedType,code:ve.invalid_type}),$t}if(b6(this,v$,"f")||z1e(this,v$,new Set(this._def.values),"f"),!b6(this,v$,"f").has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return He(r,{received:r.data,code:ve.invalid_enum_value,options:n}),$t}return yd(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};v$=new WeakMap;OM.create=J1e;EM=class extends yr{constructor(){super(...arguments),w$.set(this,void 0)}_parse(t){let r=Sn.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Qe.string&&n.parsedType!==Qe.number){let o=Sn.objectValues(r);return He(n,{expected:Sn.joinValues(o),received:n.parsedType,code:ve.invalid_type}),$t}if(b6(this,w$,"f")||z1e(this,w$,new Set(Sn.getValidEnumValues(this._def.values)),"f"),!b6(this,w$,"f").has(t.data)){let o=Sn.objectValues(r);return He(n,{received:n.data,code:ve.invalid_enum_value,options:o}),$t}return yd(t.data)}get enum(){return this._def.values}};w$=new WeakMap;EM.create=(e,t)=>new EM({values:e,typeName:re.ZodNativeEnum,...gr(t)});cO=class extends yr{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Qe.promise&&r.common.async===!1)return He(r,{code:ve.invalid_type,expected:Qe.promise,received:r.parsedType}),$t;let n=r.parsedType===Qe.promise?r.data:Promise.resolve(r.data);return yd(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};cO.create=(e,t)=>new cO({type:e,typeName:re.ZodPromise,...gr(t)});Zf=class extends yr{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===re.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:a=>{He(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async s=>{if(r.value==="aborted")return $t;let u=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return u.status==="aborted"?$t:u.status==="dirty"||r.value==="dirty"?yD(u.value):u});{if(r.value==="aborted")return $t;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});return s.status==="aborted"?$t:s.status==="dirty"||r.value==="dirty"?yD(s.value):s}}if(o.type==="refinement"){let a=s=>{let u=o.refinement(s,i);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?$t:(s.status==="dirty"&&r.dirty(),a(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?$t:(s.status==="dirty"&&r.dirty(),a(s.value).then(()=>({status:r.value,value:s.value}))))}if(o.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!hM(a))return a;let s=o.transform(a.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>hM(a)?Promise.resolve(o.transform(a.value,i)).then(s=>({status:r.value,value:s})):a);Sn.assertNever(o)}};Zf.create=(e,t,r)=>new Zf({schema:e,typeName:re.ZodEffects,effect:t,...gr(r)});Zf.createWithPreprocess=(e,t,r)=>new Zf({schema:t,effect:{type:"preprocess",transform:e},typeName:re.ZodEffects,...gr(r)});Yd=class extends yr{_parse(t){return this._getType(t)===Qe.undefined?yd(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Yd.create=(e,t)=>new Yd({innerType:e,typeName:re.ZodOptional,...gr(t)});Qg=class extends yr{_parse(t){return this._getType(t)===Qe.null?yd(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Qg.create=(e,t)=>new Qg({innerType:e,typeName:re.ZodNullable,...gr(t)});PM=class extends yr{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Qe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};PM.create=(e,t)=>new PM({innerType:e,typeName:re.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...gr(t)});TM=class extends yr{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return S$(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Yf(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Yf(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};TM.create=(e,t)=>new TM({innerType:e,typeName:re.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...gr(t)});xD=class extends yr{_parse(t){if(this._getType(t)!==Qe.nan){let n=this._getOrReturnCtx(t);return He(n,{code:ve.invalid_type,expected:Qe.nan,received:n.parsedType}),$t}return{status:"valid",value:t.data}}};xD.create=e=>new xD({typeName:re.ZodNaN,...gr(e)});F8t=Symbol("zod_brand"),x$=class extends yr{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},C$=class e extends yr{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?$t:i.status==="dirty"?(r.dirty(),yD(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?$t:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:re.ZodPipeline})}},MM=class extends yr{_parse(t){let r=this._def.innerType._parse(t),n=o=>(hM(o)&&(o.value=Object.freeze(o.value)),o);return S$(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};MM.create=(e,t)=>new MM({innerType:e,typeName:re.ZodReadonly,...gr(t)});k8t={object:Zd.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(re||(re={}));B8t=(e,t={message:`Input not instance of ${e.name}`})=>G1e(r=>r instanceof e,t),K1e=uO.create,Y1e=mM.create,$8t=xD.create,q8t=gM.create,Z1e=yM.create,U8t=bM.create,z8t=_D.create,H8t=_M.create,V8t=vM.create,W8t=lO.create,J8t=pS.create,G8t=Rm.create,K8t=vD.create,Y8t=hS.create,Z8t=Zd.create,X8t=Zd.strictCreate,Q8t=wM.create,eHt=_6.create,tHt=SM.create,rHt=Xg.create,nHt=v6.create,oHt=wD.create,iHt=SD.create,aHt=w6.create,sHt=xM.create,uHt=CM.create,lHt=OM.create,cHt=EM.create,dHt=cO.create,q1e=Zf.create,fHt=Yd.create,pHt=Qg.create,hHt=Zf.createWithPreprocess,mHt=C$.create,gHt=()=>K1e().optional(),yHt=()=>Y1e().optional(),bHt=()=>Z1e().optional(),_Ht={string:e=>uO.create({...e,coerce:!0}),number:e=>mM.create({...e,coerce:!0}),boolean:e=>yM.create({...e,coerce:!0}),bigint:e=>gM.create({...e,coerce:!0}),date:e=>bM.create({...e,coerce:!0})},vHt=$t,Er=Object.freeze({__proto__:null,defaultErrorMap:bD,setErrorMap:h8t,getErrorMap:g6,makeIssue:y6,EMPTY_PATH:m8t,addIssueToContext:He,ParseStatus:Ic,INVALID:$t,DIRTY:yD,OK:yd,isAborted:wae,isDirty:Sae,isValid:hM,isAsync:S$,get util(){return Sn},get objectUtil(){return vae},ZodParsedType:Qe,getParsedType:fS,ZodType:yr,datetimeRegex:W1e,ZodString:uO,ZodNumber:mM,ZodBigInt:gM,ZodBoolean:yM,ZodDate:bM,ZodSymbol:_D,ZodUndefined:_M,ZodNull:vM,ZodAny:lO,ZodUnknown:pS,ZodNever:Rm,ZodVoid:vD,ZodArray:hS,ZodObject:Zd,ZodUnion:wM,ZodDiscriminatedUnion:_6,ZodIntersection:SM,ZodTuple:Xg,ZodRecord:v6,ZodMap:wD,ZodSet:SD,ZodFunction:w6,ZodLazy:xM,ZodLiteral:CM,ZodEnum:OM,ZodNativeEnum:EM,ZodPromise:cO,ZodEffects:Zf,ZodTransformer:Zf,ZodOptional:Yd,ZodNullable:Qg,ZodDefault:PM,ZodCatch:TM,ZodNaN:xD,BRAND:F8t,ZodBranded:x$,ZodPipeline:C$,ZodReadonly:MM,custom:G1e,Schema:yr,ZodSchema:yr,late:k8t,get ZodFirstPartyTypeKind(){return re},coerce:_Ht,any:W8t,array:Y8t,bigint:q8t,boolean:Z1e,date:U8t,discriminatedUnion:eHt,effect:q1e,enum:lHt,function:aHt,instanceof:B8t,intersection:tHt,lazy:sHt,literal:uHt,map:oHt,nan:$8t,nativeEnum:cHt,never:G8t,null:V8t,nullable:pHt,number:Y1e,object:Z8t,oboolean:bHt,onumber:yHt,optional:fHt,ostring:gHt,pipeline:mHt,preprocess:hHt,promise:dHt,record:nHt,set:iHt,strictObject:X8t,string:K1e,symbol:z8t,transformer:q1e,tuple:rHt,undefined:H8t,union:Q8t,unknown:J8t,void:K8t,NEVER:vHt,ZodIssueCode:ve,quotelessJson:p8t,ZodError:Yf})});var Q1e=b((Wmn,X1e)=>{function Kp(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}X1e.exports=Kp;Kp.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Kp.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Kp.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};Kp.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Kp.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};Kp.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};Kp.prototype.start=Kp.prototype.try;Kp.prototype.errors=function(){return this._errors};Kp.prototype.attempts=function(){return this._attempts};Kp.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=a)}return t}});var eDe=b(IM=>{var wHt=Q1e();IM.operation=function(e){var t=IM.timeouts(e);return new wHt(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};IM.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o{tDe.exports=eDe()});var C6=b((Kmn,x6)=>{"use strict";var SHt=rDe(),xHt=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],S6=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}},CHt=(e,t,r)=>{let n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e},OHt=e=>xHt.includes(e),nDe=(e,t)=>new Promise((r,n)=>{t={onFailedAttempt:()=>{},retries:10,...t};let o=SHt.operation(t);o.attempt(async i=>{try{r(await e(i))}catch(a){if(!(a instanceof Error)){n(new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`));return}if(a instanceof S6)o.stop(),n(a.originalError);else if(a instanceof TypeError&&!OHt(a.message))o.stop(),n(a);else{CHt(a,i,t);try{await t.onFailedAttempt(a)}catch(s){n(s);return}o.retry(a)||n(o.mainError())}}})});x6.exports=nDe;x6.exports.default=nDe;x6.exports.AbortError=S6});var oDe,iDe=C(()=>{oDe=/^(?:[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});function EHt(e){return typeof e=="string"&&oDe.test(e)}var CD,aDe=C(()=>{iDe();CD=EHt});function sDe(e,t=0){return(Ll[e[t+0]]+Ll[e[t+1]]+Ll[e[t+2]]+Ll[e[t+3]]+"-"+Ll[e[t+4]]+Ll[e[t+5]]+"-"+Ll[e[t+6]]+Ll[e[t+7]]+"-"+Ll[e[t+8]]+Ll[e[t+9]]+"-"+Ll[e[t+10]]+Ll[e[t+11]]+Ll[e[t+12]]+Ll[e[t+13]]+Ll[e[t+14]]+Ll[e[t+15]]).toLowerCase()}var Ll,O6,uDe=C(()=>{Ll=[];for(O6=0;O6<256;++O6)Ll.push((O6+256).toString(16).slice(1))});function Cae(){if(!E6&&(E6=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!E6))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return E6(PHt)}var E6,PHt,lDe=C(()=>{PHt=new Uint8Array(16)});var THt,Oae,cDe=C(()=>{THt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Oae={randomUUID:THt}});function MHt(e,t,r){if(Oae.randomUUID&&!t&&!e)return Oae.randomUUID();e=e||{};var n=e.random||(e.rng||Cae)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var o=0;o<16;++o)t[r+o]=n[o];return t}return sDe(n)}var Xd,dDe=C(()=>{cDe();lDe();uDe();Xd=MHt});var O$=C(()=>{dDe();aDe()});var fDe,pDe=C(()=>{fDe=/^(?:[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});function AHt(e){return typeof e=="string"&&fDe.test(e)}var Eae,hDe=C(()=>{pDe();Eae=AHt});function mDe(e,t=0){return(Fl[e[t+0]]+Fl[e[t+1]]+Fl[e[t+2]]+Fl[e[t+3]]+"-"+Fl[e[t+4]]+Fl[e[t+5]]+"-"+Fl[e[t+6]]+Fl[e[t+7]]+"-"+Fl[e[t+8]]+Fl[e[t+9]]+"-"+Fl[e[t+10]]+Fl[e[t+11]]+Fl[e[t+12]]+Fl[e[t+13]]+Fl[e[t+14]]+Fl[e[t+15]]).toLowerCase()}var Fl,P6,gDe=C(()=>{Fl=[];for(P6=0;P6<256;++P6)Fl.push((P6+256).toString(16).slice(1))});function Pae(){if(!T6&&(T6=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!T6))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T6(RHt)}var T6,RHt,yDe=C(()=>{RHt=new Uint8Array(16)});var DHt,Tae,bDe=C(()=>{DHt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Tae={randomUUID:DHt}});function jHt(e,t,r){if(Tae.randomUUID&&!t&&!e)return Tae.randomUUID();e=e||{};var n=e.random||(e.rng||Pae)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var o=0;o<16;++o)t[r+o]=n[o];return t}return mDe(n)}var dO,_De=C(()=>{bDe();yDe();gDe();dO=jHt});var M6=C(()=>{_De();hDe()});var wDe=b((vgn,Iae)=>{"use strict";var NHt=Object.prototype.hasOwnProperty,_d="~";function E$(){}Object.create&&(E$.prototype=Object.create(null),new E$().__proto__||(_d=!1));function LHt(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function vDe(e,t,r,n,o){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new LHt(r,n||e,o),a=_d?_d+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],i]:e._events[a].push(i):(e._events[a]=i,e._eventsCount++),e}function I6(e,t){--e._eventsCount===0?e._events=new E$:delete e._events[t]}function Ac(){this._events=new E$,this._eventsCount=0}Ac.prototype.eventNames=function(){var t=[],r,n;if(this._eventsCount===0)return t;for(n in r=this._events)NHt.call(r,n)&&t.push(_d?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(r)):t};Ac.prototype.listeners=function(t){var r=_d?_d+t:t,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,a=new Array(i);o{"use strict";SDe.exports=(e,t)=>(t=t||(()=>{}),e.then(r=>new Promise(n=>{n(t())}).then(()=>r),r=>new Promise(n=>{n(t())}).then(()=>{throw r})))});var ODe=b((Sgn,R6)=>{"use strict";var FHt=xDe(),A6=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},CDe=(e,t,r)=>new Promise((n,o)=>{if(typeof t!="number"||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0){n(e);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(u){o(u)}return}let a=typeof r=="string"?r:`Promise timed out after ${t} milliseconds`,s=r instanceof Error?r:new A6(a);typeof e.cancel=="function"&&e.cancel(),o(s)},t);FHt(e.then(n,o),()=>{clearTimeout(i)})});R6.exports=CDe;R6.exports.default=CDe;R6.exports.TimeoutError=A6});var EDe=b(Aae=>{"use strict";Object.defineProperty(Aae,"__esModule",{value:!0});function kHt(e,t,r){let n=0,o=e.length;for(;o>0;){let i=o/2|0,a=n+i;r(e[a],t)<=0?(n=++a,o-=i+1):o=i}return n}Aae.default=kHt});var PDe=b(Dae=>{"use strict";Object.defineProperty(Dae,"__esModule",{value:!0});var BHt=EDe(),Rae=class{constructor(){this._queue=[]}enqueue(t,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:t};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let o=BHt.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(o,0,n)}dequeue(){let t=this._queue.shift();return t?.run}filter(t){return this._queue.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this._queue.length}};Dae.default=Rae});var j6=b(Nae=>{"use strict";Object.defineProperty(Nae,"__esModule",{value:!0});var $Ht=wDe(),TDe=ODe(),qHt=PDe(),D6=()=>{},UHt=new TDe.TimeoutError,jae=class extends $Ht{constructor(t){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=D6,this._resolveIdle=D6,t=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:qHt.default},t),!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=t.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof t.interval})`);this._carryoverConcurrencyCount=t.carryoverConcurrencyCount,this._isIntervalIgnored=t.intervalCap===1/0||t.interval===0,this._intervalCap=t.intervalCap,this._interval=t.interval,this._queue=new t.queueClass,this._queueClass=t.queueClass,this.concurrency=t.concurrency,this._timeout=t.timeout,this._throwOnTimeout=t.throwOnTimeout===!0,this._isPaused=t.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount{this._onResumeInterval()},r)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let t=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),t&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this._concurrency=t,this._processQueue()}async add(t,r={}){return new Promise((n,o)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?t():TDe.default(Promise.resolve(t()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&o(UHt)});n(await a)}catch(a){o(a)}this._next()};this._queue.enqueue(i,r),this._tryToStartAnother(),this.emit("add")})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(t=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),t()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(t=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),t()}})}get size(){return this._queue.size}sizeBy(t){return this._queue.filter(t).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(t){this._timeout=t}};Nae.default=jae});var zHt,HHt,wt,N6=C(()=>{zHt=(...e)=>fetch(...e),HHt=Symbol.for("ls:fetch_implementation"),wt=()=>globalThis[HHt]??zHt});var MDe,L6,VHt,WHt,P$,IDe=C(()=>{MDe=B(C6(),1),L6=B(j6(),1);N6();VHt=[400,401,403,404,405,406,407,408],WHt=[409],P$=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in L6.default?this.queue=new L6.default.default({concurrency:this.maxConcurrency}):this.queue=new L6.default({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...r){let n=this.onFailedResponseHook;return this.queue.add(()=>(0,MDe.default)(()=>t(...r).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt(o){if(o.message.startsWith("Cancel")||o.message.startsWith("TimeoutError")||o.message.startsWith("AbortError")||o?.code==="ECONNABORTED")throw o;let i=o?.response,a=i?.status;if(a){if(VHt.includes(+a))throw o;if(WHt.includes(+a))return;n&&await n(i)}},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,r,...n){return t.signal?Promise.race([this.call(r,...n),new Promise((o,i)=>{t.signal?.addEventListener("abort",()=>{i(new Error("AbortError"))})})]):this.call(r,...n)}fetch(...t){return this.call(()=>wt()(...t).then(r=>r.ok?r:Promise.reject(r)))}}});function Lae(e){return typeof e?._getType=="function"}function Fae(e){let t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var ADe=C(()=>{});function en(e,t){if(!Eae(e)){let r=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(r)}return e}var RDe=C(()=>{M6()});function F6(e){DDe[e]||(console.warn(e),DDe[e]=!0)}var DDe,kae=C(()=>{DDe={}});var T$=b((Rgn,jDe)=>{var JHt="2.0.0",GHt=Number.MAX_SAFE_INTEGER||9007199254740991,KHt=16,YHt=250,ZHt=["major","premajor","minor","preminor","patch","prepatch","prerelease"];jDe.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:KHt,MAX_SAFE_BUILD_LENGTH:YHt,MAX_SAFE_INTEGER:GHt,RELEASE_TYPES:ZHt,SEMVER_SPEC_VERSION:JHt,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var M$=b((Dgn,NDe)=>{var XHt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};NDe.exports=XHt});var OD=b((mS,LDe)=>{var{MAX_SAFE_COMPONENT_LENGTH:Bae,MAX_SAFE_BUILD_LENGTH:QHt,MAX_LENGTH:e6t}=T$(),t6t=M$();mS=LDe.exports={};var r6t=mS.re=[],n6t=mS.safeRe=[],tt=mS.src=[],rt=mS.t={},o6t=0,$ae="[a-zA-Z0-9-]",i6t=[["\\s",1],["\\d",e6t],[$ae,QHt]],a6t=e=>{for(let[t,r]of i6t)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},cr=(e,t,r)=>{let n=a6t(t),o=o6t++;t6t(e,o,t),rt[e]=o,tt[o]=t,r6t[o]=new RegExp(t,r?"g":void 0),n6t[o]=new RegExp(n,r?"g":void 0)};cr("NUMERICIDENTIFIER","0|[1-9]\\d*");cr("NUMERICIDENTIFIERLOOSE","\\d+");cr("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${$ae}*`);cr("MAINVERSION",`(${tt[rt.NUMERICIDENTIFIER]})\\.(${tt[rt.NUMERICIDENTIFIER]})\\.(${tt[rt.NUMERICIDENTIFIER]})`);cr("MAINVERSIONLOOSE",`(${tt[rt.NUMERICIDENTIFIERLOOSE]})\\.(${tt[rt.NUMERICIDENTIFIERLOOSE]})\\.(${tt[rt.NUMERICIDENTIFIERLOOSE]})`);cr("PRERELEASEIDENTIFIER",`(?:${tt[rt.NUMERICIDENTIFIER]}|${tt[rt.NONNUMERICIDENTIFIER]})`);cr("PRERELEASEIDENTIFIERLOOSE",`(?:${tt[rt.NUMERICIDENTIFIERLOOSE]}|${tt[rt.NONNUMERICIDENTIFIER]})`);cr("PRERELEASE",`(?:-(${tt[rt.PRERELEASEIDENTIFIER]}(?:\\.${tt[rt.PRERELEASEIDENTIFIER]})*))`);cr("PRERELEASELOOSE",`(?:-?(${tt[rt.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${tt[rt.PRERELEASEIDENTIFIERLOOSE]})*))`);cr("BUILDIDENTIFIER",`${$ae}+`);cr("BUILD",`(?:\\+(${tt[rt.BUILDIDENTIFIER]}(?:\\.${tt[rt.BUILDIDENTIFIER]})*))`);cr("FULLPLAIN",`v?${tt[rt.MAINVERSION]}${tt[rt.PRERELEASE]}?${tt[rt.BUILD]}?`);cr("FULL",`^${tt[rt.FULLPLAIN]}$`);cr("LOOSEPLAIN",`[v=\\s]*${tt[rt.MAINVERSIONLOOSE]}${tt[rt.PRERELEASELOOSE]}?${tt[rt.BUILD]}?`);cr("LOOSE",`^${tt[rt.LOOSEPLAIN]}$`);cr("GTLT","((?:<|>)?=?)");cr("XRANGEIDENTIFIERLOOSE",`${tt[rt.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);cr("XRANGEIDENTIFIER",`${tt[rt.NUMERICIDENTIFIER]}|x|X|\\*`);cr("XRANGEPLAIN",`[v=\\s]*(${tt[rt.XRANGEIDENTIFIER]})(?:\\.(${tt[rt.XRANGEIDENTIFIER]})(?:\\.(${tt[rt.XRANGEIDENTIFIER]})(?:${tt[rt.PRERELEASE]})?${tt[rt.BUILD]}?)?)?`);cr("XRANGEPLAINLOOSE",`[v=\\s]*(${tt[rt.XRANGEIDENTIFIERLOOSE]})(?:\\.(${tt[rt.XRANGEIDENTIFIERLOOSE]})(?:\\.(${tt[rt.XRANGEIDENTIFIERLOOSE]})(?:${tt[rt.PRERELEASELOOSE]})?${tt[rt.BUILD]}?)?)?`);cr("XRANGE",`^${tt[rt.GTLT]}\\s*${tt[rt.XRANGEPLAIN]}$`);cr("XRANGELOOSE",`^${tt[rt.GTLT]}\\s*${tt[rt.XRANGEPLAINLOOSE]}$`);cr("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Bae}})(?:\\.(\\d{1,${Bae}}))?(?:\\.(\\d{1,${Bae}}))?`);cr("COERCE",`${tt[rt.COERCEPLAIN]}(?:$|[^\\d])`);cr("COERCEFULL",tt[rt.COERCEPLAIN]+`(?:${tt[rt.PRERELEASE]})?(?:${tt[rt.BUILD]})?(?:$|[^\\d])`);cr("COERCERTL",tt[rt.COERCE],!0);cr("COERCERTLFULL",tt[rt.COERCEFULL],!0);cr("LONETILDE","(?:~>?)");cr("TILDETRIM",`(\\s*)${tt[rt.LONETILDE]}\\s+`,!0);mS.tildeTrimReplace="$1~";cr("TILDE",`^${tt[rt.LONETILDE]}${tt[rt.XRANGEPLAIN]}$`);cr("TILDELOOSE",`^${tt[rt.LONETILDE]}${tt[rt.XRANGEPLAINLOOSE]}$`);cr("LONECARET","(?:\\^)");cr("CARETTRIM",`(\\s*)${tt[rt.LONECARET]}\\s+`,!0);mS.caretTrimReplace="$1^";cr("CARET",`^${tt[rt.LONECARET]}${tt[rt.XRANGEPLAIN]}$`);cr("CARETLOOSE",`^${tt[rt.LONECARET]}${tt[rt.XRANGEPLAINLOOSE]}$`);cr("COMPARATORLOOSE",`^${tt[rt.GTLT]}\\s*(${tt[rt.LOOSEPLAIN]})$|^$`);cr("COMPARATOR",`^${tt[rt.GTLT]}\\s*(${tt[rt.FULLPLAIN]})$|^$`);cr("COMPARATORTRIM",`(\\s*)${tt[rt.GTLT]}\\s*(${tt[rt.LOOSEPLAIN]}|${tt[rt.XRANGEPLAIN]})`,!0);mS.comparatorTrimReplace="$1$2$3";cr("HYPHENRANGE",`^\\s*(${tt[rt.XRANGEPLAIN]})\\s+-\\s+(${tt[rt.XRANGEPLAIN]})\\s*$`);cr("HYPHENRANGELOOSE",`^\\s*(${tt[rt.XRANGEPLAINLOOSE]})\\s+-\\s+(${tt[rt.XRANGEPLAINLOOSE]})\\s*$`);cr("STAR","(<|>)?=?\\s*\\*");cr("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");cr("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var k6=b((jgn,FDe)=>{var s6t=Object.freeze({loose:!0}),u6t=Object.freeze({}),l6t=e=>e?typeof e!="object"?s6t:e:u6t;FDe.exports=l6t});var qae=b((Ngn,$De)=>{var kDe=/^[0-9]+$/,BDe=(e,t)=>{let r=kDe.test(e),n=kDe.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:eBDe(t,e);$De.exports={compareIdentifiers:BDe,rcompareIdentifiers:c6t}});var Rc=b((Lgn,HDe)=>{var B6=M$(),{MAX_LENGTH:qDe,MAX_SAFE_INTEGER:$6}=T$(),{safeRe:UDe,t:zDe}=OD(),d6t=k6(),{compareIdentifiers:ED}=qae(),Uae=class e{constructor(t,r){if(r=d6t(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>qDe)throw new TypeError(`version is longer than ${qDe} characters`);B6("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?UDe[zDe.LOOSE]:UDe[zDe.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>$6||this.major<0)throw new TypeError("Invalid major version");if(this.minor>$6||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>$6||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let i=+o;if(i>=0&&i<$6)return i}return o}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(B6("SemVer.compare",this.version,this.options,t),!(t instanceof e)){if(typeof t=="string"&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),ED(this.major,t.major)||ED(this.minor,t.minor)||ED(this.patch,t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],o=t.prerelease[r];if(B6("prerelease compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ED(n,o)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],o=t.build[r];if(B6("build compare",r,n,o),n===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(n===void 0)return-1;if(n===o)continue;return ED(n,o)}while(++r)}inc(t,r,n){switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let o=Number(n)?1:0;if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(this.prerelease.length===0)this.prerelease=[o];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(r){let i=[r,o];n===!1&&(i=[r]),ED(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};HDe.exports=Uae});var AM=b((Fgn,WDe)=>{var VDe=Rc(),f6t=(e,t,r=!1)=>{if(e instanceof VDe)return e;try{return new VDe(e,t)}catch(n){if(!r)return null;throw n}};WDe.exports=f6t});var GDe=b((kgn,JDe)=>{var p6t=AM(),h6t=(e,t)=>{let r=p6t(e,t);return r?r.version:null};JDe.exports=h6t});var YDe=b((Bgn,KDe)=>{var m6t=AM(),g6t=(e,t)=>{let r=m6t(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};KDe.exports=g6t});var QDe=b(($gn,XDe)=>{var ZDe=Rc(),y6t=(e,t,r,n,o)=>{typeof r=="string"&&(o=n,n=r,r=void 0);try{return new ZDe(e instanceof ZDe?e.version:e,r).inc(t,n,o).version}catch{return null}};XDe.exports=y6t});var rje=b((qgn,tje)=>{var eje=AM(),b6t=(e,t)=>{let r=eje(e,null,!0),n=eje(t,null,!0),o=r.compare(n);if(o===0)return null;let i=o>0,a=i?r:n,s=i?n:r,u=!!a.prerelease.length;if(!!s.prerelease.length&&!u)return!s.patch&&!s.minor?"major":a.patch?"patch":a.minor?"minor":"major";let c=u?"pre":"";return r.major!==n.major?c+"major":r.minor!==n.minor?c+"minor":r.patch!==n.patch?c+"patch":"prerelease"};tje.exports=b6t});var oje=b((Ugn,nje)=>{var _6t=Rc(),v6t=(e,t)=>new _6t(e,t).major;nje.exports=v6t});var aje=b((zgn,ije)=>{var w6t=Rc(),S6t=(e,t)=>new w6t(e,t).minor;ije.exports=S6t});var uje=b((Hgn,sje)=>{var x6t=Rc(),C6t=(e,t)=>new x6t(e,t).patch;sje.exports=C6t});var cje=b((Vgn,lje)=>{var O6t=AM(),E6t=(e,t)=>{let r=O6t(e,t);return r&&r.prerelease.length?r.prerelease:null};lje.exports=E6t});var Yp=b((Wgn,fje)=>{var dje=Rc(),P6t=(e,t,r)=>new dje(e,r).compare(new dje(t,r));fje.exports=P6t});var hje=b((Jgn,pje)=>{var T6t=Yp(),M6t=(e,t,r)=>T6t(t,e,r);pje.exports=M6t});var gje=b((Ggn,mje)=>{var I6t=Yp(),A6t=(e,t)=>I6t(e,t,!0);mje.exports=A6t});var q6=b((Kgn,bje)=>{var yje=Rc(),R6t=(e,t,r)=>{let n=new yje(e,r),o=new yje(t,r);return n.compare(o)||n.compareBuild(o)};bje.exports=R6t});var vje=b((Ygn,_je)=>{var D6t=q6(),j6t=(e,t)=>e.sort((r,n)=>D6t(r,n,t));_je.exports=j6t});var Sje=b((Zgn,wje)=>{var N6t=q6(),L6t=(e,t)=>e.sort((r,n)=>N6t(n,r,t));wje.exports=L6t});var I$=b((Xgn,xje)=>{var F6t=Yp(),k6t=(e,t,r)=>F6t(e,t,r)>0;xje.exports=k6t});var U6=b((Qgn,Cje)=>{var B6t=Yp(),$6t=(e,t,r)=>B6t(e,t,r)<0;Cje.exports=$6t});var zae=b((eyn,Oje)=>{var q6t=Yp(),U6t=(e,t,r)=>q6t(e,t,r)===0;Oje.exports=U6t});var Hae=b((tyn,Eje)=>{var z6t=Yp(),H6t=(e,t,r)=>z6t(e,t,r)!==0;Eje.exports=H6t});var z6=b((ryn,Pje)=>{var V6t=Yp(),W6t=(e,t,r)=>V6t(e,t,r)>=0;Pje.exports=W6t});var H6=b((nyn,Tje)=>{var J6t=Yp(),G6t=(e,t,r)=>J6t(e,t,r)<=0;Tje.exports=G6t});var Vae=b((oyn,Mje)=>{var K6t=zae(),Y6t=Hae(),Z6t=I$(),X6t=z6(),Q6t=U6(),eVt=H6(),tVt=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return K6t(e,r,n);case"!=":return Y6t(e,r,n);case">":return Z6t(e,r,n);case">=":return X6t(e,r,n);case"<":return Q6t(e,r,n);case"<=":return eVt(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Mje.exports=tVt});var Aje=b((iyn,Ije)=>{var rVt=Rc(),nVt=AM(),{safeRe:V6,t:W6}=OD(),oVt=(e,t)=>{if(e instanceof rVt)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?V6[W6.COERCEFULL]:V6[W6.COERCE]);else{let u=t.includePrerelease?V6[W6.COERCERTLFULL]:V6[W6.COERCERTL],l;for(;(l=u.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),u.lastIndex=l.index+l[1].length+l[2].length;u.lastIndex=-1}if(r===null)return null;let n=r[2],o=r[3]||"0",i=r[4]||"0",a=t.includePrerelease&&r[5]?`-${r[5]}`:"",s=t.includePrerelease&&r[6]?`+${r[6]}`:"";return nVt(`${n}.${o}.${i}${a}${s}`,t)};Ije.exports=oVt});var Dje=b((ayn,Rje)=>{var Wae=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}};Rje.exports=Wae});var Zp=b((syn,Fje)=>{var iVt=/\s+/g,Jae=class e{constructor(t,r){if(r=sVt(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Gae)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(iVt," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(o=>!Nje(o[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&hVt(o[0])){this.set=[o];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&fVt)|(this.options.loose&&pVt))+":"+t,o=jje.get(n);if(o)return o;let i=this.options.loose,a=i?Qd[vd.HYPHENRANGELOOSE]:Qd[vd.HYPHENRANGE];t=t.replace(a,CVt(this.options.includePrerelease)),yi("hyphen replace",t),t=t.replace(Qd[vd.COMPARATORTRIM],lVt),yi("comparator trim",t),t=t.replace(Qd[vd.TILDETRIM],cVt),yi("tilde trim",t),t=t.replace(Qd[vd.CARETTRIM],dVt),yi("caret trim",t);let s=t.split(" ").map(d=>mVt(d,this.options)).join(" ").split(/\s+/).map(d=>xVt(d,this.options));i&&(s=s.filter(d=>(yi("loose invalid filter",d,this.options),!!d.match(Qd[vd.COMPARATORLOOSE])))),yi("range list",s);let u=new Map,l=s.map(d=>new Gae(d,this.options));for(let d of l){if(Nje(d))return[d];u.set(d.value,d)}u.size>1&&u.has("")&&u.delete("");let c=[...u.values()];return jje.set(n,c),c}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>Lje(n,r)&&t.set.some(o=>Lje(o,r)&&n.every(i=>o.every(a=>i.intersects(a,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new uVt(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",hVt=e=>e.value==="",Lje=(e,t)=>{let r=!0,n=e.slice(),o=n.pop();for(;r&&n.length;)r=n.every(i=>o.intersects(i,t)),o=n.pop();return r},mVt=(e,t)=>(yi("comp",e,t),e=bVt(e,t),yi("caret",e),e=gVt(e,t),yi("tildes",e),e=vVt(e,t),yi("xrange",e),e=SVt(e,t),yi("stars",e),e),wd=e=>!e||e.toLowerCase()==="x"||e==="*",gVt=(e,t)=>e.trim().split(/\s+/).map(r=>yVt(r,t)).join(" "),yVt=(e,t)=>{let r=t.loose?Qd[vd.TILDELOOSE]:Qd[vd.TILDE];return e.replace(r,(n,o,i,a,s)=>{yi("tilde",e,n,o,i,a,s);let u;return wd(o)?u="":wd(i)?u=`>=${o}.0.0 <${+o+1}.0.0-0`:wd(a)?u=`>=${o}.${i}.0 <${o}.${+i+1}.0-0`:s?(yi("replaceTilde pr",s),u=`>=${o}.${i}.${a}-${s} <${o}.${+i+1}.0-0`):u=`>=${o}.${i}.${a} <${o}.${+i+1}.0-0`,yi("tilde return",u),u})},bVt=(e,t)=>e.trim().split(/\s+/).map(r=>_Vt(r,t)).join(" "),_Vt=(e,t)=>{yi("caret",e,t);let r=t.loose?Qd[vd.CARETLOOSE]:Qd[vd.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(o,i,a,s,u)=>{yi("caret",e,o,i,a,s,u);let l;return wd(i)?l="":wd(a)?l=`>=${i}.0.0${n} <${+i+1}.0.0-0`:wd(s)?i==="0"?l=`>=${i}.${a}.0${n} <${i}.${+a+1}.0-0`:l=`>=${i}.${a}.0${n} <${+i+1}.0.0-0`:u?(yi("replaceCaret pr",u),i==="0"?a==="0"?l=`>=${i}.${a}.${s}-${u} <${i}.${a}.${+s+1}-0`:l=`>=${i}.${a}.${s}-${u} <${i}.${+a+1}.0-0`:l=`>=${i}.${a}.${s}-${u} <${+i+1}.0.0-0`):(yi("no pr"),i==="0"?a==="0"?l=`>=${i}.${a}.${s}${n} <${i}.${a}.${+s+1}-0`:l=`>=${i}.${a}.${s}${n} <${i}.${+a+1}.0-0`:l=`>=${i}.${a}.${s} <${+i+1}.0.0-0`),yi("caret return",l),l})},vVt=(e,t)=>(yi("replaceXRanges",e,t),e.split(/\s+/).map(r=>wVt(r,t)).join(" ")),wVt=(e,t)=>{e=e.trim();let r=t.loose?Qd[vd.XRANGELOOSE]:Qd[vd.XRANGE];return e.replace(r,(n,o,i,a,s,u)=>{yi("xRange",e,n,o,i,a,s,u);let l=wd(i),c=l||wd(a),d=c||wd(s),f=d;return o==="="&&f&&(o=""),u=t.includePrerelease?"-0":"",l?o===">"||o==="<"?n="<0.0.0-0":n="*":o&&f?(c&&(a=0),s=0,o===">"?(o=">=",c?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):o==="<="&&(o="<",c?i=+i+1:a=+a+1),o==="<"&&(u="-0"),n=`${o+i}.${a}.${s}${u}`):c?n=`>=${i}.0.0${u} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${u} <${i}.${+a+1}.0-0`),yi("xRange return",n),n})},SVt=(e,t)=>(yi("replaceStars",e,t),e.trim().replace(Qd[vd.STAR],"")),xVt=(e,t)=>(yi("replaceGTE0",e,t),e.trim().replace(Qd[t.includePrerelease?vd.GTE0PRE:vd.GTE0],"")),CVt=e=>(t,r,n,o,i,a,s,u,l,c,d,f)=>(wd(n)?r="":wd(o)?r=`>=${n}.0.0${e?"-0":""}`:wd(i)?r=`>=${n}.${o}.0${e?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,wd(l)?u="":wd(c)?u=`<${+l+1}.0.0-0`:wd(d)?u=`<${l}.${+c+1}.0-0`:f?u=`<=${l}.${c}.${d}-${f}`:e?u=`<${l}.${c}.${+d+1}-0`:u=`<=${u}`,`${r} ${u}`.trim()),OVt=(e,t,r)=>{for(let n=0;n0){let o=e[n].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}});var A$=b((uyn,zje)=>{var R$=Symbol("SemVer ANY"),Zae=class e{static get ANY(){return R$}constructor(t,r){if(r=kje(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Yae("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===R$?this.value="":this.value=this.operator+this.semver.version,Yae("comp",this)}parse(t){let r=this.options.loose?Bje[$je.COMPARATORLOOSE]:Bje[$je.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new qje(n[2],this.options.loose):this.semver=R$}toString(){return this.value}test(t){if(Yae("Comparator.test",t,this.options.loose),this.semver===R$||t===R$)return!0;if(typeof t=="string")try{t=new qje(t,this.options)}catch{return!1}return Kae(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Uje(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Uje(this.value,r).test(t.semver):(r=kje(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Kae(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Kae(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};zje.exports=Zae;var kje=k6(),{safeRe:Bje,t:$je}=OD(),Kae=Vae(),Yae=M$(),qje=Rc(),Uje=Zp()});var D$=b((lyn,Hje)=>{var EVt=Zp(),PVt=(e,t,r)=>{try{t=new EVt(t,r)}catch{return!1}return t.test(e)};Hje.exports=PVt});var Wje=b((cyn,Vje)=>{var TVt=Zp(),MVt=(e,t)=>new TVt(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));Vje.exports=MVt});var Gje=b((dyn,Jje)=>{var IVt=Rc(),AVt=Zp(),RVt=(e,t,r)=>{let n=null,o=null,i=null;try{i=new AVt(t,r)}catch{return null}return e.forEach(a=>{i.test(a)&&(!n||o.compare(a)===-1)&&(n=a,o=new IVt(n,r))}),n};Jje.exports=RVt});var Yje=b((fyn,Kje)=>{var DVt=Rc(),jVt=Zp(),NVt=(e,t,r)=>{let n=null,o=null,i=null;try{i=new jVt(t,r)}catch{return null}return e.forEach(a=>{i.test(a)&&(!n||o.compare(a)===1)&&(n=a,o=new DVt(n,r))}),n};Kje.exports=NVt});var Qje=b((pyn,Xje)=>{var Xae=Rc(),LVt=Zp(),Zje=I$(),FVt=(e,t)=>{e=new LVt(e,t);let r=new Xae("0.0.0");if(e.test(r)||(r=new Xae("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let s=new Xae(a.semver.version);switch(a.operator){case">":s.prerelease.length===0?s.patch++:s.prerelease.push(0),s.raw=s.format();case"":case">=":(!i||Zje(s,i))&&(i=s);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),i&&(!r||Zje(r,i))&&(r=i)}return r&&e.test(r)?r:null};Xje.exports=FVt});var tNe=b((hyn,eNe)=>{var kVt=Zp(),BVt=(e,t)=>{try{return new kVt(e,t).range||"*"}catch{return null}};eNe.exports=BVt});var J6=b((myn,iNe)=>{var $Vt=Rc(),oNe=A$(),{ANY:qVt}=oNe,UVt=Zp(),zVt=D$(),rNe=I$(),nNe=U6(),HVt=H6(),VVt=z6(),WVt=(e,t,r,n)=>{e=new $Vt(e,n),t=new UVt(t,n);let o,i,a,s,u;switch(r){case">":o=rNe,i=HVt,a=nNe,s=">",u=">=";break;case"<":o=nNe,i=VVt,a=rNe,s="<",u="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(zVt(e,t,n))return!1;for(let l=0;l{p.semver===qVt&&(p=new oNe(">=0.0.0")),d=d||p,f=f||p,o(p.semver,d.semver,n)?d=p:a(p.semver,f.semver,n)&&(f=p)}),d.operator===s||d.operator===u||(!f.operator||f.operator===s)&&i(e,f.semver))return!1;if(f.operator===u&&a(e,f.semver))return!1}return!0};iNe.exports=WVt});var sNe=b((gyn,aNe)=>{var JVt=J6(),GVt=(e,t,r)=>JVt(e,t,">",r);aNe.exports=GVt});var lNe=b((yyn,uNe)=>{var KVt=J6(),YVt=(e,t,r)=>KVt(e,t,"<",r);uNe.exports=YVt});var fNe=b((byn,dNe)=>{var cNe=Zp(),ZVt=(e,t,r)=>(e=new cNe(e,r),t=new cNe(t,r),e.intersects(t,r));dNe.exports=ZVt});var hNe=b((_yn,pNe)=>{var XVt=D$(),QVt=Yp();pNe.exports=(e,t,r)=>{let n=[],o=null,i=null,a=e.sort((c,d)=>QVt(c,d,r));for(let c of a)XVt(c,t,r)?(i=c,o||(o=c)):(i&&n.push([o,i]),i=null,o=null);o&&n.push([o,null]);let s=[];for(let[c,d]of n)c===d?s.push(c):!d&&c===a[0]?s.push("*"):d?c===a[0]?s.push(`<=${d}`):s.push(`${c} - ${d}`):s.push(`>=${c}`);let u=s.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return u.length{var mNe=Zp(),ese=A$(),{ANY:Qae}=ese,j$=D$(),tse=Yp(),e5t=(e,t,r={})=>{if(e===t)return!0;e=new mNe(e,r),t=new mNe(t,r);let n=!1;e:for(let o of e.set){for(let i of t.set){let a=r5t(o,i,r);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},t5t=[new ese(">=0.0.0-0")],gNe=[new ese(">=0.0.0")],r5t=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Qae){if(t.length===1&&t[0].semver===Qae)return!0;r.includePrerelease?e=t5t:e=gNe}if(t.length===1&&t[0].semver===Qae){if(r.includePrerelease)return!0;t=gNe}let n=new Set,o,i;for(let p of e)p.operator===">"||p.operator===">="?o=yNe(o,p,r):p.operator==="<"||p.operator==="<="?i=bNe(i,p,r):n.add(p.semver);if(n.size>1)return null;let a;if(o&&i){if(a=tse(o.semver,i.semver,r),a>0)return null;if(a===0&&(o.operator!==">="||i.operator!=="<="))return null}for(let p of n){if(o&&!j$(p,String(o),r)||i&&!j$(p,String(i),r))return null;for(let h of t)if(!j$(p,String(h),r))return!1;return!0}let s,u,l,c,d=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,f=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&i.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of t){if(c=c||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",o){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(s=yNe(o,p,r),s===p&&s!==o)return!1}else if(o.operator===">="&&!j$(o.semver,String(p),r))return!1}if(i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(u=bNe(i,p,r),u===p&&u!==i)return!1}else if(i.operator==="<="&&!j$(i.semver,String(p),r))return!1}if(!p.operator&&(i||o)&&a!==0)return!1}return!(o&&l&&!i&&a!==0||i&&c&&!o&&a!==0||f||d)},yNe=(e,t,r)=>{if(!e)return t;let n=tse(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},bNe=(e,t,r)=>{if(!e)return t;let n=tse(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};_Ne.exports=e5t});var CNe=b((wyn,xNe)=>{var rse=OD(),wNe=T$(),n5t=Rc(),SNe=qae(),o5t=AM(),i5t=GDe(),a5t=YDe(),s5t=QDe(),u5t=rje(),l5t=oje(),c5t=aje(),d5t=uje(),f5t=cje(),p5t=Yp(),h5t=hje(),m5t=gje(),g5t=q6(),y5t=vje(),b5t=Sje(),_5t=I$(),v5t=U6(),w5t=zae(),S5t=Hae(),x5t=z6(),C5t=H6(),O5t=Vae(),E5t=Aje(),P5t=A$(),T5t=Zp(),M5t=D$(),I5t=Wje(),A5t=Gje(),R5t=Yje(),D5t=Qje(),j5t=tNe(),N5t=J6(),L5t=sNe(),F5t=lNe(),k5t=fNe(),B5t=hNe(),$5t=vNe();xNe.exports={parse:o5t,valid:i5t,clean:a5t,inc:s5t,diff:u5t,major:l5t,minor:c5t,patch:d5t,prerelease:f5t,compare:p5t,rcompare:h5t,compareLoose:m5t,compareBuild:g5t,sort:y5t,rsort:b5t,gt:_5t,lt:v5t,eq:w5t,neq:S5t,gte:x5t,lte:C5t,cmp:O5t,coerce:E5t,Comparator:P5t,Range:T5t,satisfies:M5t,toComparators:I5t,maxSatisfying:A5t,minSatisfying:R5t,minVersion:D5t,validRange:j5t,outside:N5t,gtr:L5t,ltr:F5t,intersects:k5t,simplifyRange:B5t,subset:$5t,SemVer:n5t,re:rse.re,src:rse.src,tokens:rse.t,SEMVER_SPEC_VERSION:wNe.SEMVER_SPEC_VERSION,RELEASE_TYPES:wNe.RELEASE_TYPES,compareIdentifiers:SNe.compareIdentifiers,rcompareIdentifiers:SNe.rcompareIdentifiers}});function gS(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);let[t,r]=e.split(":"),n=r||"latest";if(t.includes("/")){let[o,i]=t.split("/",2);if(!o||!i)throw new Error(`Invalid identifier format: ${e}`);return[o,i,n]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,n]}}var q5t,ONe=C(()=>{q5t=B(CNe(),1)});async function qr(e,t,r){let n;if(e.ok){r&&(n=await e.text());return}n=await e.text();let o=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Server response: ${n}`;throw e.status===409?new nse(o):new Error(o)}var nse,ENe=C(()=>{nse=class extends Error{constructor(t){super(t),this.name="LangSmithConflictError"}}});function z5t(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function ef(e,t,r,n){try{return JSON.stringify(e,t,r)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."),"[Unserializable]";console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."),typeof n>"u"&&(n=z5t()),ise(e,"",0,[],void 0,0,n);var o;try{PD.length===0?o=JSON.stringify(e,t,r):o=JSON.stringify(e,H5t(t),r)}catch{return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;G6.length!==0;){var i=G6.pop();i.length===4?Object.defineProperty(i[0],i[1],i[3]):i[0][i[1]]=i[2]}}return o}}function ose(e,t,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:e}),G6.push([n,r,t,o])):PD.push([t,r,e]):(n[r]=e,G6.push([n,r,t]))}function ise(e,t,r,n,o,i,a){i+=1;var s;if(typeof e=="object"&&e!==null){for(s=0;sa.depthLimit){ose(PNe,e,t,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){ose(PNe,e,t,o);return}if(n.push(e),Array.isArray(e))for(s=0;s0)for(var n=0;n{PNe="[...]",U5t={result:"[Circular]"},G6=[],PD=[]});function MNe(e){let t=Z6(),r=INe(),n=e.extra??{},o=n.metadata;return e.extra={...n,runtime:{...t,...n?.runtime},metadata:{...r,...r.revision_id||e.revision_id?{revision_id:e.revision_id??r.revision_id}:{},...o}},e}async function J5t(e){let t=[];for await(let r of e)t.push(r);return t}function ase(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}var V5t,W5t,G5t,sse,K5t,Y5t,RM,use=C(()=>{M6();IDe();ADe();X6();Y6();RDe();kae();ONe();ENe();N6();TNe();V5t=()=>{let e=yS("TRACING_SAMPLING_RATE");if(e===void 0)return;let t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},W5t=e=>{let r=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};G5t=async e=>{if(e?.status===429){let t=parseInt(e.headers.get("retry-after")??"30",10)*1e3;if(t>0)return await new Promise(r=>setTimeout(r,t)),!0}return!1},sse=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let r,n=new Promise(i=>{r=i}),o=ef(t.item).length;return this.items.push({action:t.action,payload:t.item,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n}pop(t){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],n=0;for(;n+(this.peek()?.size??0)0;){let o=this.items.shift();o&&(r.push(o),n+=o.size,this.sizeBytes-=o.size)}if(r.length===0&&this.items.length>0){let o=this.items.shift();r.push(o),n+=o.size,this.sizeBytes-=o.size}return[r.map(o=>({action:o.action,item:o.payload})),()=>r.forEach(o=>o.itemPromiseResolve())]}},K5t=20971520,Y5t=2500,RM=class e{constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new sse}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:ey("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1});let r=e.getDefaultClientConfig();if(this.tracingSampleRate=V5t(),this.apiUrl=ase(t.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=ase(t.apiKey??r.apiKey),this.webUrl=ase(t.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.timeout_ms=t.timeout_ms??9e4,this.caller=new P$(t.callerOptions??{}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.batchIngestCaller=new P$({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:G5t}),this.hideInputs=t.hideInputs??t.anonymizer??r.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??r.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode}static getDefaultClientConfig(){let t=yS("API_KEY"),r=yS("ENDPOINT")??"https://api.smith.langchain.com",n=yS("HIDE_INPUTS")==="true",o=yS("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:t,webUrl:void 0,hideInputs:n,hideOutputs:o}}getHostUrl(){return this.webUrl?this.webUrl:W5t(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let t={"User-Agent":`langsmith-js/${K6}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),t}processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}prepareRunCreateOrUpdateInputs(t){let r={...t};return r.inputs!==void 0&&(r.inputs=this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=this.processOutputs(r.outputs)),r}async _getResponse(t,r){let n=r?.toString()??"",o=`${this.apiUrl}${t}?${n}`,i=await this.caller.call(wt(),o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(i,`Failed to fetch ${t}`),i}async _get(t,r){return(await this._getResponse(t,r)).json()}async*_getPaginated(t,r=new URLSearchParams,n){let o=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(o)),r.set("limit",String(i));let a=`${this.apiUrl}${t}?${r}`,s=await this.caller.call(wt(),a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(s,`Failed to fetch ${t}`);let u=n?n(await s.json()):await s.json();if(u.length===0||(yield u,u.length0;){let[n,o]=this.autoBatchQueue.pop(t);if(!n.length){o();break}let i=this._processBatch(n,o).catch(console.error);r.push(i)}return Promise.all(r)}async _processBatch(t,r){if(!t.length){r();return}try{let n={runCreates:t.filter(i=>i.action==="create").map(i=>i.item),runUpdates:t.filter(i=>i.action==="update").map(i=>i.item)};(await this._ensureServerInfo())?.batch_ingest_config?.use_multipart_endpoint?await this.multipartIngestRuns(n):await this.batchIngestRuns(n)}finally{r()}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.action==="create"&&(t.item=MNe(t.item));let r=this.autoBatchQueue.push(t);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes();return this.autoBatchQueue.sizeBytes>n&&this.drainAutoBatchQueue(n),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue(n)},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let t=await wt()(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Y5t),...this.fetchOptions});return await qr(t,"get server info"),t.json()}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let t=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(t)}async createRun(t){if(!this._filterForSampling([t]).length)return;let r={...this.headers,"Content-Type":"application/json"},n=t.project_name;delete t.project_name;let o=this.prepareRunCreateOrUpdateInputs({session_name:n,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){this.processRunOperation({action:"create",item:o}).catch(console.error);return}let i=MNe(o),a=await this.caller.call(wt(),`${this.apiUrl}/runs`,{method:"POST",headers:r,body:ef(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(a,"create run",!0)}async batchIngestRuns({runCreates:t,runUpdates:r}){if(t===void 0&&r===void 0)return;let n=t?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[],o=r?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[];if(n.length>0&&o.length>0){let s=n.reduce((l,c)=>(c.id&&(l[c.id]=c),l),{}),u=[];for(let l of o)l.id!==void 0&&s[l.id]?s[l.id]={...s[l.id],...l}:u.push(l);n=Object.values(s),o=u}let i={post:this._filterForSampling(n),patch:this._filterForSampling(o,!0)};if(!i.post.length&&!i.patch.length)return;let a={post:[],patch:[]};for(let s of["post","patch"]){let u=s,l=i[u].reverse(),c=l.pop();for(;c!==void 0;)a[u].push(c),c=l.pop()}(a.post.length>0||a.patch.length>0)&&await this._postBatchIngestRuns(ef(a))}async _postBatchIngestRuns(t){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(wt(),`${this.apiUrl}/runs/batch`,{method:"POST",headers:r,body:t,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(n,"batch create run",!0)}async multipartIngestRuns({runCreates:t,runUpdates:r}){if(t===void 0&&r===void 0)return;let n={},o=[];for(let c of t??[]){let d=this.prepareRunCreateOrUpdateInputs(c);d.id!==void 0&&d.attachments!==void 0&&(n[d.id]=d.attachments),delete d.attachments,o.push(d)}let i=[];for(let c of r??[])i.push(this.prepareRunCreateOrUpdateInputs(c));if(o.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(o.length>0&&i.length>0){let c=o.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),d=[];for(let f of i)f.id!==void 0&&c[f.id]?c[f.id]={...c[f.id],...f}:d.push(f);o=Object.values(c),i=d}if(o.length===0&&i.length===0)return;let u=[],l=[];for(let[c,d]of[["post",o],["patch",i]])for(let f of d){let{inputs:p,outputs:h,events:m,attachments:_,...g}=f,v={inputs:p,outputs:h,events:m},S=ef(g);l.push({name:`${c}.${g.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[x,O]of Object.entries(v)){if(O===void 0)continue;let T=ef(O);l.push({name:`${c}.${g.id}.${x}`,payload:new Blob([T],{type:`application/json; length=${T.length}`})})}if(g.id!==void 0){let x=n[g.id];if(x){delete n[g.id];for(let[O,T]of Object.entries(x)){let E,M;if(Array.isArray(T)?[E,M]=T:(E=T.mimeType,M=T.data),O.includes(".")){console.warn(`Skipping attachment '${O}' for run ${g.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${g.id}.${O}`,payload:new Blob([M],{type:`${E}; length=${M.byteLength}`})})}}}u.push(`trace=${g.trace_id},id=${g.id}`)}await this._sendMultipartRequest(l,u.join("; "))}async _sendMultipartRequest(t,r){try{let n="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),o=[];for(let u of t)o.push(new Blob([`--${n}\r +`])),o.push(new Blob([`Content-Disposition: form-data; name="${u.name}"\r +`,`Content-Type: ${u.payload.type}\r \r -` - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); - } - chunks.push(new Blob([`--${boundary}--\r -`])); - const body = new Blob(chunks); - const arrayBuffer = await body.arrayBuffer(); - const res = await this.batchIngestCaller.call(_getFetchImplementation(), `${this.apiUrl}/runs/multipart`, { - method: "POST", - headers: { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}` - }, - body: arrayBuffer, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(res, "ingest multipart runs", true); - } catch (e3) { - console.warn(`${e3.message.trim()} +`])),o.push(u.payload),o.push(new Blob([`\r +`]));o.push(new Blob([`--${n}--\r +`]));let a=await new Blob(o).arrayBuffer(),s=await this.batchIngestCaller.call(wt(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`},body:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(s,"ingest multipart runs",!0)}catch(n){console.warn(`${n.message.trim()} -Context: ${context}`); - } - } - async updateRun(runId, run) { - assertUuid(runId); - if (run.inputs) { - run.inputs = this.processInputs(run.inputs); - } - if (run.outputs) { - run.outputs = this.processOutputs(run.outputs); - } - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; - } - if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) { - if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) { - await this.processRunOperation({ action: "update", item: data }).catch(console.error); - return; - } else { - void this.processRunOperation({ action: "update", item: data }).catch(console.error); - } - return; - } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - body: stringify(run), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update run", true); - } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns && run.child_run_ids) { - run = await this._loadChildRuns(run); - } - return run; - } - async getRunUrl({ runId, run, projectOpts }) { - if (run !== void 0) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default" - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; - } else if (runId !== void 0) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; - } else { - throw new Error("Must provide either runId or run"); - } - } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); - const treemap = {}; - const runs = {}; - childRuns.sort((a3, b3) => (a3?.dotted_order ?? "").localeCompare(b3?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; - } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } - } - return run; - } - /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * 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: "", - * 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: "", - * 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: "", - * 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: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); - */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter: filter2, traceFilter, treeFilter, limit: limit2, select } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; - } - if (projectName) { - const projectNames = Array.isArray(projectName) ? projectName : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); - } - const default_select = [ - "app_path", - "child_run_ids", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id" - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter: filter2, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit: limit2, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot - }; - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit2) { - if (runsYielded >= limit2) { - break; - } - if (runs.length + runsYielded > limit2) { - const newRuns = runs.slice(0, limit2 - runsYielded); - yield* newRuns; - break; - } - runsYielded += runs.length; - yield* runs; - } else { - yield* runs; - } - } - } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter: filter2, traceFilter, treeFilter, isRoot, dataSourceType }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...projectIds || [], - ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))) - ]; - } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter: filter2, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType - }; - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_2, value]) => value !== void 0)); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/stats`, { - method: "POST", - headers: this.headers, - body: JSON.stringify(filteredPayload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const result = await response.json(); - return result; - } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || v4_default2() - }; - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async unshareRun(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "unshare run", true); - } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return void 0; - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async listSharedRuns(shareToken, { runIds } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken - }); - if (runIds !== void 0) { - for (const runId of runIds) { - queryParams.append("id", runId); - } - } - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const runs = await response.json(); - return runs; - } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - const data = { - dataset_id: datasetId - }; - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async unshareDataset(datasetId) { - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "unshare dataset", true); - } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const dataset = await response.json(); - return dataset; - } - /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. - */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; - } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v5) => urlParams.append(key, v5)); - } else { - urlParams.append(key, value); - } - }); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples. -Status: ${response.status} -Message: ${result.detail.join("\n")}`); - } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); - } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl() - })); - } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; - } - const body = { - name: projectName, - extra, - description - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; - } - const response = await this.caller.call(_getFetchImplementation(), endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create project"); - const result = await response.json(); - return result; - } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...extra || {}, metadata }; - } - const body = { - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null - }; - const response = await this.caller.call(_getFetchImplementation(), endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update project"); - const result = await response.json(); - return result; - } - async hasProject({ projectId, projectName }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== void 0 && projectName !== void 0) { - throw new Error("Must provide either projectName or projectId, not both"); - } else if (projectId !== void 0) { - assertUuid(projectId); - path += `/${projectId}`; - } else if (projectName !== void 0) { - params.append("name", projectName); - } else { - throw new Error("Must provide projectName or projectId"); - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${path}?${params}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - try { - const result = await response.json(); - if (!response.ok) { - return false; - } - if (Array.isArray(result)) { - return result.length > 0; - } - return true; - } catch (e3) { - return false; - } - } - async readProject({ projectId, projectName, includeStats }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== void 0 && projectName !== void 0) { - throw new Error("Must provide either projectName or projectId, not both"); - } else if (projectId !== void 0) { - assertUuid(projectId); - path += `/${projectId}`; - } else if (projectName !== void 0) { - params.append("name", projectName); - } else { - throw new Error("Must provide projectName or projectId"); - } - if (includeStats !== void 0) { - params.append("include_stats", includeStats.toString()); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); - } - result = response[0]; - } else { - result = response; - } - return result; - } - async getProjectUrl({ projectId, projectName }) { - if (projectId === void 0 && projectName === void 0) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; - } - async getDatasetUrl({ datasetId, datasetName }) { - if (datasetId === void 0 && datasetName === void 0) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; - } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; - } - throw new Error("No projects found to resolve tenant."); - } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata } = {}) { - const params = new URLSearchParams(); - if (projectIds !== void 0) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== void 0) { - params.append("name", name); - } - if (nameContains !== void 0) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== void 0) { - params.append("reference_dataset", referenceDatasetId); - } else if (referenceDatasetName !== void 0) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName - }); - params.append("reference_dataset", dataset.id); - } - if (referenceFree !== void 0) { - params.append("reference_free", referenceFree.toString()); - } - if (metadata !== void 0) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; - } - } - async deleteProject({ projectId, projectName }) { - let projectId_; - if (projectId === void 0 && projectName === void 0) { - throw new Error("Must provide projectName or projectId"); - } else if (projectId !== void 0 && projectName !== void 0) { - throw new Error("Must provide either projectName or projectId, not both"); - } else if (projectId === void 0) { - projectId_ = (await this.readProject({ projectName })).id; - } else { - projectId_ = projectId; - } - assertUuid(projectId_); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); - } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); - } - if (dataType) { - formData.append("data_type", dataType); - } - if (name) { - formData.append("name", name); - } - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "POST", - headers: this.headers, - body: formData, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "upload CSV"); - const result = await response.json(); - return result; - } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : void 0 - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create dataset"); - const result = await response.json(); - return result; - } - async readDataset({ datasetId, datasetName }) { - let path = "/datasets"; - const params = new URLSearchParams({ limit: "1" }); - if (datasetId !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId !== void 0) { - assertUuid(datasetId); - path += `/${datasetId}`; - } else if (datasetName !== void 0) { - params.append("name", datasetName); - } else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); - } - result = response[0]; - } else { - result = response; - } - return result; - } - async hasDataset({ datasetId, datasetName }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; - } catch (e3) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e3 instanceof Error && e3.message.toLocaleLowerCase().includes("not found") - ) { - return false; - } - throw e3; - } - } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) { - let datasetId_ = datasetId; - if (datasetId_ === void 0 && datasetName === void 0) { - throw new Error("Must provide either datasetName or datasetId"); - } else if (datasetId_ !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId_ === void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString() - }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; - } - async readDatasetOpenaiFinetuning({ datasetId, datasetName }) { - const path = "/datasets"; - if (datasetId !== void 0) { - } else if (datasetName !== void 0) { - datasetId = (await this.readDataset({ datasetName })).id; - } else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line)); - return dataset; - } - async *listDatasets({ limit: limit2 = 100, offset: offset5 = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit2.toString(), - offset: offset5.toString() - }); - if (datasetIds !== void 0) { - for (const id_ of datasetIds) { - params.append("id", id_); - } - } - if (datasetName !== void 0) { - params.append("name", datasetName); - } - if (datasetNameContains !== void 0) { - params.append("name_contains", datasetNameContains); - } - if (metadata !== void 0) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; - } - } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update2 } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${_datasetId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update2), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update dataset"); - return await response.json(); - } - async deleteDataset({ datasetId, datasetName }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetName !== void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== void 0) { - assertUuid(datasetId_); - path += `/${datasetId_}`; - } else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); - } - async indexDataset({ datasetId, datasetName, tag }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - assertUuid(datasetId_); - const data = { - tag - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "index dataset"); - await response.json(); - } - /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) - */ - async similarExamples(inputs, datasetId, limit2, { filter: filter2 } = {}) { - const data = { - limit: limit2, - inputs - }; - if (filter2 !== void 0) { - data["filter"] = filter2; - } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId}/search`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "fetch similar examples"); - const result = await response.json(); - return result["examples"]; - } - async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, split, sourceRunId }) { - let datasetId_ = datasetId; - if (datasetId_ === void 0 && datasetName === void 0) { - throw new Error("Must provide either datasetName or datasetId"); - } else if (datasetId_ !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId_ === void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const createdAt_ = createdAt || new Date(); - const data = { - dataset_id: datasetId_, - inputs, - outputs, - created_at: createdAt_?.toISOString(), - id: exampleId, - metadata, - split, - source_run_id: sourceRunId - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create example"); - const result = await response.json(); - return result; - } - async createExamples(props) { - const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName } = props; - let datasetId_ = datasetId; - if (datasetId_ === void 0 && datasetName === void 0) { - throw new Error("Must provide either datasetName or datasetId"); - } else if (datasetId_ !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId_ === void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs ? outputs[idx] : void 0, - metadata: metadata ? metadata[idx] : void 0, - split: props.splits ? props.splits[idx] : void 0, - id: exampleIds ? exampleIds[idx] : void 0, - source_run_id: sourceRunIds ? sourceRunIds[idx] : void 0 - }; - }); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/bulk`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(formattedExamples), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create examples"); - const result = await response.json(); - return result; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; - }); - const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); - } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url - }; - return acc; - }, {}); - } - return example; - } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit: limit2, offset: offset5, filter: filter2, includeAttachments } = {}) { - let datasetId_; - if (datasetId !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId !== void 0) { - datasetId_ = datasetId; - } else if (datasetName !== void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } else { - throw new Error("Must provide a datasetName or datasetId"); - } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== void 0) { - for (const id_ of exampleIds) { - params.append("id", id_); - } - } - if (splits !== void 0) { - for (const split of splits) { - params.append("splits", split); - } - } - if (metadata !== void 0) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); - } - if (limit2 !== void 0) { - params.append("limit", limit2.toString()); - } - if (offset5 !== void 0) { - params.append("offset", offset5.toString()); - } - if (filter2 !== void 0) { - params.append("filter", filter2); - } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); - } - let i3 = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url - }; - return acc; - }, {}); - } - yield example; - i3++; - } - if (limit2 !== void 0 && i3 >= limit2) { - break; - } - } - } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); - } - async updateExample(exampleId, update2) { - assertUuid(exampleId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/${exampleId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update2), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update example"); - const result = await response.json(); - return result; - } - async updateExamples(update2) { - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/examples/bulk`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update2), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update examples"); - const result = await response.json(); - return result; - } - async listDatasetSplits({ datasetId, datasetName, asOf }) { - let datasetId_; - if (datasetId === void 0 && datasetName === void 0) { - throw new Error("Must provide dataset name or ID"); - } else if (datasetId !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId === void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; - } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove: remove6 = false }) { - let datasetId_; - if (datasetId === void 0 && datasetName === void 0) { - throw new Error("Must provide dataset name or ID"); - } else if (datasetId !== void 0 && datasetName !== void 0) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } else if (datasetId === void 0) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove: remove6 - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update dataset splits", true); - } - /** - * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. - */ - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) { - warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); - } else if (typeof run === "object" && "id" in run) { - run_ = run; - } else { - throw new Error(`Invalid run type: ${typeof run}`); - } - if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) { - referenceExample = await this.readExample(run_.reference_example_id); - } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - const [_2, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); - return feedbacks[0]; - } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); - } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); - } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {} - }; - if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; - } - if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) { - assertUuid(feedback_source.metadata["__run"].run_id); - } - const feedback = { - id: feedbackId ?? v4_default2(), - run_id: runId, - key, - score, - value, - correction, - comment, - feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId - }; - const url = `${this.apiUrl}/feedback`; - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedback), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create feedback", true); - return feedback; - } - async updateFeedback(feedbackId, { score, value, correction, comment }) { - const feedbackUpdate = {}; - if (score !== void 0 && score !== null) { - feedbackUpdate["score"] = score; - } - if (value !== void 0 && value !== null) { - feedbackUpdate["value"] = value; - } - if (correction !== void 0 && correction !== null) { - feedbackUpdate["correction"] = correction; - } - if (comment !== void 0 && comment !== null) { - feedbackUpdate["comment"] = comment; - } - assertUuid(feedbackId); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedbackUpdate), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update feedback", true); - } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; - } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this.caller.call(_getFetchImplementation(), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); - } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - queryParams.append("run", runIds.join(",")); - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } - } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } - } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; - } - } - /** - * Creates a presigned feedback token and URL. - * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. - * - * @param runId - The ID of the run. - * @param feedbackKey - The feedback key. - * @param options - Additional options for the token. - * @param options.expiration - The expiration time for the token. - * - * @returns A promise that resolves to a FeedbackIngestToken. - */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; - } else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; - } - } else { - body["expires_in"] = { - hours: 3 - }; - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - const result = await response.json(); - return result; - } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); - } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0] - })).reference_dataset_id; - } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); - } - const body = { - id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {} - }; - if (metadata) - body.extra["metadata"] = metadata; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - return await response.json(); - } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; - } - } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; - } else { - results_ = [results]; - } - return results_; - } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; - } else if (run) { - runId_ = run.id; - } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model" - })); - } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; - } - /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects - */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit: limit2 } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i3) => { - assertUuid(id, `queueIds[${i3}]`); - params.append("ids", id); - }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit2 !== void 0 ? Math.min(limit2, 100) : 100).toString()); - let count5 = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count5++; - if (limit2 !== void 0 && count5 >= limit2) - break; - } - } - /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object - */ - async createAnnotationQueue(options) { - const { name, description, queueId } = options; - const body = { - name, - description, - id: queueId || v4_default2() - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_2, v5]) => v5 !== void 0))), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create annotation queue"); - const data = await response.json(); - return data; - } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueue object - */ - async readAnnotationQueue(queueId) { - const queueIteratorResult = await this.listAnnotationQueues({ - queueIds: [queueId] - }).next(); - if (queueIteratorResult.done) { - throw new Error(`Annotation queue with ID ${queueId} not found`); - } - return queueIteratorResult.value; - } - /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue - */ - async updateAnnotationQueue(queueId, options) { - const { name, description } = options; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ name, description }), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update annotation queue"); - } - /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete - */ - async deleteAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "delete annotation queue"); - } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(runIds.map((id, i3) => assertUuid(id, `runIds[${i3}]`).toString())), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "add runs to annotation queue"); - } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index2) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}${baseUrl}/${index2}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "get run from annotation queue"); - return await response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; - } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant. +Context: ${r}`)}}async updateRun(t,r){en(t),r.inputs&&(r.inputs=this.processInputs(r.inputs)),r.outputs&&(r.outputs=this.processOutputs(r.outputs));let n={...r,id:t};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(r.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}let o={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(wt(),`${this.apiUrl}/runs/${t}`,{method:"PATCH",headers:o,body:ef(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,"update run",!0)}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){en(t);let n=await this._get(`/runs/${t}`);return r&&n.child_run_ids&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:yS("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}else if(t!==void 0){let o=await this.readRun(t);if(!o.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await J5t(this.listRuns({id:t.child_run_ids})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i}t.child_runs=n[t.id]||[];for(let i in n)i!==t.id&&(o[i].child_runs=n[i]);return t}async*listRuns(t){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:h,traceFilter:m,treeFilter:_,limit:g,select:v}=t,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],M=await Promise.all(E.map(A=>this.readProject({projectName:A}).then(j=>j.id)));S.push(...M)}let x=["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"],O={session:S.length?S:null,run_type:c,reference_example:a,query:p,filter:h,trace_filter:m,tree_filter:_,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:v||x,is_root:l},T=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(T>=g)break;if(E.length+T>g){yield*E.slice(0,g-T);break}T+=E.length,yield*E}else yield*E}async getRunStats({id:t,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:m,dataSourceType:_}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(T=>this.readProject({projectName:T}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:m,data_source_type:_}).filter(([T,E])=>E!==void 0));return await(await this.caller.call(wt(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||dO()};en(t);let i=await(await this.caller.call(wt(),`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(t){en(t);let r=await this.caller.call(wt(),`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(r,"unshare run",!0)}async readRunSharedLink(t){en(t);let n=await(await this.caller.call(wt(),`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(t,{runIds:r}={}){let n=new URLSearchParams({share_token:t});if(r!==void 0)for(let a of r)n.append("id",a);return en(t),await(await this.caller.call(wt(),`${this.apiUrl}/public/${t}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async readDatasetSharedSchema(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id),en(t);let o=await(await this.caller.call(wt(),`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async shareDataset(t,r){if(!t&&!r)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:r})).id);let n={dataset_id:t};en(t);let i=await(await this.caller.call(wt(),`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(t){en(t);let r=await this.caller.call(wt(),`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(r,"unshare dataset",!0)}async readSharedDataset(t){return en(t),await(await this.caller.call(wt(),`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async listSharedExamples(t,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let o=new URLSearchParams;Object.entries(n).forEach(([s,u])=>{Array.isArray(u)?u.forEach(l=>o.append(s,l)):o.append(s,u)});let i=await this.caller.call(wt(),`${this.apiUrl}/public/${t}/examples?${o.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples. +Status: ${i.status} +Message: ${a.detail.join(` +`)}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:t,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=await this.caller.call(wt(),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(d,"create project"),await d.json()}async updateProject(t,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${t}`,u=i;o&&(u={...u||{},metadata:o});let l={name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null},c=await this.caller.call(wt(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(c,"update project"),await c.json()}async hasProject({projectId:t,projectName:r}){let n="/sessions",o=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)en(t),n+=`/${t}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(wt(),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)en(t),o+=`/${t}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${t}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:t,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:t,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(t!==void 0)for(let l of t)u.append("id",l);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let l=await this.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void 0&&u.append("reference_free",a.toString()),s!==void 0&&u.append("metadata",JSON.stringify(s));for await(let l of this._getPaginated("/sessions",u))yield*l}async deleteProject({projectId:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,en(n);let o=await this.caller.call(wt(),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(o,`delete session ${n} (${r})`,!0)}async uploadCsv({csvFile:t,fileName:r,inputKeys:n,outputKeys:o,description:i,dataType:a,name:s}){let u=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",t,r),n.forEach(f=>{l.append("input_keys",f)}),o.forEach(f=>{l.append("output_keys",f)}),i&&l.append("description",i),a&&l.append("data_type",a),s&&l.append("name",s);let c=await this.caller.call(wt(),u,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(c,"upload CSV"),await c.json()}async createDataset(t,{description:r,dataType:n,inputsSchema:o,outputsSchema:i,metadata:a}={}){let s={name:t,description:r,extra:a?{metadata:a}:void 0};n&&(s.data_type=n),o&&(s.inputs_schema_definition=o),i&&(s.outputs_schema_definition=i);let u=await this.caller.call(wt(),`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(u,"create dataset"),await u.json()}async readDataset({datasetId:t,datasetName:r}){let n="/datasets",o=new URLSearchParams({limit:"1"});if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)en(t),n+=`/${t}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(n,o),a;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${t}, name=${r}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:t,datasetName:r}){try{return await this.readDataset({datasetId:t,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:t,datasetName:r,fromVersion:n,toVersion:o}){let i=t;if(i===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:r})).id);let a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof o=="string"?o:o.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:r}){let n="/datasets";if(t===void 0)if(r!==void 0)t=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide datasetName or datasetId");return(await(await this._getResponse(`${n}/${t}/openai_ft`)).text()).trim().split(` +`).map(s=>JSON.parse(s))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:t.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(t){let{datasetId:r,datasetName:n,...o}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;en(i);let a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"update dataset"),await a.json()}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",o=t;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)en(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(wt(),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,`delete ${n}`),await i.json()}async indexDataset({datasetId:t,datasetName:r,tag:n}){let o=t;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),en(o);let i={tag:n},a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(a,"index dataset"),await a.json()}async similarExamples(t,r,n,{filter:o}={}){let i={limit:n,inputs:t};o!==void 0&&(i.filter=o),en(r);let a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"fetch similar examples"),(await a.json()).examples}async createExample(t,r,{datasetId:n,datasetName:o,createdAt:i,exampleId:a,metadata:s,split:u,sourceRunId:l}){let c=n;if(c===void 0&&o===void 0)throw new Error("Must provide either datasetName or datasetId");if(c!==void 0&&o!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");c===void 0&&(c=(await this.readDataset({datasetName:o})).id);let f={dataset_id:c,inputs:t,outputs:r,created_at:(i||new Date)?.toISOString(),id:a,metadata:s,split:u,source_run_id:l},p=await this.caller.call(wt(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(p,"create example"),await p.json()}async createExamples(t){let{inputs:r,outputs:n,metadata:o,sourceRunIds:i,exampleIds:a,datasetId:s,datasetName:u}=t,l=s;if(l===void 0&&u===void 0)throw new Error("Must provide either datasetName or datasetId");if(l!==void 0&&u!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");l===void 0&&(l=(await this.readDataset({datasetName:u})).id);let c=r.map((p,h)=>({dataset_id:l,inputs:p,outputs:n?n[h]:void 0,metadata:o?o[h]:void 0,split:t.splits?t.splits[h]:void 0,id:a?a[h]:void 0,source_run_id:i?i[h]:void 0})),d=await this.caller.call(wt(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(d,"create examples"),await d.json()}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let o=t.map(a=>Lae(a)?Fae(a):a),i=Lae(r)?Fae(r):r;return this.createExample({input:o},{output:i},n)}async readExample(t){en(t);let r=`/examples/${t}`,n=await this._get(r),{attachment_urls:o,...i}=n,a=i;return o&&(a.attachments=Object.entries(o).reduce((s,[u,l])=>(s[u.slice(11)]={presigned_url:l.presigned_url},s),{})),a}async*listExamples({datasetId:t,datasetName:r,exampleIds:n,asOf:o,splits:i,inlineS3Urls:a,metadata:s,limit:u,offset:l,filter:c,includeAttachments:d}={}){let f;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(r!==void 0)f=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),h=o?typeof o=="string"?o:o?.toISOString():void 0;h&&p.append("as_of",h);let m=a??!0;if(p.append("inline_s3_urls",m.toString()),n!==void 0)for(let g of n)p.append("id",g);if(i!==void 0)for(let g of i)p.append("splits",g);if(s!==void 0){let g=JSON.stringify(s);p.append("metadata",g)}u!==void 0&&p.append("limit",u.toString()),l!==void 0&&p.append("offset",l.toString()),c!==void 0&&p.append("filter",c),d===!0&&["attachment_urls","outputs","metadata"].forEach(g=>p.append("select",g));let _=0;for await(let g of this._getPaginated("/examples",p)){for(let v of g){let{attachment_urls:S,...x}=v,O=x;S&&(O.attachments=Object.entries(S).reduce((T,[E,M])=>(T[E.slice(11)]={presigned_url:M.presigned_url},T),{})),yield O,_++}if(u!==void 0&&_>=u)break}}async deleteExample(t){en(t);let r=`/examples/${t}`,n=await this.caller.call(wt(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(n,`delete ${r}`),await n.json()}async updateExample(t,r){en(t);let n=await this.caller.call(wt(),`${this.apiUrl}/examples/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(n,"update example"),await n.json()}async updateExamples(t){let r=await this.caller.call(wt(),`${this.apiUrl}/examples/bulk`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(r,"update examples"),await r.json()}async listDatasetSplits({datasetId:t,datasetName:r,asOf:n}){let o;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?o=(await this.readDataset({datasetName:r})).id:o=t,en(o);let i=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${o}/splits`,i)}async updateDatasetSplits({datasetId:t,datasetName:r,splitName:n,exampleIds:o,remove:i=!1}){let a;if(t===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?a=(await this.readDataset({datasetName:r})).id:a=t,en(a);let s={split_name:n,examples:o.map(l=>(en(l),l)),remove:i},u=await this.caller.call(wt(),`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(u,"update dataset splits",!0)}async evaluateRun(t,r,{sourceInfo:n,loadChildRuns:o,referenceExample:i}={loadChildRuns:!1}){F6("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let a;if(typeof t=="string")a=await this.readRun(t,{loadChildRuns:o});else if(typeof t=="object"&&"id"in t)a=t;else throw new Error(`Invalid run type: ${typeof t}`);a.reference_example_id!==null&&a.reference_example_id!==void 0&&(i=await this.readExample(a.reference_example_id));let s=await r.evaluateRun(a,i),[u,l]=await this._logEvaluationFeedback(s,a,n);return l[0]}async createFeedback(t,r,{score:n,value:o,correction:i,comment:a,sourceInfo:s,feedbackSourceType:u="api",sourceRunId:l,feedbackId:c,feedbackConfig:d,projectId:f,comparativeExperimentId:p}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");let h={type:u??"api",metadata:s??{}};l!==void 0&&h?.metadata!==void 0&&!h.metadata.__run&&(h.metadata.__run={run_id:l}),h?.metadata!==void 0&&h.metadata.__run?.run_id!==void 0&&en(h.metadata.__run.run_id);let m={id:c??dO(),run_id:t,key:r,score:n,value:o,correction:i,comment:a,feedback_source:h,comparative_experiment_id:p,feedbackConfig:d,session_id:f},_=`${this.apiUrl}/feedback`,g=await this.caller.call(wt(),_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(g,"create feedback",!0),m}async updateFeedback(t,{score:r,value:n,correction:o,comment:i}){let a={};r!=null&&(a.score=r),n!=null&&(a.value=n),o!=null&&(a.correction=o),i!=null&&(a.comment=i),en(t);let s=await this.caller.call(wt(),`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(s,"update feedback",!0)}async readFeedback(t){en(t);let r=`/feedback/${t}`;return await this._get(r)}async deleteFeedback(t){en(t);let r=`/feedback/${t}`,n=await this.caller.call(wt(),this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(n,`delete ${r}`),await n.json()}async*listFeedback({runIds:t,feedbackKeys:r,feedbackSourceTypes:n}={}){let o=new URLSearchParams;if(t&&o.append("run",t.join(",")),r)for(let i of r)o.append("key",i);if(n)for(let i of n)o.append("source",i);for await(let i of this._getPaginated("/feedback",o))yield*i}async createPresignedFeedbackToken(t,r,{expiration:n,feedbackConfig:o}={}){let i={run_id:t,feedback_key:r,feedback_config:o};return n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3},await(await this.caller.call(wt(),`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async createComparativeExperiment({name:t,experimentIds:r,referenceDatasetId:n,createdAt:o,description:i,metadata:a,id:s}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let u={id:s,name:t,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(o??new Date)?.toISOString(),extra:{}};return a&&(u.extra.metadata=a),await(await this.caller.call(wt(),`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async*listPresignedFeedbackTokens(t){en(t);let r=new URLSearchParams({run_id:t});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(t){let r;return"results"in t?r=t.results:r=[t],r}async _logEvaluationFeedback(t,r,n){let o=this._selectEvalResults(t),i=[];for(let a of o){let s=n||{};a.evaluatorInfo&&(s={...a.evaluatorInfo,...s});let u=null;a.targetRunId?u=a.targetRunId:r&&(u=r.id),i.push(await this.createFeedback(u,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:s,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model"}))}return[o,i]}async logEvaluationFeedback(t,r,n){let[o]=await this._logEvaluationFeedback(t,r,n);return o}async*listAnnotationQueues(t={}){let{queueIds:r,name:n,nameContains:o,limit:i}=t,a=new URLSearchParams;r&&r.forEach((u,l)=>{en(u,`queueIds[${l}]`),a.append("ids",u)}),n&&a.append("name",n),o&&a.append("name_contains",o),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let s=0;for await(let u of this._getPaginated("/annotation-queues",a))if(yield*u,s++,i!==void 0&&s>=i)break}async createAnnotationQueue(t){let{name:r,description:n,queueId:o}=t,i={name:r,description:n,id:o||dO()},a=await this.caller.call(wt(),`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0))),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"create annotation queue"),await a.json()}async readAnnotationQueue(t){let r=await this.listAnnotationQueues({queueIds:[t]}).next();if(r.done)throw new Error(`Annotation queue with ID ${t} not found`);return r.value}async updateAnnotationQueue(t,r){let{name:n,description:o}=r,i=await this.caller.call(wt(),`${this.apiUrl}/annotation-queues/${en(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({name:n,description:o}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,"update annotation queue")}async deleteAnnotationQueue(t){let r=await this.caller.call(wt(),`${this.apiUrl}/annotation-queues/${en(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(r,"delete annotation queue")}async addRunsToAnnotationQueue(t,r){let n=await this.caller.call(wt(),`${this.apiUrl}/annotation-queues/${en(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r.map((o,i)=>en(o,`runIds[${i}]`).toString())),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(n,"add runs to annotation queue")}async getRunFromAnnotationQueue(t,r){let n=`/annotation-queues/${en(t,"queueId")}/run`,o=await this.caller.call(wt(),`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(o,"get run from annotation queue"),await o.json()}async _currentTenantIsOwner(t){let r=await this._getSettings();return t=="-"||r.tenant_handle===t}async _ownerConflictError(t,r){let n=await this._getSettings();return new Error(`Cannot ${t} for another tenant. - Current tenant: ${settings.tenant_handle} + Current tenant: ${n.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 + Requested tenant: ${r}`)}async _getLatestCommitHash(t){let r=await this.caller.call(wt(),`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){let o=typeof n.detail=="string"?n.detail:JSON.stringify(n.detail),i=new Error(`Error ${r.status}: ${r.statusText} +${o}`);throw i.statusCode=r.status,i}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){let[n,o,i]=gS(t),a=await this.caller.call(wt(),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(t){let[r,n,o]=gS(t);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(let r of this._getPaginated(`/commits/${t}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(t){let r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query);for await(let n of this._getPaginated("/repos",r,o=>o.repos))yield*n}async getPrompt(t){let[r,n,o]=gS(t),i=await this.caller.call(wt(),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)return null;await qr(i,"get prompt");let a=await i.json();return a.repo?a.repo:null}async createPrompt(t,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first creating a LangChain Hub handle. You can add a handle by creating a public prompt at: - https://smith.langchain.com/prompts`); - } - const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); - if (!await this._currentTenantIsOwner(owner)) { - throw await this._ownerConflictError("create a prompt", owner); - } - const data = { - repo_handle: promptName, - ...options?.description && { description: options.description }, - ...options?.readme && { readme: options.readme }, - ...options?.tags && { tags: options.tags }, - is_public: !!options?.isPublic - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create prompt"); - const { repo } = await response.json(); - return repo; - } - async createCommit(promptIdentifier, object, options) { - if (!await this.promptExists(promptIdentifier)) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash - }; - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "create commit"); - const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); - } - /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response - */ - async updateExamplesMultipart(datasetId, updates = []) { - if (!await this._getMultiPartSupport()) { - throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version."); - } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - const exampleBody = { - ...example.metadata && { metadata: example.metadata }, - ...example.split && { split: example.split } - }; - const stringifiedExample = stringify(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json" - }); - formData.append(exampleId, exampleBlob); - if (example.inputs) { - const stringifiedInputs = stringify(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json" - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - if (example.outputs) { - const stringifiedOutputs = stringify(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json" - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}` - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = stringify(example.attachments_operations); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json" - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); - } - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { - method: "PATCH", - headers: this.headers, - body: formData - }); - const result = await response.json(); - return result; - } - /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - */ - async uploadExamplesMultipart(datasetId, uploads = []) { - if (!await this._getMultiPartSupport()) { - throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version."); - } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? v4_default2()).toString(); - const exampleBody = { - created_at: example.created_at, - ...example.metadata && { metadata: example.metadata }, - ...example.split && { split: example.split } - }; - const stringifiedExample = stringify(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json" - }); - formData.append(exampleId, exampleBlob); - const stringifiedInputs = stringify(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json" - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - if (example.outputs) { - const stringifiedOutputs = stringify(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json" - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}` - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { - method: "POST", - headers: this.headers, - body: formData - }); - const result = await response.json(); - return result; - } - async updatePrompt(promptIdentifier, options) { - if (!await this.promptExists(promptIdentifier)) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!await this._currentTenantIsOwner(owner)) { - throw await this._ownerConflictError("update a prompt", owner); - } - const payload = {}; - if (options?.description !== void 0) - payload.description = options.description; - if (options?.readme !== void 0) - payload.readme = options.readme; - if (options?.tags !== void 0) - payload.tags = options.tags; - if (options?.isPublic !== void 0) - payload.is_public = options.isPublic; - if (options?.isArchived !== void 0) - payload.is_archived = options.isArchived; - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - body: JSON.stringify(payload), - headers: { - ...this.headers, - "Content-Type": "application/json" - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "update prompt"); - return response.json(); - } - async deletePrompt(promptIdentifier) { - if (!await this.promptExists(promptIdentifier)) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); - if (!await this._currentTenantIsOwner(owner)) { - throw await this._ownerConflictError("delete a prompt", owner); - } - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - return await response.json(); - } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions - }); - await raiseForStatus(response, "pull prompt commit"); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples - }; - } - /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private - */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel - }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; - } - async pushPrompt(promptIdentifier, options) { - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic - }); - } - } else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic - }); - } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); - } - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash - }); - return url; - } - /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} - */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder" - }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; - } - } catch (_2) { - } - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? void 0, - outputsSchema: ds.outputs_schema_definition ?? void 0 - }); - try { - await this.createExamples({ - inputs: examples.map((e3) => e3.inputs), - outputs: examples.flatMap((e3) => e3.outputs ? [e3.outputs] : []), - datasetId: dataset.id - }); - } catch (e3) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`); - throw e3; - } - } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind4 = "dataset") { - try { - assertUuid(urlOrToken); - return [apiUrl, urlOrToken]; - } catch (_2) { - } - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname.split("/").filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; - } else { - throw new Error(`Invalid public ${kind4} URL: ${urlOrToken}`); - } - } catch (error) { - throw new Error(`Invalid public ${kind4} URL or token: ${urlOrToken}`); - } - } - /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. - * - * @example - * ``` - * import { Client } from "langsmith"; - * - * const client = new Client(); - * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` - * - * @returns A promise that resolves once all currently pending traces have sent. - */ - awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); - } - return Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle() - ]); - } - }; - } -}); - -// node_modules/langsmith/dist/index.js -var __version__; -var init_dist = __esm({ - "node_modules/langsmith/dist/index.js"() { - init_client(); - init_run_trees(); - init_fetch(); - __version__ = "0.2.14"; - } -}); - -// node_modules/langsmith/dist/utils/env.js -function getRuntimeEnvironment() { - if (runtimeEnvironment === void 0) { - const env = getEnv(); - const releaseEnv = getShas(); - runtimeEnvironment = { - library: "langsmith", - runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv - }; - } - return runtimeEnvironment; -} -function getLangChainEnvVarsMetadata() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION" - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; - } else { - envVars[key] = value; - } - } - } - return envVars; -} -function getEnvironmentVariables() { - try { - if (typeof process !== "undefined" && process.env) { - return Object.entries(process.env).reduce((acc, [key, value]) => { - acc[key] = String(value); - return acc; - }, {}); - } - return void 0; - } catch (e3) { - return void 0; - } -} -function getEnvironmentVariable(name) { - try { - return typeof process !== "undefined" ? ( - // eslint-disable-next-line no-process-env - process.env?.[name] - ) : void 0; - } catch (e3) { - return void 0; - } -} -function getLangSmithEnvironmentVariable(name) { - return getEnvironmentVariable(`LANGSMITH_${name}`) || getEnvironmentVariable(`LANGCHAIN_${name}`); -} -function getShas() { - if (cachedCommitSHAs !== void 0) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT" - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = getEnvironmentVariable(env); - if (envVar !== void 0) { - shas[env] = envVar; - } - } - cachedCommitSHAs = shas; - return shas; -} -var globalEnv, isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment, cachedCommitSHAs; -var init_env = __esm({ - "node_modules/langsmith/dist/utils/env.js"() { - init_dist(); - isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; - isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; - isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); - isDeno = () => typeof Deno !== "undefined"; - isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); - getEnv = () => { - if (globalEnv) { - return globalEnv; - } - if (isBrowser()) { - globalEnv = "browser"; - } else if (isNode()) { - globalEnv = "node"; - } else if (isWebWorker()) { - globalEnv = "webworker"; - } else if (isJsDom()) { - globalEnv = "jsdom"; - } else if (isDeno()) { - globalEnv = "deno"; - } else { - globalEnv = "other"; - } - return globalEnv; - }; - } -}); - -// node_modules/langsmith/dist/env.js -var isTracingEnabled; -var init_env2 = __esm({ - "node_modules/langsmith/dist/env.js"() { - init_env(); - isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== void 0) { - return tracingEnabled; - } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); - }; - } -}); - -// node_modules/langsmith/dist/singletons/constants.js -var _LC_CONTEXT_VARIABLES_KEY; -var init_constants = __esm({ - "node_modules/langsmith/dist/singletons/constants.js"() { - _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); - } -}); - -// node_modules/langsmith/dist/run_trees.js -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId; -} -function isRunTree(x2) { - return x2 !== void 0 && typeof x2.createChild === "function" && typeof x2.postRun === "function"; -} -function isLangChainTracerLike(x2) { - return typeof x2 === "object" && x2 != null && typeof x2.name === "string" && x2.name === "langchain_tracer"; -} -function containsLangChainTracerLike(x2) { - return Array.isArray(x2) && x2.some((callback) => isLangChainTracerLike(callback)); -} -function isCallbackManagerLike(x2) { - return typeof x2 === "object" && x2 != null && Array.isArray(x2.handlers); -} -function isRunnableConfigLike(x2) { - return x2 !== void 0 && typeof x2.callbacks === "object" && // Callback manager with a langchain tracer - (containsLangChainTracerLike(x2.callbacks?.handlers) || // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(x2.callbacks)); -} -var Baggage, RunTree; -var init_run_trees = __esm({ - "node_modules/langsmith/dist/run_trees.js"() { - init_esm_browser2(); - init_env(); - init_client(); - init_env2(); - init_warn(); - init_constants(); - Baggage = class { - constructor(metadata, tags) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.metadata = metadata; - this.tags = tags; - } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value2 = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value2); - } else if (key === "langsmith-tags") { - tags = value2.split(","); - } - } - return new Baggage(metadata, tags); - } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); - } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); - } - return items.join(","); - } - }; - RunTree = class { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reference_example_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "events", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "trace_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "dotted_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "attachments", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; - } - const defaultConfig = RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client2 = config.client ?? RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - Object.assign(this, { ...defaultConfig, ...config, client: client2 }); - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; - } else { - this.trace_id = this.id; - } - } - this.execution_order ?? (this.execution_order = 1); - this.child_execution_order ?? (this.child_execution_order = 1); - if (!this.dotted_order) { - const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = this.parent_run.dotted_order + "." + currentDottedOrder; - } else { - this.dotted_order = currentDottedOrder; - } - } - } - static getDefaultConfig() { - return { - id: v4_default2(), - run_type: "chain", - project_name: getEnvironmentVariable("LANGCHAIN_PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default", - child_runs: [], - api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {} - }; - } - static getSharedClient() { - if (!RunTree.sharedClient) { - RunTree.sharedClient = new Client(); - } - return RunTree.sharedClient; - } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - const child = new RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order - }); - if (_LC_CONTEXT_VARIABLES_KEY in this) { - child[_LC_CONTEXT_VARIABLES_KEY] = this[_LC_CONTEXT_VARIABLES_KEY]; - } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? this.extra[LC_CHILD]; - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0; - if (callbacks) { - Object.assign(callbacks, { _parentRunId: child.id }); - callbacks.handlers?.find(isLangChainTracerLike)?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; - } - child.extra[LC_CHILD] = newConfig; - } - const visited = /* @__PURE__ */ new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; - } - this.child_runs.push(child); - return child; - } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } : { metadata }; - } - } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - if (!runExtra.runtime) { - runExtra.runtime = {}; - } - if (runtimeEnv) { - for (const [k3, v5] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k3]) { - runExtra.runtime[k3] = v5; - } - } - } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = void 0; - } else { - parent_run_id = run.parent_run?.id; - child_runs = []; - } - const persistedRun = { - id: run.id, - name: run.name, - start_time: run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs, - parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments - }; - return persistedRun; - } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = getRuntimeEnvironment(); - const runCreate = await this._convertToCreate(this, runtimeEnv, true); - await this.client.createRun(runCreate); - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); - } - } - } catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); - } - } - async patchRun() { - try { - const runUpdate = { - end_time: this.end_time, - error: this.error, - inputs: this.inputs, - outputs: this.outputs, - parent_run_id: this.parent_run?.id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments - }; - await this.client.updateRun(this.id, runUpdate); - } catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); - } - } - toJSON() { - return this._convertToCreate(this, void 0, false); - } - static fromRunnableConfig(parentConfig, props) { - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client2; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client2 = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; - } - if (!parentRun) { - return new RunTree({ - ...props, - client: client2, - tracingEnabled, - project_name: projectName - }); - } - const parentRunTree = new RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client: client2, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])) - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata - } - } - }); - return parentRunTree.createChild(props); - } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); - } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage") - } : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return void 0; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; - }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - } - return new RunTree(config); - } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags).toHeader() - }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); - } - } - return result; - } - }; - Object.defineProperty(RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - } -}); - -// node_modules/langsmith/dist/singletons/traceable.js -function isTraceableFunction(x2) { - return typeof x2 === "function" && "langsmith:traceable" in x2; -} -var MockAsyncLocalStorage, TRACING_ALS_KEY, mockAsyncLocalStorage, AsyncLocalStorageProvider, AsyncLocalStorageProviderSingleton, getCurrentRunTree, ROOT; -var init_traceable = __esm({ - "node_modules/langsmith/dist/singletons/traceable.js"() { - init_run_trees(); - MockAsyncLocalStorage = class { - getStore() { - return void 0; - } - run(_2, callback) { - return callback(); - } - }; - TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); - mockAsyncLocalStorage = new MockAsyncLocalStorage(); - AsyncLocalStorageProvider = class { - getInstance() { - return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; - } - initializeGlobalInstance(instance) { - if (globalThis[TRACING_ALS_KEY] === void 0) { - globalThis[TRACING_ALS_KEY] = instance; - } - } - }; - AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); - getCurrentRunTree = () => { - const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!isRunTree(runTree)) { - throw new Error([ - "Could not get the current run tree.", - "", - "Please make sure you are calling this method within a traceable function or the tracing is enabled." - ].join("\n")); - } - return runTree; - }; - ROOT = Symbol.for("langsmith:traceable:root"); - } -}); - -// node_modules/langsmith/singletons/traceable.js -var init_traceable2 = __esm({ - "node_modules/langsmith/singletons/traceable.js"() { - init_traceable(); - } -}); - -// node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -function hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys2 = new Array(obj.length); - for (let k3 = 0; k3 < keys2.length; k3++) { - keys2[k3] = "" + k3; - } - return keys2; - } - if (Object.keys) { - return Object.keys(obj); - } - let keys = []; - for (let i3 in obj) { - if (hasOwnProperty(obj, i3)) { - keys.push(i3); - } - } - return keys; -} -function _deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); - case "undefined": - return null; - default: - return obj; - } -} -function isInteger(str2) { - let i3 = 0; - const len = str2.length; - let charCode; - while (i3 < len) { - charCode = str2.charCodeAt(i3); - if (charCode >= 48 && charCode <= 57) { - i3++; - continue; - } - return false; - } - return true; -} -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function hasUndefined(obj) { - if (obj === void 0) { - return true; - } - if (obj) { - if (Array.isArray(obj)) { - for (let i4 = 0, len = obj.length; i4 < len; i4++) { - if (hasUndefined(obj[i4])) { - return true; - } - } - } else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i3 = 0; i3 < objKeysLength; i3++) { - if (hasUndefined(obj[objKeys[i3]])) { - return true; - } - } - } - } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; - if (typeof value !== "undefined") { - messageParts.push(`${key}: ${value}`); - } - } - return messageParts.join("\n"); -} -var _hasOwnProperty, PatchError; -var init_helpers = __esm({ - "node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js"() { - _hasOwnProperty = Object.prototype.hasOwnProperty; - PatchError = class extends Error { - constructor(message, name, index2, operation, tree) { - super(patchErrorMessageFormatter(message, { name, index: index2, operation, tree })); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: name - }); - Object.defineProperty(this, "index", { - enumerable: true, - configurable: true, - writable: true, - value: index2 - }); - Object.defineProperty(this, "operation", { - enumerable: true, - configurable: true, - writable: true, - value: operation - }); - Object.defineProperty(this, "tree", { - enumerable: true, - configurable: true, - writable: true, - value: tree - }); - Object.setPrototypeOf(this, new.target.prototype); - this.message = patchErrorMessageFormatter(message, { - name, - index: index2, - operation, - tree - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -var core_exports = {}; -__export(core_exports, { - JsonPatchError: () => JsonPatchError, - _areEquals: () => _areEquals, - applyOperation: () => applyOperation, - applyPatch: () => applyPatch, - applyReducer: () => applyReducer, - deepClone: () => deepClone, - getValueByPointer: () => getValueByPointer, - validate: () => validate3, - validator: () => validator -}); -function getValueByPointer(document2, pointer) { - if (pointer == "") { - return document2; - } - var getOriginalDestination = { op: "_get", path: pointer }; - applyOperation(document2, getOriginalDestination); - return getOriginalDestination.value; -} -function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index2 = 0) { - if (validateOperation) { - if (typeof validateOperation == "function") { - validateOperation(operation, 0, document2, operation.path); - } else { - validator(operation, 0); - } - } - if (operation.path === "") { - let returnValue = { newDocument: document2 }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document2; - return returnValue; - } else if (operation.op === "move" || operation.op === "copy") { - returnValue.newDocument = getValueByPointer(document2, operation.from); - if (operation.op === "move") { - returnValue.removed = document2; - } - return returnValue; - } else if (operation.op === "test") { - returnValue.test = _areEquals(document2, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); - } - returnValue.newDocument = document2; - return returnValue; - } else if (operation.op === "remove") { - returnValue.removed = document2; - returnValue.newDocument = null; - return returnValue; - } else if (operation.op === "_get") { - operation.value = document2; - return returnValue; - } else { - if (validateOperation) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); - } else { - return returnValue; - } - } - } else { - if (!mutateDocument) { - document2 = _deepClone(document2); - } - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document2; - let t3 = 1; - let len = keys.length; - let existingPathFragment = void 0; - let key; - let validateFunction; - if (typeof validateOperation == "function") { - validateFunction = validateOperation; - } else { - validateFunction = validator; - } - while (true) { - key = keys[t3]; - if (key && key.indexOf("~") != -1) { - key = unescapePathComponent(key); - } - if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t3 > 0 && keys[t3 - 1] == "constructor")) { - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - } - if (validateOperation) { - if (existingPathFragment === void 0) { - if (obj[key] === void 0) { - existingPathFragment = keys.slice(0, t3).join("/"); - } else if (t3 == len - 1) { - existingPathFragment = operation.path; - } - if (existingPathFragment !== void 0) { - validateFunction(operation, 0, document2, existingPathFragment); - } - } - } - t3++; - if (Array.isArray(obj)) { - if (key === "-") { - key = obj.length; - } else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index2, operation, document2); - } else if (isInteger(key)) { - key = ~~key; - } - } - if (t3 >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) { - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index2, operation, document2); - } - const returnValue = arrOps[operation.op].call(operation, obj, key, document2); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); - } - return returnValue; - } - } else { - if (t3 >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document2); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); - } - return returnValue; - } - } - obj = obj[key]; - if (validateOperation && t3 < len && (!obj || typeof obj !== "object")) { - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); - } - } - } -} -function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - } - if (!mutateDocument) { - document2 = _deepClone(document2); - } - const results = new Array(patch.length); - for (let i3 = 0, length = patch.length; i3 < length; i3++) { - results[i3] = applyOperation(document2, patch[i3], validateOperation, true, banPrototypeModifications, i3); - document2 = results[i3].newDocument; - } - results.newDocument = document2; - return results; -} -function applyReducer(document2, operation, index2) { - const operationResult = applyOperation(document2, operation); - if (operationResult.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); - } - return operationResult.newDocument; -} -function validator(operation, index2, document2, existingPathFragment) { - if (typeof operation !== "object" || operation === null || Array.isArray(operation)) { - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index2, operation, document2); - } else if (!objOps[operation.op]) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); - } else if (typeof operation.path !== "string") { - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index2, operation, document2); - } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index2, operation, document2); - } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") { - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index2, operation, document2); - } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index2, operation, document2); - } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index2, operation, document2); - } else if (document2) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index2, operation, document2); - } - } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); - } - } else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: void 0 - }; - var error = validate3([existingValue], document2); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index2, operation, document2); - } - } - } -} -function validate3(sequence, document2, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (document2) { - applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); - } else { - externalValidator = externalValidator || validator; - for (var i3 = 0; i3 < sequence.length; i3++) { - externalValidator(sequence[i3], i3, document2, void 0); - } - } - } catch (e3) { - if (e3 instanceof JsonPatchError) { - return e3; - } else { - throw e3; - } - } -} -function _areEquals(a3, b3) { - if (a3 === b3) - return true; - if (a3 && b3 && typeof a3 == "object" && typeof b3 == "object") { - var arrA = Array.isArray(a3), arrB = Array.isArray(b3), i3, length, key; - if (arrA && arrB) { - length = a3.length; - if (length != b3.length) - return false; - for (i3 = length; i3-- !== 0; ) - if (!_areEquals(a3[i3], b3[i3])) - return false; - return true; - } - if (arrA != arrB) - return false; - var keys = Object.keys(a3); - length = keys.length; - if (length !== Object.keys(b3).length) - return false; - for (i3 = length; i3-- !== 0; ) - if (!b3.hasOwnProperty(keys[i3])) - return false; - for (i3 = length; i3-- !== 0; ) { - key = keys[i3]; - if (!_areEquals(a3[key], b3[key])) - return false; - } - return true; - } - return a3 !== a3 && b3 !== b3; -} -var JsonPatchError, deepClone, objOps, arrOps; -var init_core = __esm({ - "node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js"() { - init_helpers(); - JsonPatchError = PatchError; - deepClone = _deepClone; - objOps = { - add: function(obj, key, document2) { - obj[key] = this.value; - return { newDocument: document2 }; - }, - remove: function(obj, key, document2) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document2, removed }; - }, - replace: function(obj, key, document2) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document2, removed }; - }, - move: function(obj, key, document2) { - let removed = getValueByPointer(document2, this.path); - if (removed) { - removed = _deepClone(removed); - } - const originalValue = applyOperation(document2, { - op: "remove", - path: this.from - }).removed; - applyOperation(document2, { - op: "add", - path: this.path, - value: originalValue - }); - return { newDocument: document2, removed }; - }, - copy: function(obj, key, document2) { - const valueToCopy = getValueByPointer(document2, this.from); - applyOperation(document2, { - op: "add", - path: this.path, - value: _deepClone(valueToCopy) - }); - return { newDocument: document2 }; - }, - test: function(obj, key, document2) { - return { newDocument: document2, test: _areEquals(obj[key], this.value) }; - }, - _get: function(obj, key, document2) { - this.value = obj[key]; - return { newDocument: document2 }; - } - }; - arrOps = { - add: function(arr2, i3, document2) { - if (isInteger(i3)) { - arr2.splice(i3, 0, this.value); - } else { - arr2[i3] = this.value; - } - return { newDocument: document2, index: i3 }; - }, - remove: function(arr2, i3, document2) { - var removedList = arr2.splice(i3, 1); - return { newDocument: document2, removed: removedList[0] }; - }, - replace: function(arr2, i3, document2) { - var removed = arr2[i3]; - arr2[i3] = this.value; - return { newDocument: document2, removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get - }; - } -}); - -// node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) { - return; - } - if (typeof obj.toJSON === "function") { - obj = obj.toJSON(); - } - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - for (var t3 = oldKeys.length - 1; t3 >= 0; t3--) { - var key = oldKeys[t3]; - var oldVal = mirror[key]; - if (hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { - _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); - } else { - if (oldVal !== newVal) { - changed = true; - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - } - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: _deepClone(newVal) - }); - } - } - } else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - } - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key) - }); - deleted = true; - } else { - if (invertible) { - patches.push({ op: "test", path, value: mirror }); - } - patches.push({ op: "replace", path, value: obj }); - changed = true; - } - } - if (!deleted && newKeys.length == oldKeys.length) { - return; - } - for (var t3 = 0; t3 < newKeys.length; t3++) { - var key = newKeys[t3]; - if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) { - patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: _deepClone(obj[key]) - }); - } - } -} -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; -} -var init_duplex = __esm({ - "node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js"() { - init_helpers(); - init_core(); - } -}); - -// node_modules/@langchain/core/dist/utils/fast-json-patch/index.js -var fast_json_patch_default; -var init_fast_json_patch = __esm({ - "node_modules/@langchain/core/dist/utils/fast-json-patch/index.js"() { - init_core(); - init_duplex(); - init_helpers(); - init_core(); - init_helpers(); - fast_json_patch_default = { - ...core_exports, - // ...duplex, - JsonPatchError: PatchError, - deepClone: _deepClone, - escapePathComponent, - unescapePathComponent - }; - } -}); - -// node_modules/decamelize/index.js -var require_decamelize = __commonJS({ - "node_modules/decamelize/index.js"(exports, module2) { - "use strict"; - module2.exports = function(str2, sep) { - if (typeof str2 !== "string") { - throw new TypeError("Expected a string"); - } - sep = typeof sep === "undefined" ? "_" : sep; - return str2.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase(); - }; - } -}); - -// node_modules/@langchain/core/node_modules/camelcase/index.js -var require_camelcase = __commonJS({ - "node_modules/@langchain/core/node_modules/camelcase/index.js"(exports, module2) { - "use strict"; - var UPPERCASE = /[\p{Lu}]/u; - var LOWERCASE = /[\p{Ll}]/u; - var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; - var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; - var SEPARATORS = /[_.\- ]+/; - var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); - var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); - var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); - var preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - for (let i3 = 0; i3 < string.length; i3++) { - const character = string[i3]; - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i3) + "-" + string.slice(i3); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i3++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i3 - 1) + "-" + string.slice(i3 - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } - return string; - }; - var preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; - return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); - }; - var postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; - return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m3) => toUpperCase(m3)); - }; - var camelCase2 = (input, options) => { - if (!(typeof input === "string" || Array.isArray(input))) { - throw new TypeError("Expected the input to be `string | string[]`"); - } - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; - if (Array.isArray(input)) { - input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-"); - } else { - input = input.trim(); - } - if (input.length === 0) { - return ""; - } - const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale); - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } - const hasUpperCase = input !== toLowerCase(input); - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } - input = input.replace(LEADING_SEPARATORS, ""); - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } - return postProcess(input, toUpperCase); - }; - module2.exports = camelCase2; - module2.exports.default = camelCase2; - } -}); - -// node_modules/@langchain/core/dist/load/map_keys.js -function keyToJson(key, map) { - return map?.[key] || (0, import_decamelize.default)(key); -} -function mapKeys(fields, mapper, map) { - const mapped = {}; - for (const key in fields) { - if (Object.hasOwn(fields, key)) { - mapped[mapper(key, map)] = fields[key]; - } - } - return mapped; -} -var import_decamelize, import_camelcase; -var init_map_keys = __esm({ - "node_modules/@langchain/core/dist/load/map_keys.js"() { - import_decamelize = __toESM(require_decamelize(), 1); - import_camelcase = __toESM(require_camelcase(), 1); - } -}); - -// node_modules/@langchain/core/dist/load/serializable.js -function shallowCopy(obj) { - return Array.isArray(obj) ? [...obj] : { ...obj }; -} -function replaceSecrets(root2, secretsMap) { - const result = shallowCopy(root2); - for (const [path, secretId] of Object.entries(secretsMap)) { - const [last, ...partsReverse] = path.split(".").reverse(); - let current = result; - for (const part of partsReverse.reverse()) { - if (current[part] === void 0) { - break; - } - current[part] = shallowCopy(current[part]); - current = current[part]; - } - if (current[last] !== void 0) { - current[last] = { - lc: 1, - type: "secret", - id: [secretId] - }; - } - } - return result; -} -function get_lc_unique_name(serializableClass) { - const parentClass = Object.getPrototypeOf(serializableClass); - const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); - if (lcNameIsSubclassed) { - return serializableClass.lc_name(); - } else { - return serializableClass.name; - } -} -var Serializable; -var init_serializable = __esm({ - "node_modules/@langchain/core/dist/load/serializable.js"() { - init_map_keys(); - Serializable = class { - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor) - ]; - } - /** - * A map of secrets, which will be omitted from serialization. - * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". - * Values are the secret ids, which will be used when deserializing. - */ - get lc_secrets() { - return void 0; - } - /** - * A map of additional attributes to merge with constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the attribute values, which will be serialized. - * These attributes need to be accepted by the constructor as arguments. - */ - get lc_attributes() { - return void 0; - } - /** - * A map of aliases for constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the alias that will replace the key in serialization. - * This is used to eg. make argument names match Python. - */ - get lc_aliases() { - return void 0; - } - constructor(kwargs, ..._args) { - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.lc_kwargs = kwargs || {}; - } - toJSON() { - if (!this.lc_serializable) { - return this.toJSONNotImplemented(); - } - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs) - ) { - return this.toJSONNotImplemented(); - } - const aliases = {}; - const secrets = {}; - const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { - acc[key] = key in this ? this[key] : this.lc_kwargs[key]; - return acc; - }, {}); - for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { - Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); - Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); - Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); - } - Object.keys(secrets).forEach((keyPath) => { - let read = this; - let write = kwargs; - const [last, ...partsReverse] = keyPath.split(".").reverse(); - for (const key of partsReverse.reverse()) { - if (!(key in read) || read[key] === void 0) - return; - if (!(key in write) || write[key] === void 0) { - if (typeof read[key] === "object" && read[key] != null) { - write[key] = {}; - } else if (Array.isArray(read[key])) { - write[key] = []; - } - } - read = read[key]; - write = write[key]; - } - if (last in read && read[last] !== void 0) { - write[last] = write[last] || read[last]; - } - }); - return { - lc: 1, - type: "constructor", - id: this.lc_id, - kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) - }; - } - toJSONNotImplemented() { - return { - lc: 1, - type: "not_implemented", - id: this.lc_id - }; - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/env.js -async function getRuntimeEnvironment2() { - if (runtimeEnvironment2 === void 0) { - const env = getEnv2(); - runtimeEnvironment2 = { - library: "langchain-js", - runtime: env - }; - } - return runtimeEnvironment2; -} -function getEnvironmentVariable2(name) { - try { - if (typeof process !== "undefined") { - return process.env?.[name]; - } else if (isDeno2()) { - return Deno?.env.get(name); - } else { - return void 0; - } - } catch (e3) { - return void 0; - } -} -var isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2; -var init_env3 = __esm({ - "node_modules/@langchain/core/dist/utils/env.js"() { - isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; - isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; - isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); - isDeno2 = () => typeof Deno !== "undefined"; - isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2(); - getEnv2 = () => { - let env; - if (isBrowser2()) { - env = "browser"; - } else if (isNode2()) { - env = "node"; - } else if (isWebWorker2()) { - env = "webworker"; - } else if (isJsDom2()) { - env = "jsdom"; - } else if (isDeno2()) { - env = "deno"; - } else { - env = "other"; - } - return env; - }; - } -}); - -// node_modules/@langchain/core/dist/callbacks/base.js -function callbackHandlerPrefersStreaming(x2) { - return "lc_prefer_streaming" in x2 && x2.lc_prefer_streaming; -} -var BaseCallbackHandlerMethodsClass, BaseCallbackHandler, isBaseCallbackHandler; -var init_base = __esm({ - "node_modules/@langchain/core/dist/callbacks/base.js"() { - init_esm_browser(); - init_serializable(); - init_env3(); - BaseCallbackHandlerMethodsClass = class { - }; - BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { - get lc_namespace() { - return ["langchain_core", "callbacks", this.name]; - } - get lc_secrets() { - return void 0; - } - get lc_attributes() { - return void 0; - } - get lc_aliases() { - return void 0; - } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor) - ]; - } - constructor(input) { - super(); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "ignoreLLM", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreChain", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreAgent", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreRetriever", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreCustomEvent", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "raiseError", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "awaitHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" - }); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; - this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; - this.raiseError = input.raiseError ?? this.raiseError; - this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); - } - } - copy() { - return new this.constructor(this); - } - toJSON() { - return Serializable.prototype.toJSON.call(this); - } - toJSONNotImplemented() { - return Serializable.prototype.toJSONNotImplemented.call(this); - } - static fromMethods(methods2) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4_default() - }); - Object.assign(this, methods2); - } - } - return new Handler(); - } - }; - isBaseCallbackHandler = (x2) => { - const callbackHandler = x2; - return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; - }; - } -}); - -// node_modules/@langchain/core/dist/tracers/base.js -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function stripNonAlphanumeric2(input) { - return input.replace(/[-:.]/g, ""); -} -function convertToDottedOrderFormat2(epoch, runId, executionOrder) { - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return stripNonAlphanumeric2(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId; -} -function isBaseTracer(x2) { - return typeof x2._addRunToRunMap === "function"; -} -var BaseTracer; -var init_base2 = __esm({ - "node_modules/@langchain/core/dist/tracers/base.js"() { - init_base(); - BaseTracer = class extends BaseCallbackHandler { - constructor(_fields) { - super(...arguments); - Object.defineProperty(this, "runMap", { - enumerable: true, - configurable: true, - writable: true, - value: /* @__PURE__ */ new Map() - }); - } - copy() { - return this; - } - stringifyError(error) { - if (error instanceof Error) { - return error.message + (error?.stack ? ` - -${error.stack}` : ""); - } - if (typeof error === "string") { - return error; - } - return `${error}`; - } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); - } - _addRunToRunMap(run) { - const currentDottedOrder = convertToDottedOrderFormat2(run.start_time, run.id, run.execution_order); - const storedRun = { ...run }; - if (storedRun.parent_run_id !== void 0) { - const parentRun = this.runMap.get(storedRun.parent_run_id); - if (parentRun) { - this._addChildRun(parentRun, storedRun); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); - storedRun.trace_id = parentRun.trace_id; - if (parentRun.dotted_order !== void 0) { - storedRun.dotted_order = [ - parentRun.dotted_order, - currentDottedOrder - ].join("."); - } else { - } - } else { - } - } else { - storedRun.trace_id = storedRun.id; - storedRun.dotted_order = currentDottedOrder; - } - this.runMap.set(storedRun.id, storedRun); - return storedRun; - } - async _endTrace(run) { - const parentRun = run.parent_run_id !== void 0 && this.runMap.get(run.parent_run_id); - if (parentRun) { - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - } else { - await this.persistRun(run); - } - this.runMap.delete(run.id); - await this.onRunUpdate?.(run); - } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== void 0 && this.runMap.get(parentRunId); - if (!parentRun) { - return 1; - } - return parentRun.child_execution_order + 1; - } - /** - * Create and add a run to the run map for LLM start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString() - } - ], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - /** - * Create and add a run to the run map for chat model start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString() - } - ], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; - } - async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for chain start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [ - { - name: "start", - time: new Date(start_time).toISOString() - } - ], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.runMap.get(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); - await this.onRunCreate?.(run); - await this.onChainStart?.(run); - return run; - } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); - } - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); - } - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; - } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); - } - await this.onChainError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for tool start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool2.id[tool2.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool2, - events: [ - { - name: "start", - time: new Date(start_time).toISOString() - } - ], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleToolStart(tool2, input, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? this._createRunForToolStart(tool2, input, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onToolStart?.(run); - return run; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; - } - async handleToolError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; - } - async handleAgentAction(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: new Date().toISOString(), - kwargs: { action } - }); - await this.onAgentAction?.(run); - } - async handleAgentEnd(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - run.events.push({ - name: "agent_end", - time: new Date().toISOString(), - kwargs: { action } - }); - await this.onAgentEnd?.(run); - } - /** - * Create and add a run to the run map for retriever start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [ - { - name: "start", - time: new Date(start_time).toISOString() - } - ], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onRetrieverStart?.(run); - return run; - } - async handleRetrieverEnd(documents, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; - } - async handleRetrieverError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; - } - async handleText(text, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - run.events.push({ - name: "text", - time: new Date().toISOString(), - kwargs: { text } - }); - await this.onText?.(run); - } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); - } - run.events.push({ - name: "new_token", - time: new Date().toISOString(), - kwargs: { token, idx, chunk: fields?.chunk } - }); - await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); - return run; - } - }; - } -}); - -// node_modules/@langchain/core/node_modules/ansi-styles/index.js -var require_ansi_styles = __commonJS({ - "node_modules/@langchain/core/node_modules/ansi-styles/index.js"(exports, module2) { - "use strict"; - var ANSI_BACKGROUND_OFFSET = 10; - var wrapAnsi256 = (offset5 = 0) => (code) => `\x1B[${38 + offset5};5;${code}m`; - var wrapAnsi16m = (offset5 = 0) => (red, green, blue) => `\x1B[${38 + offset5};2;${red};${green};${blue}m`; - function assembleStyles() { - const codes = /* @__PURE__ */ new Map(); - const styles2 = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - styles2.color.gray = styles2.color.blackBright; - styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; - styles2.color.grey = styles2.color.blackBright; - styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; - for (const [groupName, group] of Object.entries(styles2)) { - for (const [styleName, style] of Object.entries(group)) { - styles2[styleName] = { - open: `\x1B[${style[0]}m`, - close: `\x1B[${style[1]}m` - }; - group[styleName] = styles2[styleName]; - codes.set(style[0], style[1]); - } - Object.defineProperty(styles2, groupName, { - value: group, - enumerable: false - }); - } - Object.defineProperty(styles2, "codes", { - value: codes, - enumerable: false - }); - styles2.color.close = "\x1B[39m"; - styles2.bgColor.close = "\x1B[49m"; - styles2.color.ansi256 = wrapAnsi256(); - styles2.color.ansi16m = wrapAnsi16m(); - styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - Object.defineProperties(styles2, { - rgbToAnsi256: { - value: (red, green, blue) => { - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - if (red > 248) { - return 231; - } - return Math.round((red - 8) / 247 * 24) + 232; - } - return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); - }, - enumerable: false - }, - hexToRgb: { - value: (hex) => { - const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - let { colorString } = matches.groups; - if (colorString.length === 3) { - colorString = colorString.split("").map((character) => character + character).join(""); - } - const integer = Number.parseInt(colorString, 16); - return [ - integer >> 16 & 255, - integer >> 8 & 255, - integer & 255 - ]; - }, - enumerable: false - }, - hexToAnsi256: { - value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), - enumerable: false - } - }); - return styles2; - } - Object.defineProperty(module2, "exports", { - enumerable: true, - get: assembleStyles - }); - } -}); - -// node_modules/@langchain/core/dist/tracers/console.js -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); - } catch (err) { - return fallback; - } -} -function formatKVMapItem(value) { - if (typeof value === "string") { - return value.trim(); - } - if (value === null || value === void 0) { - return value; - } - return tryJsonStringify(value, value.toString()); -} -function elapsed(run) { - if (!run.end_time) - return ""; - const elapsed2 = run.end_time - run.start_time; - if (elapsed2 < 1e3) { - return `${elapsed2}ms`; - } - return `${(elapsed2 / 1e3).toFixed(2)}s`; -} -var import_ansi_styles, color, ConsoleCallbackHandler; -var init_console = __esm({ - "node_modules/@langchain/core/dist/tracers/console.js"() { - import_ansi_styles = __toESM(require_ansi_styles(), 1); - init_base2(); - ({ color } = import_ansi_styles.default); - ConsoleCallbackHandler = class extends BaseTracer { - constructor() { - super(...arguments); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "console_callback_handler" - }); - } - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); - } - // utility methods - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; - } else { - break; - } - } - return parents; - } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run].map((parent, i3, arr2) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i3 === arr2.length - 1 ? wrap(import_ansi_styles.default.bold, name) : name; - }).join(" > "); - return wrap(color.grey, string); - } - // logging methods - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p3) => p3.trim()) } : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); - } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); - } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); - } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); - } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void - */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); - } - }; - } -}); - -// node_modules/@langchain/core/dist/errors/index.js -function addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message} - -Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/ -`; - return error; -} -var init_errors = __esm({ - "node_modules/@langchain/core/dist/errors/index.js"() { - } -}); - -// node_modules/@langchain/core/dist/tools/utils.js -function _isToolCall(toolCall) { - return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); -} -var ToolInputParsingException; -var init_utils = __esm({ - "node_modules/@langchain/core/dist/tools/utils.js"() { - ToolInputParsingException = class extends Error { - constructor(message, output) { - super(message); - Object.defineProperty(this, "output", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.output = output; - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/json.js -function parseJsonMarkdown(s4, parser = parsePartialJson) { - s4 = s4.trim(); - const match2 = /```(json)?(.*)```/s.exec(s4); - if (!match2) { - return parser(s4); - } else { - return parser(match2[2]); - } -} -function parsePartialJson(s4) { - if (typeof s4 === "undefined") { - return null; - } - try { - return JSON.parse(s4); - } catch (error) { - } - let new_s = ""; - const stack = []; - let isInsideString = false; - let escaped = false; - for (let char of s4) { - if (isInsideString) { - if (char === '"' && !escaped) { - isInsideString = false; - } else if (char === "\n" && !escaped) { - char = "\\n"; - } else if (char === "\\") { - escaped = !escaped; - } else { - escaped = false; - } - } else { - if (char === '"') { - isInsideString = true; - escaped = false; - } else if (char === "{") { - stack.push("}"); - } else if (char === "[") { - stack.push("]"); - } else if (char === "}" || char === "]") { - if (stack && stack[stack.length - 1] === char) { - stack.pop(); - } else { - return null; - } - } - } - new_s += char; - } - if (isInsideString) { - new_s += '"'; - } - for (let i3 = stack.length - 1; i3 >= 0; i3 -= 1) { - new_s += stack[i3]; - } - try { - return JSON.parse(new_s); - } catch (error) { - return null; - } -} -var init_json = __esm({ - "node_modules/@langchain/core/dist/utils/json.js"() { - } -}); - -// node_modules/@langchain/core/dist/messages/base.js -function mergeContent(firstContent, secondContent) { - if (typeof firstContent === "string") { - if (typeof secondContent === "string") { - return firstContent + secondContent; - } else { - return [{ type: "text", text: firstContent }, ...secondContent]; - } - } else if (Array.isArray(secondContent)) { - return _mergeLists(firstContent, secondContent) ?? [ - ...firstContent, - ...secondContent - ]; - } else { - return [...firstContent, { type: "text", text: secondContent }]; - } -} -function _mergeStatus(left, right) { - if (left === "error" || right === "error") { - return "error"; - } - return "success"; -} -function stringifyWithDepthLimit(obj, depthLimit) { - function helper(obj2, currentDepth) { - if (typeof obj2 !== "object" || obj2 === null || obj2 === void 0) { - return obj2; - } - if (currentDepth >= depthLimit) { - if (Array.isArray(obj2)) { - return "[Array]"; - } - return "[Object]"; - } - if (Array.isArray(obj2)) { - return obj2.map((item) => helper(item, currentDepth + 1)); - } - const result = {}; - for (const key of Object.keys(obj2)) { - result[key] = helper(obj2[key], currentDepth + 1); - } - return result; - } - return JSON.stringify(helper(obj, 0), null, 2); -} -function _mergeDicts(left, right) { - const merged = { ...left }; - for (const [key, value] of Object.entries(right)) { - if (merged[key] == null) { - merged[key] = value; - } else if (value == null) { - continue; - } else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) { - throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); - } else if (typeof merged[key] === "string") { - if (key === "type") { - continue; - } - merged[key] += value; - } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) { - merged[key] = _mergeDicts(merged[key], value); - } else if (Array.isArray(merged[key])) { - merged[key] = _mergeLists(merged[key], value); - } else if (merged[key] === value) { - continue; - } else { - console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); - } - } - return merged; -} -function _mergeLists(left, right) { - if (left === void 0 && right === void 0) { - return void 0; - } else if (left === void 0 || right === void 0) { - return left || right; - } else { - const merged = [...left]; - for (const item of right) { - if (typeof item === "object" && "index" in item && typeof item.index === "number") { - const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index); - if (toMerge !== -1) { - merged[toMerge] = _mergeDicts(merged[toMerge], item); - } else { - merged.push(item); - } - } else if (typeof item === "object" && "text" in item && item.text === "") { - continue; - } else { - merged.push(item); - } - } - return merged; - } -} -function _mergeObj(left, right) { - if (!left && !right) { - throw new Error("Cannot merge two undefined objects."); - } - if (!left || !right) { - return left || right; - } else if (typeof left !== typeof right) { - throw new Error(`Cannot merge objects of different types. -Left ${typeof left} -Right ${typeof right}`); - } else if (typeof left === "string" && typeof right === "string") { - return left + right; - } else if (Array.isArray(left) && Array.isArray(right)) { - return _mergeLists(left, right); - } else if (typeof left === "object" && typeof right === "object") { - return _mergeDicts(left, right); - } else if (left === right) { - return left; - } else { - throw new Error(`Can not merge objects of different types. -Left ${left} -Right ${right}`); - } -} -function _isMessageFieldWithRole(x2) { - return typeof x2.role === "string"; -} -function isBaseMessage(messageLike) { - return typeof messageLike?._getType === "function"; -} -function isBaseMessageChunk(messageLike) { - return isBaseMessage(messageLike) && typeof messageLike.concat === "function"; -} -var BaseMessage, BaseMessageChunk; -var init_base3 = __esm({ - "node_modules/@langchain/core/dist/messages/base.js"() { - init_serializable(); - BaseMessage = class extends Serializable { - get lc_aliases() { - return { - additional_kwargs: "additional_kwargs", - response_metadata: "response_metadata" - }; - } - /** - * @deprecated - * Use {@link BaseMessage.content} instead. - */ - get text() { - return typeof this.content === "string" ? this.content : ""; - } - /** The type of the message. */ - getType() { - return this._getType(); - } - constructor(fields, kwargs) { - if (typeof fields === "string") { - fields = { - content: fields, - additional_kwargs: kwargs, - response_metadata: {} - }; - } - if (!fields.additional_kwargs) { - fields.additional_kwargs = {}; - } - if (!fields.response_metadata) { - fields.response_metadata = {}; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "messages"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "content", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "additional_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "response_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = fields.name; - this.content = fields.content; - this.additional_kwargs = fields.additional_kwargs; - this.response_metadata = fields.response_metadata; - this.id = fields.id; - } - toDict() { - return { - type: this._getType(), - data: this.toJSON().kwargs - }; - } - static lc_name() { - return "BaseMessage"; - } - // Can't be protected for silly reasons - get _printableFields() { - return { - id: this.id, - content: this.content, - name: this.name, - additional_kwargs: this.additional_kwargs, - response_metadata: this.response_metadata - }; - } - // this private method is used to update the ID for the runtime - // value as well as in lc_kwargs for serialisation - _updateId(value) { - this.id = value; - this.lc_kwargs.id = value; - } - get [Symbol.toStringTag]() { - return this.constructor.lc_name(); - } - // Override the default behavior of console.log - [Symbol.for("nodejs.util.inspect.custom")](depth) { - if (depth === null) { - return this; - } - const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); - return `${this.constructor.lc_name()} ${printable}`; - } - }; - BaseMessageChunk = class extends BaseMessage { - }; - } -}); - -// node_modules/@langchain/core/dist/messages/tool.js -function isDirectToolOutput(x2) { - return x2 != null && typeof x2 === "object" && "lc_direct_tool_output" in x2 && x2.lc_direct_tool_output === true; -} -function defaultToolCallParser(rawToolCalls) { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCall of rawToolCalls) { - if (!toolCall.function) { - continue; - } else { - const functionName = toolCall.function.name; - try { - const functionArgs = JSON.parse(toolCall.function.arguments); - const parsed = { - name: functionName || "", - args: functionArgs || {}, - id: toolCall.id - }; - toolCalls.push(parsed); - } catch (error) { - invalidToolCalls.push({ - name: functionName, - args: toolCall.function.arguments, - id: toolCall.id, - error: "Malformed args." - }); - } - } - } - return [toolCalls, invalidToolCalls]; -} -var ToolMessage, ToolMessageChunk; -var init_tool = __esm({ - "node_modules/@langchain/core/dist/messages/tool.js"() { - init_base3(); - ToolMessage = class extends BaseMessage { - static lc_name() { - return "ToolMessage"; - } - get lc_aliases() { - return { tool_call_id: "tool_call_id" }; - } - constructor(fields, tool_call_id, name) { - if (typeof fields === "string") { - fields = { content: fields, name, tool_call_id }; - } - super(fields); - Object.defineProperty(this, "lc_direct_tool_output", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tool_call_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "artifact", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; - } - _getType() { - return "tool"; - } - static isInstance(message) { - return message._getType() === "tool"; - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } - }; - ToolMessageChunk = class extends BaseMessageChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "tool_call_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "artifact", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; - } - static lc_name() { - return "ToolMessageChunk"; - } - _getType() { - return "tool"; - } - concat(chunk) { - return new ToolMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - artifact: _mergeObj(this.artifact, chunk.artifact), - tool_call_id: this.tool_call_id, - id: this.id ?? chunk.id, - status: _mergeStatus(this.status, chunk.status) - }); - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/ai.js -function isAIMessage(x2) { - return x2._getType() === "ai"; -} -function isAIMessageChunk(x2) { - return x2._getType() === "ai"; -} -var AIMessage, AIMessageChunk; -var init_ai = __esm({ - "node_modules/@langchain/core/dist/messages/ai.js"() { - init_json(); - init_base3(); - init_tool(); - AIMessage = class extends BaseMessage { - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls" - }; - } - constructor(fields, kwargs) { - let initParams; - if (typeof fields === "string") { - initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - additional_kwargs: kwargs ?? {} - }; - } else { - initParams = fields; - const rawToolCalls = initParams.additional_kwargs?.tool_calls; - const toolCalls = initParams.tool_calls; - if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) { - console.warn([ - "New LangChain packages are available that more efficiently handle", - "tool calling.\n\nPlease upgrade your packages to versions that set", - "message tool calls. e.g., `yarn add @langchain/anthropic`,", - "yarn add @langchain/openai`, etc." - ].join(" ")); - } - try { - if (!(rawToolCalls == null) && toolCalls === void 0) { - const [toolCalls2, invalidToolCalls] = defaultToolCallParser(rawToolCalls); - initParams.tool_calls = toolCalls2 ?? []; - initParams.invalid_tool_calls = invalidToolCalls ?? []; - } else { - initParams.tool_calls = initParams.tool_calls ?? []; - initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; - } - } catch (e3) { - initParams.tool_calls = []; - initParams.invalid_tool_calls = []; - } - } - super(initParams); - Object.defineProperty(this, "tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "invalid_tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "usage_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (typeof initParams !== "string") { - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - } - this.usage_metadata = initParams.usage_metadata; - } - static lc_name() { - return "AIMessage"; - } - _getType() { - return "ai"; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - }; - AIMessageChunk = class extends BaseMessageChunk { - constructor(fields) { - let initParams; - if (typeof fields === "string") { - initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - tool_call_chunks: [] - }; - } else if (fields.tool_call_chunks === void 0) { - initParams = { - ...fields, - tool_calls: fields.tool_calls ?? [], - invalid_tool_calls: [], - tool_call_chunks: [], - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - } else { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCallChunk of fields.tool_call_chunks) { - let parsedArgs = {}; - try { - parsedArgs = parsePartialJson(toolCallChunk.args || "{}"); - if (parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) { - throw new Error("Malformed tool call chunk args."); - } - toolCalls.push({ - name: toolCallChunk.name ?? "", - args: parsedArgs, - id: toolCallChunk.id, - type: "tool_call" - }); - } catch (e3) { - invalidToolCalls.push({ - name: toolCallChunk.name, - args: toolCallChunk.args, - id: toolCallChunk.id, - error: "Malformed args.", - type: "invalid_tool_call" - }); - } - } - initParams = { - ...fields, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls, - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - } - super(initParams); - Object.defineProperty(this, "tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "invalid_tool_calls", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "tool_call_chunks", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "usage_metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - this.usage_metadata = initParams.usage_metadata; - } - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls", - tool_call_chunks: "tool_call_chunks" - }; - } - static lc_name() { - return "AIMessageChunk"; - } - _getType() { - return "ai"; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - tool_call_chunks: this.tool_call_chunks, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - concat(chunk) { - const combinedFields = { - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - tool_call_chunks: [], - id: this.id ?? chunk.id - }; - if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { - const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); - if (rawToolCalls !== void 0 && rawToolCalls.length > 0) { - combinedFields.tool_call_chunks = rawToolCalls; - } - } - if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) { - const inputTokenDetails = { - ...(this.usage_metadata?.input_token_details?.audio !== void 0 || chunk.usage_metadata?.input_token_details?.audio !== void 0) && { - audio: (this.usage_metadata?.input_token_details?.audio ?? 0) + (chunk.usage_metadata?.input_token_details?.audio ?? 0) - }, - ...(this.usage_metadata?.input_token_details?.cache_read !== void 0 || chunk.usage_metadata?.input_token_details?.cache_read !== void 0) && { - cache_read: (this.usage_metadata?.input_token_details?.cache_read ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_read ?? 0) - }, - ...(this.usage_metadata?.input_token_details?.cache_creation !== void 0 || chunk.usage_metadata?.input_token_details?.cache_creation !== void 0) && { - cache_creation: (this.usage_metadata?.input_token_details?.cache_creation ?? 0) + (chunk.usage_metadata?.input_token_details?.cache_creation ?? 0) - } - }; - const outputTokenDetails = { - ...(this.usage_metadata?.output_token_details?.audio !== void 0 || chunk.usage_metadata?.output_token_details?.audio !== void 0) && { - audio: (this.usage_metadata?.output_token_details?.audio ?? 0) + (chunk.usage_metadata?.output_token_details?.audio ?? 0) - }, - ...(this.usage_metadata?.output_token_details?.reasoning !== void 0 || chunk.usage_metadata?.output_token_details?.reasoning !== void 0) && { - reasoning: (this.usage_metadata?.output_token_details?.reasoning ?? 0) + (chunk.usage_metadata?.output_token_details?.reasoning ?? 0) - } - }; - const left = this.usage_metadata ?? { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0 - }; - const right = chunk.usage_metadata ?? { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0 - }; - const usage_metadata = { - input_tokens: left.input_tokens + right.input_tokens, - output_tokens: left.output_tokens + right.output_tokens, - total_tokens: left.total_tokens + right.total_tokens, - // Do not include `input_token_details` / `output_token_details` keys in combined fields - // unless their values are defined. - ...Object.keys(inputTokenDetails).length > 0 && { - input_token_details: inputTokenDetails - }, - ...Object.keys(outputTokenDetails).length > 0 && { - output_token_details: outputTokenDetails - } - }; - combinedFields.usage_metadata = usage_metadata; - } - return new AIMessageChunk(combinedFields); - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/chat.js -var ChatMessage, ChatMessageChunk; -var init_chat = __esm({ - "node_modules/@langchain/core/dist/messages/chat.js"() { - init_base3(); - ChatMessage = class extends BaseMessage { - static lc_name() { - return "ChatMessage"; - } - static _chatMessageClass() { - return ChatMessage; - } - constructor(fields, role) { - if (typeof fields === "string") { - fields = { content: fields, role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; - } - _getType() { - return "generic"; - } - static isInstance(message) { - return message._getType() === "generic"; - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } - }; - ChatMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "ChatMessageChunk"; - } - constructor(fields, role) { - if (typeof fields === "string") { - fields = { content: fields, role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; - } - _getType() { - return "generic"; - } - concat(chunk) { - return new ChatMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - role: this.role, - id: this.id ?? chunk.id - }); - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/function.js -var FunctionMessageChunk; -var init_function = __esm({ - "node_modules/@langchain/core/dist/messages/function.js"() { - init_base3(); - FunctionMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "FunctionMessageChunk"; - } - _getType() { - return "function"; - } - concat(chunk) { - return new FunctionMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - name: this.name ?? "", - id: this.id ?? chunk.id - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/human.js -var HumanMessage, HumanMessageChunk; -var init_human = __esm({ - "node_modules/@langchain/core/dist/messages/human.js"() { - init_base3(); - HumanMessage = class extends BaseMessage { - static lc_name() { - return "HumanMessage"; - } - _getType() { - return "human"; - } - }; - HumanMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "HumanMessageChunk"; - } - _getType() { - return "human"; - } - concat(chunk) { - return new HumanMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/system.js -var SystemMessage, SystemMessageChunk; -var init_system = __esm({ - "node_modules/@langchain/core/dist/messages/system.js"() { - init_base3(); - SystemMessage = class extends BaseMessage { - static lc_name() { - return "SystemMessage"; - } - _getType() { - return "system"; - } - }; - SystemMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "SystemMessageChunk"; - } - _getType() { - return "system"; - } - concat(chunk) { - return new SystemMessageChunk({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/messages/utils.js -function _coerceToolCall(toolCall) { - if (_isToolCall(toolCall)) { - return toolCall; - } else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") { - return { - id: toolCall.id, - args: JSON.parse(toolCall.function.arguments), - name: toolCall.function.name, - type: "tool_call" - }; - } else { - return toolCall; - } -} -function isSerializedConstructor(x2) { - return typeof x2 === "object" && x2 != null && x2.lc === 1 && Array.isArray(x2.id) && x2.kwargs != null && typeof x2.kwargs === "object"; -} -function _constructMessageFromParams(params) { - let type; - let rest; - if (isSerializedConstructor(params)) { - const className = params.id.at(-1); - if (className === "HumanMessage" || className === "HumanMessageChunk") { - type = "user"; - } else if (className === "AIMessage" || className === "AIMessageChunk") { - type = "assistant"; - } else if (className === "SystemMessage" || className === "SystemMessageChunk") { - type = "system"; - } else { - type = "unknown"; - } - rest = params.kwargs; - } else { - const { type: extractedType, ...otherParams } = params; - type = extractedType; - rest = otherParams; - } - if (type === "human" || type === "user") { - return new HumanMessage(rest); - } else if (type === "ai" || type === "assistant") { - const { tool_calls: rawToolCalls, ...other } = rest; - if (!Array.isArray(rawToolCalls)) { - return new AIMessage(rest); - } - const tool_calls = rawToolCalls.map(_coerceToolCall); - return new AIMessage({ ...other, tool_calls }); - } else if (type === "system") { - return new SystemMessage(rest); - } else if (type === "developer") { - return new SystemMessage({ - ...rest, - additional_kwargs: { - ...rest.additional_kwargs, - __openai_role__: "developer" - } - }); - } else if (type === "tool" && "tool_call_id" in rest) { - return new ToolMessage({ - ...rest, - content: rest.content, - tool_call_id: rest.tool_call_id, - name: rest.name - }); - } else { - const error = addLangChainErrorFields(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. - -Received: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); - throw error; - } -} -function coerceMessageLikeToMessage(messageLike) { - if (typeof messageLike === "string") { - return new HumanMessage(messageLike); - } else if (isBaseMessage(messageLike)) { - return messageLike; - } - if (Array.isArray(messageLike)) { - const [type, content] = messageLike; - return _constructMessageFromParams({ type, content }); - } else if (_isMessageFieldWithRole(messageLike)) { - const { role: type, ...rest } = messageLike; - return _constructMessageFromParams({ ...rest, type }); - } else { - return _constructMessageFromParams(messageLike); - } -} -function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { - const string_messages = []; - for (const m3 of messages) { - let role; - if (m3._getType() === "human") { - role = humanPrefix; - } else if (m3._getType() === "ai") { - role = aiPrefix; - } else if (m3._getType() === "system") { - role = "System"; - } else if (m3._getType() === "function") { - role = "Function"; - } else if (m3._getType() === "tool") { - role = "Tool"; - } else if (m3._getType() === "generic") { - role = m3.role; - } else { - throw new Error(`Got unsupported message type: ${m3._getType()}`); - } - const nameStr = m3.name ? `${m3.name}, ` : ""; - const readableContent = typeof m3.content === "string" ? m3.content : JSON.stringify(m3.content, null, 2); - string_messages.push(`${role}: ${nameStr}${readableContent}`); - } - return string_messages.join("\n"); -} -function convertToChunk(message) { - const type = message._getType(); - if (type === "human") { - return new HumanMessageChunk({ ...message }); - } else if (type === "ai") { - let aiChunkFields = { - ...message - }; - if ("tool_calls" in aiChunkFields) { - aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: void 0, - args: JSON.stringify(tc.args) - })) - }; - } - return new AIMessageChunk({ ...aiChunkFields }); - } else if (type === "system") { - return new SystemMessageChunk({ ...message }); - } else if (type === "function") { - return new FunctionMessageChunk({ ...message }); - } else if (ChatMessage.isInstance(message)) { - return new ChatMessageChunk({ ...message }); - } else { - throw new Error("Unknown message type."); - } -} -var init_utils2 = __esm({ - "node_modules/@langchain/core/dist/messages/utils.js"() { - init_errors(); - init_utils(); - init_ai(); - init_base3(); - init_chat(); - init_function(); - init_human(); - init_system(); - init_tool(); - } -}); - -// node_modules/langsmith/run_trees.js -var init_run_trees2 = __esm({ - "node_modules/langsmith/run_trees.js"() { - init_run_trees(); - } -}); - -// node_modules/langsmith/index.js -var init_langsmith = __esm({ - "node_modules/langsmith/index.js"() { - init_dist(); - } -}); - -// node_modules/@langchain/core/dist/singletons/tracer.js -var client, getDefaultLangChainClientSingleton; -var init_tracer = __esm({ - "node_modules/@langchain/core/dist/singletons/tracer.js"() { - init_langsmith(); - init_env3(); - getDefaultLangChainClientSingleton = () => { - if (client === void 0) { - const clientParams = getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { - // LangSmith has its own backgrounding system - blockOnRootRunFinalization: true - } : {}; - client = new Client(clientParams); - } - return client; - }; - } -}); - -// node_modules/@langchain/core/dist/tracers/tracer_langchain.js -var LangChainTracer; -var init_tracer_langchain = __esm({ - "node_modules/@langchain/core/dist/tracers/tracer_langchain.js"() { - init_run_trees2(); - init_traceable2(); - init_env3(); - init_base2(); - init_tracer(); - LangChainTracer = class extends BaseTracer { - constructor(fields = {}) { - super(fields); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "langchain_tracer" - }); - Object.defineProperty(this, "projectName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "exampleId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const { exampleId, projectName, client: client2 } = fields; - this.projectName = projectName ?? getEnvironmentVariable2("LANGCHAIN_PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION"); - this.exampleId = exampleId; - this.client = client2 ?? getDefaultLangChainClientSingleton(); - const traceableTree = LangChainTracer.getTraceableRunTree(); - if (traceableTree) { - this.updateFromRunTree(traceableTree); - } - } - async _convertToCreate(run, example_id = void 0) { - return { - ...run, - extra: { - ...run.extra, - runtime: await getRuntimeEnvironment2() - }, - child_runs: void 0, - session_name: this.projectName, - reference_example_id: run.parent_run_id ? void 0 : example_id - }; - } - async persistRun(_run) { - } - async onRunCreate(run) { - const persistedRun = await this._convertToCreate(run, this.exampleId); - await this.client.createRun(persistedRun); - } - async onRunUpdate(run) { - const runUpdate = { - end_time: run.end_time, - error: run.error, - outputs: run.outputs, - events: run.events, - inputs: run.inputs, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - parent_run_id: run.parent_run_id, - extra: run.extra - }; - await this.client.updateRun(run.id, runUpdate); - } - getRun(id) { - return this.runMap.get(id); - } - updateFromRunTree(runTree) { - let rootRun = runTree; - const visited = /* @__PURE__ */ new Set(); - while (rootRun.parent_run) { - if (visited.has(rootRun.id)) - break; - visited.add(rootRun.id); - if (!rootRun.parent_run) - break; - rootRun = rootRun.parent_run; - } - visited.clear(); - const queue2 = [rootRun]; - while (queue2.length > 0) { - const current = queue2.shift(); - if (!current || visited.has(current.id)) - continue; - visited.add(current.id); - this.runMap.set(current.id, current); - if (current.child_runs) { - queue2.push(...current.child_runs); - } - } - this.client = runTree.client ?? this.client; - this.projectName = runTree.project_name ?? this.projectName; - this.exampleId = runTree.reference_example_id ?? this.exampleId; - } - convertToRunTree(id) { - const runTreeMap = {}; - const runTreeList = []; - for (const [id2, run] of this.runMap) { - const runTree = new RunTree({ - ...run, - child_runs: [], - parent_run: void 0, - // inherited properties - client: this.client, - project_name: this.projectName, - reference_example_id: this.exampleId, - tracingEnabled: true - }); - runTreeMap[id2] = runTree; - runTreeList.push([id2, run.dotted_order]); - } - runTreeList.sort((a3, b3) => { - if (!a3[1] || !b3[1]) - return 0; - return a3[1].localeCompare(b3[1]); - }); - for (const [id2] of runTreeList) { - const run = this.runMap.get(id2); - const runTree = runTreeMap[id2]; - if (!run || !runTree) - continue; - if (run.parent_run_id) { - const parentRunTree = runTreeMap[run.parent_run_id]; - if (parentRunTree) { - parentRunTree.child_runs.push(runTree); - runTree.parent_run = parentRunTree; - } - } - } - return runTreeMap[id]; - } - static getTraceableRunTree() { - try { - return getCurrentRunTree(); - } catch { - return void 0; - } - } - }; - } -}); - -// node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js -var TRACING_ALS_KEY2, _CONTEXT_VARIABLES_KEY, setGlobalAsyncLocalStorageInstance, getGlobalAsyncLocalStorageInstance; -var init_globals = __esm({ - "node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js"() { - TRACING_ALS_KEY2 = Symbol.for("ls:tracing_async_local_storage"); - _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); - setGlobalAsyncLocalStorageInstance = (instance) => { - globalThis[TRACING_ALS_KEY2] = instance; - }; - getGlobalAsyncLocalStorageInstance = () => { - return globalThis[TRACING_ALS_KEY2]; - }; - } -}); - -// node_modules/@langchain/core/dist/singletons/callbacks.js -function createQueue() { - const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default; - return new PQueue({ - autoStart: true, - concurrency: 1 - }); -} -function getQueue() { - if (typeof queue === "undefined") { - queue = createQueue(); - } - return queue; -} -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) { - await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - } else { - await promiseFn(); - } - } else { - queue = getQueue(); - void queue.add(async () => { - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) { - await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - } else { - await promiseFn(); - } - }); - } -} -var import_p_queue2, queue; -var init_callbacks = __esm({ - "node_modules/@langchain/core/dist/singletons/callbacks.js"() { - import_p_queue2 = __toESM(require_dist(), 1); - init_globals(); - } -}); - -// node_modules/@langchain/core/dist/callbacks/promises.js -var init_promises = __esm({ - "node_modules/@langchain/core/dist/callbacks/promises.js"() { - init_callbacks(); - } -}); - -// node_modules/@langchain/core/dist/utils/callbacks.js -var isTracingEnabled2; -var init_callbacks2 = __esm({ - "node_modules/@langchain/core/dist/utils/callbacks.js"() { - init_env3(); - isTracingEnabled2 = (tracingEnabled) => { - if (tracingEnabled !== void 0) { - return tracingEnabled; - } - const envVars = [ - "LANGSMITH_TRACING_V2", - "LANGCHAIN_TRACING_V2", - "LANGSMITH_TRACING", - "LANGCHAIN_TRACING" - ]; - return !!envVars.find((envVar) => getEnvironmentVariable2(envVar) === "true"); - }; - } -}); - -// node_modules/@langchain/core/dist/singletons/async_local_storage/context.js -function getContextVariable(name) { - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === void 0) { - return void 0; - } - const runTree = asyncLocalStorageInstance.getStore(); - return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name]; -} -var LC_CONFIGURE_HOOKS_KEY, _getConfigureHooks; -var init_context = __esm({ - "node_modules/@langchain/core/dist/singletons/async_local_storage/context.js"() { - init_run_trees2(); - init_globals(); - LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); - _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; - } -}); - -// node_modules/@langchain/core/dist/callbacks/manager.js -function parseCallbackConfigArg(arg) { - if (!arg) { - return {}; - } else if (Array.isArray(arg) || "name" in arg) { - return { callbacks: arg }; - } else { - return arg; - } -} -function ensureHandler(handler) { - if ("name" in handler) { - return handler; - } - return BaseCallbackHandler.fromMethods(handler); -} -var BaseCallbackManager, BaseRunManager, CallbackManagerForRetrieverRun, CallbackManagerForLLMRun, CallbackManagerForChainRun, CallbackManagerForToolRun, CallbackManager; -var init_manager = __esm({ - "node_modules/@langchain/core/dist/callbacks/manager.js"() { - init_esm_browser(); - init_base(); - init_console(); - init_utils2(); - init_env3(); - init_tracer_langchain(); - init_promises(); - init_callbacks2(); - init_base2(); - init_context(); - BaseCallbackManager = class { - setHandler(handler) { - return this.setHandlers([handler]); - } - }; - BaseRunManager = class { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - Object.defineProperty(this, "runId", { - enumerable: true, - configurable: true, - writable: true, - value: runId - }); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: handlers - }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableHandlers - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: tags - }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableTags - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: metadata - }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableMetadata - }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: _parentRunId - }); - } - get parentRunId() { - return this._parentRunId; - } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } - async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } - }; - CallbackManagerForRetrieverRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); - } catch (error) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - }; - CallbackManagerForLLMRun = class extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err2) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`); - if (handler.raiseError) { - throw err2; - } - } - } - }, handler.awaitHandlers))); - } - async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - }; - CallbackManagerForChainRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err2) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`); - if (handler.raiseError) { - throw err2; - } - } - } - }, handler.awaitHandlers))); - } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - }; - CallbackManagerForToolRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } catch (err2) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`); - if (handler.raiseError) { - throw err2; - } - } - } - }, handler.awaitHandlers))); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - }; - CallbackManager = class extends BaseCallbackManager { - constructor(parentRunId, options) { - super(); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "callback_manager" - }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.handlers = options?.handlers ?? this.handlers; - this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; - this.tags = options?.tags ?? this.tags; - this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; - this.metadata = options?.metadata ?? this.metadata; - this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; - this._parentRunId = parentRunId; - } - /** - * Gets the parent run ID, if any. - * - * @returns The parent run ID. - */ - getParentRunId() { - return this._parentRunId; - } - async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(prompts.map(async (prompt, idx) => { - const runId_ = idx === 0 && runId ? runId : v4_default(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(messages.map(async (messageGroup, idx) => { - const runId_ = idx === 0 && runId ? runId : v4_default(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - if (handler.handleChatModelStart) { - await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } else if (handler.handleLLMStart) { - const messageString = getBufferString(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChainStart(chain, inputs, runId = v4_default(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreChain) { - return; - } - if (isBaseTracer(handler)) { - handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - } - return consumeCallback(async () => { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool2, input, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreAgent) { - return; - } - if (isBaseTracer(handler)) { - handler._createRunForToolStart(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleToolStart?.(tool2, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreRetriever) { - return; - } - if (isBaseTracer(handler)) { - handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleCustomEvent(eventName, data, runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreCustomEvent) { - try { - await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) { - this.inheritableHandlers.push(handler); - } - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) { - this.addHandler(handler, inherit); - } - } - addTags(tags, inherit = true) { - this.removeTags(tags); - this.tags.push(...tags); - if (inherit) { - this.inheritableTags.push(...tags); - } - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { ...this.metadata, ...metadata }; - if (inherit) { - this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; - } - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; - } - } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); - } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); - } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); - } - for (const handler of additionalHandlers) { - if ( - // Prevent multiple copies of console_callback_handler - manager.handlers.filter((h3) => h3.name === "console_callback_handler").some((h3) => h3.name === handler.name) - ) { - continue; - } - manager.addHandler(handler, inherit); - } - return manager; - } - static fromHandlers(handlers) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4_default() - }); - Object.assign(this, handlers); - } - } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); - } - // TODO: Deprecate async method in favor of this one. - static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); - } else { - callbackManager = inheritableHandlers; - } - callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); - } - const verboseEnabled = getEnvironmentVariable2("LANGCHAIN_VERBOSE") === "true" || options?.verbose; - const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled2(); - const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable2("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) { - callbackManager = new CallbackManager(); - } - if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); - } - if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - const tracerV2 = new LangChainTracer(); - callbackManager.addHandler(tracerV2, true); - callbackManager._parentRunId = LangChainTracer.getTraceableRunTree()?.id ?? callbackManager._parentRunId; - } - } - } - for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { - const createIfNotInContext = envVar && getEnvironmentVariable2(envVar) === "true" && handlerClass; - let handler; - const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; - if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { - handler = contextVarValue; - } else if (createIfNotInContext) { - handler = new handlerClass({}); - } - if (handler !== void 0) { - if (!callbackManager) { - callbackManager = new CallbackManager(); - } - if (!callbackManager.handlers.some((h3) => h3.name === handler.name)) { - callbackManager.addHandler(handler, inheritable); - } - } - } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); - } - } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); - } - } - return callbackManager; - } - }; - } -}); - -// node_modules/@langchain/core/dist/singletons/async_local_storage/index.js -var MockAsyncLocalStorage2, mockAsyncLocalStorage2, LC_CHILD_KEY, AsyncLocalStorageProvider2, AsyncLocalStorageProviderSingleton2; -var init_async_local_storage = __esm({ - "node_modules/@langchain/core/dist/singletons/async_local_storage/index.js"() { - init_langsmith(); - init_globals(); - init_manager(); - MockAsyncLocalStorage2 = class { - getStore() { - return void 0; - } - run(_store, callback) { - return callback(); - } - enterWith(_store) { - return void 0; - } - }; - mockAsyncLocalStorage2 = new MockAsyncLocalStorage2(); - LC_CHILD_KEY = Symbol.for("lc:child_config"); - AsyncLocalStorageProvider2 = class { - getInstance() { - return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage2; - } - getRunnableConfig() { - const storage = this.getInstance(); - return storage.getStore()?.extra?.[LC_CHILD_KEY]; - } - runWithConfig(config, callback, avoidCreatingRootRunTree) { - const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); - const storage = this.getInstance(); - const previousValue = storage.getStore(); - const parentRunId = callbackManager?.getParentRunId(); - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); - let runTree; - if (langChainTracer && parentRunId) { - runTree = langChainTracer.convertToRunTree(parentRunId); - } else if (!avoidCreatingRootRunTree) { - runTree = new RunTree({ - name: "", - tracingEnabled: false - }); - } - if (runTree) { - runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; - } - if (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) { - runTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY]; - } - return storage.run(runTree, callback); - } - initializeGlobalInstance(instance) { - if (getGlobalAsyncLocalStorageInstance() === void 0) { - setGlobalAsyncLocalStorageInstance(instance); - } - } - }; - AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2(); - } -}); - -// node_modules/@langchain/core/dist/singletons/index.js -var init_singletons = __esm({ - "node_modules/@langchain/core/dist/singletons/index.js"() { - init_async_local_storage(); - init_globals(); - } -}); - -// node_modules/@langchain/core/dist/runnables/config.js -async function getCallbackManagerForConfig(config) { - return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); -} -function mergeConfigs(...configs) { - const copy = {}; - for (const options of configs.filter((c4) => !!c4)) { - for (const key of Object.keys(options)) { - if (key === "metadata") { - copy[key] = { ...copy[key], ...options[key] }; - } else if (key === "tags") { - const baseKeys = copy[key] ?? []; - copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; - } else if (key === "configurable") { - copy[key] = { ...copy[key], ...options[key] }; - } else if (key === "timeout") { - if (copy.timeout === void 0) { - copy.timeout = options.timeout; - } else if (options.timeout !== void 0) { - copy.timeout = Math.min(copy.timeout, options.timeout); - } - } else if (key === "signal") { - if (copy.signal === void 0) { - copy.signal = options.signal; - } else if (options.signal !== void 0) { - if ("any" in AbortSignal) { - copy.signal = AbortSignal.any([ - copy.signal, - options.signal - ]); - } else { - copy.signal = options.signal; - } - } - } else if (key === "callbacks") { - const baseCallbacks = copy.callbacks; - const providedCallbacks = options.callbacks; - if (Array.isArray(providedCallbacks)) { - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } else if (Array.isArray(baseCallbacks)) { - copy.callbacks = baseCallbacks.concat(providedCallbacks); - } else { - const manager = baseCallbacks.copy(); - for (const callback of providedCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; - } - } else if (providedCallbacks) { - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } else if (Array.isArray(baseCallbacks)) { - const manager = providedCallbacks.copy(); - for (const callback of baseCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; - } else { - copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { - handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), - inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), - tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), - inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), - metadata: { - ...baseCallbacks.metadata, - ...providedCallbacks.metadata - } - }); - } - } - } else { - const typedKey = key; - copy[typedKey] = options[typedKey] ?? copy[typedKey]; - } - } - } - return copy; -} -function ensureConfig(config) { - const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - let empty = { - tags: [], - metadata: {}, - recursionLimit: 25, - runId: void 0 - }; - if (implicitConfig) { - const { runId, runName, ...rest } = implicitConfig; - empty = Object.entries(rest).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== void 0) { - currentConfig[key] = value; - } - return currentConfig; - }, - empty - ); - } - if (config) { - empty = Object.entries(config).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== void 0) { - currentConfig[key] = value; - } - return currentConfig; - }, - empty - ); - } - if (empty?.configurable) { - for (const key of Object.keys(empty.configurable)) { - if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) { - if (!empty.metadata) { - empty.metadata = {}; - } - empty.metadata[key] = empty.configurable[key]; - } - } - } - if (empty.timeout !== void 0) { - if (empty.timeout <= 0) { - throw new Error("Timeout must be a positive number"); - } - const timeoutSignal = AbortSignal.timeout(empty.timeout); - if (empty.signal !== void 0) { - if ("any" in AbortSignal) { - empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); - } - } else { - empty.signal = timeoutSignal; - } - delete empty.timeout; - } - return empty; -} -function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { - const newConfig = ensureConfig(config); - if (callbacks !== void 0) { - delete newConfig.runName; - newConfig.callbacks = callbacks; - } - if (recursionLimit !== void 0) { - newConfig.recursionLimit = recursionLimit; - } - if (maxConcurrency !== void 0) { - newConfig.maxConcurrency = maxConcurrency; - } - if (runName !== void 0) { - newConfig.runName = runName; - } - if (configurable !== void 0) { - newConfig.configurable = { ...newConfig.configurable, ...configurable }; - } - if (runId !== void 0) { - delete newConfig.runId; - } - return newConfig; -} -function pickRunnableConfigKeys(config) { - return config ? { - configurable: config.configurable, - recursionLimit: config.recursionLimit, - callbacks: config.callbacks, - tags: config.tags, - metadata: config.metadata, - maxConcurrency: config.maxConcurrency, - timeout: config.timeout, - signal: config.signal - } : void 0; -} -var DEFAULT_RECURSION_LIMIT, PRIMITIVES; -var init_config = __esm({ - "node_modules/@langchain/core/dist/runnables/config.js"() { - init_manager(); - init_singletons(); - DEFAULT_RECURSION_LIMIT = 25; - PRIMITIVES = /* @__PURE__ */ new Set(["string", "number", "boolean"]); - } -}); - -// node_modules/@langchain/core/dist/utils/signal.js -async function raceWithSignal(promise, signal) { - if (signal === void 0) { - return promise; - } - let listener; - return Promise.race([ - promise.catch((err) => { - if (!signal?.aborted) { - throw err; - } else { - return void 0; - } - }), - new Promise((_2, reject) => { - listener = () => { - reject(new Error("Aborted")); - }; - signal.addEventListener("abort", listener); - if (signal.aborted) { - reject(new Error("Aborted")); - } - }) - ]).finally(() => signal.removeEventListener("abort", listener)); -} -var init_signal = __esm({ - "node_modules/@langchain/core/dist/utils/signal.js"() { - } -}); - -// node_modules/@langchain/core/dist/utils/stream.js -function atee(iter, length = 2) { - const buffers = Array.from({ length }, () => []); - return buffers.map(async function* makeIter(buffer) { - while (true) { - if (buffer.length === 0) { - const result = await iter.next(); - for (const buffer2 of buffers) { - buffer2.push(result); - } - } else if (buffer[0].done) { - return; - } else { - yield buffer.shift().value; - } - } - }); -} -function concat(first, second2) { - if (Array.isArray(first) && Array.isArray(second2)) { - return first.concat(second2); - } else if (typeof first === "string" && typeof second2 === "string") { - return first + second2; - } else if (typeof first === "number" && typeof second2 === "number") { - return first + second2; - } else if ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - "concat" in first && // eslint-disable-next-line @typescript-eslint/no-explicit-any - typeof first.concat === "function" - ) { - return first.concat(second2); - } else if (typeof first === "object" && typeof second2 === "object") { - const chunk = { ...first }; - for (const [key, value] of Object.entries(second2)) { - if (key in chunk && !Array.isArray(chunk[key])) { - chunk[key] = concat(chunk[key], value); - } else { - chunk[key] = value; - } - } - return chunk; - } else { - throw new Error(`Cannot concat ${typeof first} and ${typeof second2}`); - } -} -async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { - const gen = new AsyncGeneratorWithSetup({ - generator, - startSetup, - signal - }); - const setup = await gen.setup; - return { output: to(gen, setup, ...args), setup }; -} -var IterableReadableStream, AsyncGeneratorWithSetup; -var init_stream = __esm({ - "node_modules/@langchain/core/dist/utils/stream.js"() { - init_config(); - init_singletons(); - init_signal(); - IterableReadableStream = class extends ReadableStream { - constructor() { - super(...arguments); - Object.defineProperty(this, "reader", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - ensureReader() { - if (!this.reader) { - this.reader = this.getReader(); - } - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); - return { - done: true, - value: void 0 - }; - } else { - return { - done: false, - value: result.value - }; - } - } catch (e3) { - this.reader.releaseLock(); - throw e3; - } - } - async return() { - this.ensureReader(); - if (this.locked) { - const cancelPromise2 = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise2; - } - return { done: true, value: void 0 }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async throw(e3) { - this.ensureReader(); - if (this.locked) { - const cancelPromise2 = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise2; - } - throw e3; - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); - } - static fromReadableStream(stream) { - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump(); - }); - } - }, - cancel() { - reader.releaseLock(); - } - }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - if (done) { - controller.close(); - } - controller.enqueue(value); - }, - async cancel(reason) { - await generator.return(reason); - } - }); - } - }; - AsyncGeneratorWithSetup = class { - constructor(params) { - Object.defineProperty(this, "generator", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "setup", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "signal", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "firstResult", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "firstResultUsed", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - this.generator = params.generator; - this.config = params.config; - this.signal = params.signal ?? this.config?.signal; - this.setup = new Promise((resolve, reject) => { - void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(params.config), async () => { - this.firstResult = params.generator.next(); - if (params.startSetup) { - this.firstResult.then(params.startSetup).then(resolve, reject); - } else { - this.firstResult.then((_result) => resolve(void 0), reject); - } - }, true); - }); - } - async next(...args) { - this.signal?.throwIfAborted(); - if (!this.firstResultUsed) { - this.firstResultUsed = true; - return this.firstResult; - } - return AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(this.config), this.signal ? async () => { - return raceWithSignal(this.generator.next(...args), this.signal); - } : async () => { - return this.generator.next(...args); - }, true); - } - async return(value) { - return this.generator.return(value); - } - async throw(e3) { - return this.generator.throw(e3); - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); - } - }; - } -}); - -// node_modules/@langchain/core/dist/tracers/log_stream.js -async function _getStandardizedInputs(run, schemaFormat) { - if (schemaFormat === "original") { - throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); - } - const { inputs } = run; - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return inputs; - } - if (Object.keys(inputs).length === 1 && inputs?.input === "") { - return void 0; - } - return inputs.input; -} -async function _getStandardizedOutputs(run, schemaFormat) { - const { outputs } = run; - if (schemaFormat === "original") { - return outputs; - } - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return outputs; - } - if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) { - return outputs.output; - } - return outputs; -} -function isChatGenerationChunk(x2) { - return x2 !== void 0 && x2.message !== void 0; -} -var RunLogPatch, RunLog, isLogStreamHandler, LogStreamCallbackHandler; -var init_log_stream = __esm({ - "node_modules/@langchain/core/dist/tracers/log_stream.js"() { - init_fast_json_patch(); - init_base2(); - init_stream(); - init_ai(); - RunLogPatch = class { - constructor(fields) { - Object.defineProperty(this, "ops", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch({}, ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } - }; - RunLog = class extends RunLogPatch { - constructor(fields) { - super(fields); - Object.defineProperty(this, "state", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch(this.state, other.ops); - return new RunLog({ ops, state: states[states.length - 1].newDocument }); - } - static fromRunLogPatch(patch) { - const states = applyPatch({}, patch.ops); - return new RunLog({ - ops: patch.ops, - state: states[states.length - 1].newDocument - }); - } - }; - isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; - LogStreamCallbackHandler = class extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_schemaFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "original" - }); - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "keyMapByRunId", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "counterMapByRunName", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "log_stream_tracer" - }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) { - } - _includeRun(run) { - if (run.id === this.rootId) { - return false; - } - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) { - include = include || this.includeNames.includes(run.name); - } - if (this.includeTypes !== void 0) { - include = include || this.includeTypes.includes(run.run_type); - } - if (this.includeTags !== void 0) { - include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - } - if (this.excludeNames !== void 0) { - include = include && !this.excludeNames.includes(run.name); - } - if (this.excludeTypes !== void 0) { - include = include && !this.excludeTypes.includes(run.run_type); - } - if (this.excludeTags !== void 0) { - include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - } - return include; - } - async *tapOutputIterable(runId, output) { - for await (const chunk of output) { - if (runId !== this.rootId) { - const key = this.keyMapByRunId[runId]; - if (key) { - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk - } - ] - })); - } - } - yield chunk; - } - } - async onRunCreate(run) { - if (this.rootId === void 0) { - this.rootId = run.id; - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "replace", - path: "", - value: { - id: run.id, - name: run.name, - type: run.run_type, - streamed_output: [], - final_output: void 0, - logs: {} - } - } - ] - })); - } - if (!this._includeRun(run)) { - return; - } - if (this.counterMapByRunName[run.name] === void 0) { - this.counterMapByRunName[run.name] = 0; - } - this.counterMapByRunName[run.name] += 1; - const count5 = this.counterMapByRunName[run.name]; - this.keyMapByRunId[run.id] = count5 === 1 ? run.name : `${run.name}:${count5}`; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: void 0, - end_time: void 0 - }; - if (this._schemaFormat === "streaming_events") { - logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); - } - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${this.keyMapByRunId[run.id]}`, - value: logEntry - } - ] - })); - } - async onRunUpdate(run) { - try { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) { - return; - } - const ops = []; - if (this._schemaFormat === "streaming_events") { - ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run, this._schemaFormat) - }); - } - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run, this._schemaFormat) - }); - if (run.end_time !== void 0) { - ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run.end_time).toISOString() - }); - } - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); - } finally { - if (run.id === this.rootId) { - const patch = new RunLogPatch({ - ops: [ - { - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run, this._schemaFormat) - } - ] - }); - await this.writer.write(patch); - if (this.autoClose) { - await this.writer.close(); - } - } - } - } - async onLLMNewToken(run, token, kwargs) { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) { - return; - } - const isChatModel = run.inputs.messages !== void 0; - let streamedOutputValue; - if (isChatModel) { - if (isChatGenerationChunk(kwargs?.chunk)) { - streamedOutputValue = kwargs?.chunk; - } else { - streamedOutputValue = new AIMessageChunk({ - id: `run-${run.id}`, - content: token - }); - } - } else { - streamedOutputValue = token; - } - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token - }, - { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue - } - ] - }); - await this.writer.write(patch); - } - }; - } -}); - -// node_modules/@langchain/core/dist/outputs.js -var RUN_KEY, GenerationChunk, ChatGenerationChunk; -var init_outputs = __esm({ - "node_modules/@langchain/core/dist/outputs.js"() { - RUN_KEY = "__run"; - GenerationChunk = class { - constructor(fields) { - Object.defineProperty(this, "text", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "generationInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.text = fields.text; - this.generationInfo = fields.generationInfo; - } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - } - }); - } - }; - ChatGenerationChunk = class extends GenerationChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "message", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.message = fields.message; - } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - }, - message: this.message.concat(chunk.message) - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/tracers/event_stream.js -function assignName({ name, serialized }) { - if (name !== void 0) { - return name; - } - if (serialized?.name !== void 0) { - return serialized.name; - } else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) { - return serialized.id[serialized.id.length - 1]; - } - return "Unnamed"; -} -var isStreamEventsHandler, EventStreamCallbackHandler; -var init_event_stream = __esm({ - "node_modules/@langchain/core/dist/tracers/event_stream.js"() { - init_base2(); - init_stream(); - init_ai(); - init_outputs(); - isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; - EventStreamCallbackHandler = class extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "runInfoMap", { - enumerable: true, - configurable: true, - writable: true, - value: /* @__PURE__ */ new Map() - }); - Object.defineProperty(this, "tappedPromises", { - enumerable: true, - configurable: true, - writable: true, - value: /* @__PURE__ */ new Map() - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "event_stream_tracer" - }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) { - } - _includeRun(run) { - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) { - include = include || this.includeNames.includes(run.name); - } - if (this.includeTypes !== void 0) { - include = include || this.includeTypes.includes(run.runType); - } - if (this.includeTags !== void 0) { - include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - } - if (this.excludeNames !== void 0) { - include = include && !this.excludeNames.includes(run.name); - } - if (this.excludeTypes !== void 0) { - include = include && !this.excludeTypes.includes(run.runType); - } - if (this.excludeTags !== void 0) { - include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - } - return include; - } - async *tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) { - return; - } - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) { - yield firstChunk.value; - return; - } - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") { - return new GenerationChunk({ text: data }); - } - return data; - } - let tappedPromise = this.tappedPromises.get(runId); - if (tappedPromise === void 0) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve) => { - tappedPromiseResolver = resolve; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {} - }; - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) - } - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, chunk) - } - }, runInfo); - } - yield chunk; - } - } finally { - tappedPromiseResolver(); - } - } else { - yield firstChunk.value; - for await (const chunk of outputStream) { - yield chunk; - } - } - } - async send(payload, run) { - if (this._includeRun(run)) { - await this.writer.write(payload); - } - } - async sendEndEvent(payload, run) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== void 0) { - void tappedPromise.then(() => { - void this.send(payload, run); - }); - } else { - await this.send(payload, run); - } - } - async onLLMStart(run) { - const runName = assignName(run); - const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run.inputs - }; - this.runInfoMap.set(run.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { - input: run.inputs - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onLLMNewToken(run, token, kwargs) { - const runInfo = this.runInfoMap.get(run.id); - let chunk; - let eventName; - if (runInfo === void 0) { - throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); - } - if (this.runInfoMap.size === 1) { - return; - } - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === void 0) { - chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` }); - } else { - chunk = kwargs.chunk.message; - } - } else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === void 0) { - chunk = new GenerationChunk({ text: token }); - } else { - chunk = kwargs.chunk; - } - } else { - throw new Error(`Unexpected run type ${runInfo.runType}`); - } - await this.send({ - event: eventName, - data: { - chunk - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onLLMEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - let eventName; - if (runInfo === void 0) { - throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); - } - const generations = run.outputs?.generations; - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== void 0) { - break; - } - output = generation[0]?.message; - } - eventName = "on_chat_model_end"; - } else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo - }; - }); - }), - llmOutput: run.outputs?.llmOutput ?? {} - }; - eventName = "on_llm_end"; - } else { - throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); - } - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onChainStart(run) { - const runName = assignName(run); - const runType = run.run_type ?? "chain"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: run.run_type - }; - let eventData = {}; - if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; - } else if (run.inputs.input !== void 0) { - eventData.input = run.inputs.input; - runInfo.inputs = run.inputs.input; - } else { - eventData.input = run.inputs; - runInfo.inputs = run.inputs; - } - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onChainEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) { - throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); - } - const eventName = `on_${run.run_type}_end`; - const inputs = run.inputs ?? runInfo.inputs ?? {}; - const outputs = run.outputs?.output ?? run.outputs; - const data = { - output: outputs, - input: inputs - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; - } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {} - }, runInfo); - } - async onToolStart(run) { - const runName = assignName(run); - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run.inputs ?? {} - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { - input: run.inputs ?? {} - }, - name: runName, - run_id: run.id, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onToolEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) { - throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); - } - if (runInfo.inputs === void 0) { - throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); - } - const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onRetrieverStart(run) { - const runName = assignName(run); - const runType = "retriever"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: { - query: run.inputs.query - } - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { - input: { - query: run.inputs.query - } - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onRetrieverEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) { - throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); - } - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run.outputs?.documents ?? run.outputs, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) { - throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); - } - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data - }, runInfo); - } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - void Promise.all(pendingPromises).finally(() => { - void this.writer.close(); - }); - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/async_caller.js -var import_p_retry2, import_p_queue3, STATUS_NO_RETRY2, defaultFailedAttemptHandler, AsyncCaller2; -var init_async_caller2 = __esm({ - "node_modules/@langchain/core/dist/utils/async_caller.js"() { - import_p_retry2 = __toESM(require_p_retry(), 1); - import_p_queue3 = __toESM(require_dist(), 1); - STATUS_NO_RETRY2 = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 - // Conflict - ]; - defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") { - throw error; - } - if (error?.code === "ECONNABORTED") { - throw error; - } - const status = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error?.response?.status ?? error?.status - ); - if (status && STATUS_NO_RETRY2.includes(+status)) { - throw error; - } - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; - } - }; - AsyncCaller2 = class { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.queue.add(() => (0, import_p_retry2.default)(() => callable(...args).catch((error) => { - if (error instanceof Error) { - throw error; - } else { - throw new Error(error); - } - }), { - onFailedAttempt: this.onFailedAttempt, - retries: this.maxRetries, - randomize: true - // If needed we can change some of the defaults here, - // but they're quite sensible. - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_2, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }) - ]); - } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); - } - }; - } -}); - -// node_modules/@langchain/core/dist/tracers/root_listener.js -var RootListenersTracer; -var init_root_listener = __esm({ - "node_modules/@langchain/core/dist/tracers/root_listener.js"() { - init_base2(); - RootListenersTracer = class extends BaseTracer { - constructor({ config, onStart, onEnd, onError }) { - super({ _awaitHandler: true }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "RootListenersTracer" - }); - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnStart", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnEnd", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnError", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.config = config; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError; - } - /** - * This is a legacy method only called once for an entire run tree - * therefore not useful here - * @param {Run} _ Not used - */ - persistRun(_2) { - return Promise.resolve(); - } - async onRunCreate(run) { - if (this.rootId) { - return; - } - this.rootId = run.id; - if (this.argOnStart) { - await this.argOnStart(run, this.config); - } - } - async onRunUpdate(run) { - if (run.id !== this.rootId) { - return; - } - if (!run.error) { - if (this.argOnEnd) { - await this.argOnEnd(run, this.config); - } - } else if (this.argOnError) { - await this.argOnError(run, this.config); - } - } - }; - } -}); - -// node_modules/@langchain/core/dist/runnables/utils.js -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; -} -var _RootEventFilter; -var init_utils3 = __esm({ - "node_modules/@langchain/core/dist/runnables/utils.js"() { - _RootEventFilter = class { - constructor(fields) { - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; - } - includeEvent(event, rootType) { - let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; - const eventTags = event.tags ?? []; - if (this.includeNames !== void 0) { - include = include || this.includeNames.includes(event.name); - } - if (this.includeTypes !== void 0) { - include = include || this.includeTypes.includes(rootType); - } - if (this.includeTags !== void 0) { - include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); - } - if (this.excludeNames !== void 0) { - include = include && !this.excludeNames.includes(event.name); - } - if (this.excludeTypes !== void 0) { - include = include && !this.excludeTypes.includes(rootType); - } - if (this.excludeTags !== void 0) { - include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); - } - return include; - } - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/Options.js -var ignoreOverride, defaultOptions2, getDefaultOptions; -var init_Options = __esm({ - "node_modules/zod-to-json-schema/dist/esm/Options.js"() { - ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); - defaultOptions2 = { - name: void 0, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref" - }; - getDefaultOptions = (options) => typeof options === "string" ? { - ...defaultOptions2, - name: options - } : { - ...defaultOptions2, - ...options - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/Refs.js -var getRefs; -var init_Refs = __esm({ - "node_modules/zod-to-json-schema/dist/esm/Refs.js"() { - init_Options(); - getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; - return { - ..._options, - currentPath, - propertyPath: void 0, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: void 0 - } - ])) - }; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/errorMessages.js -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; - } -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} -var init_errorMessages = __esm({ - "node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef() { - return {}; -} -var init_any = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/array.js -function parseArrayDef(def, refs) { - const res = { - type: "array" - }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - } - if (def.minLength) { - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} -var init_array = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() { - init_lib(); - init_errorMessages(); - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} -var init_bigint = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() { - init_errorMessages(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js -function parseBooleanDef() { - return { - type: "boolean" - }; -} -var init_boolean = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} -var init_branded = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() { - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js -var parseCatchDef; -var init_catch = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() { - init_parseDef(); - parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/date.js -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i3) => parseDateDef(def, refs, item)) - }; - } - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time" - }; - case "format:date": - return { - type: "string", - format: "date" - }; - case "integer": - return integerDateParser(def, refs); - } -} -var integerDateParser; -var init_date = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() { - init_errorMessages(); - integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" - }; - if (refs.target === "openApi3") { - return res; - } - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors( - res, - "minimum", - check.value, - // This is in milliseconds - check.message, - refs - ); - break; - case "max": - setResponseValueAndErrors( - res, - "maximum", - check.value, - // This is in milliseconds - check.message, - refs - ); - break; - } - } - return res; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/default.js -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() - }; -} -var init_default = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() { - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {}; -} -var init_effects = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() { - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) - }; -} -var init_enum = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js -function parseIntersectionDef(def, refs) { - const allOf = [ - parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }), - parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "1"] - }) - ].filter((x2) => !!x2); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === void 0) { - unevaluatedProperties = void 0; - } - } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } else { - unevaluatedProperties = void 0; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : void 0; -} -var isJsonSchema7AllOfType; -var init_intersection = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() { - init_parseDef(); - isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object" - }; - } - if (refs.target === "openApi3") { - return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value] - }; - } - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value - }; -} -var init_literal = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/string.js -function parseStringDef(def, refs) { - const res = { - type: "string" - }; - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "includes": { - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; - } - case "ip": { - if (check.version !== "v6") { - addFormat(res, "ipv4", check.message, refs); - } - if (check.version !== "v4") { - addFormat(res, "ipv6", check.message, refs); - } - break; - } - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": { - if (check.version !== "v6") { - addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - } - if (check.version !== "v4") { - addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - } - break; - } - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": { - addPattern(res, zodPatterns.ulid, check.message, refs); - break; - } - case "base64": { - switch (refs.base64Strategy) { - case "format:binary": { - addFormat(res, "binary", check.message, refs); - break; - } - case "contentEncoding:base64": { - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - } - case "pattern:zod": { - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - } - break; - } - case "nanoid": { - addPattern(res, zodPatterns.nanoid, check.message, refs); - } - case "toLowerCase": - case "toUpperCase": - case "trim": - break; - default: - ((_2) => { - })(check); - } - } - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; -} -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i3 = 0; i3 < source.length; i3++) { - if (!ALPHA_NUMERIC.has(source[i3])) { - result += "\\"; - } - result += source[i3]; - } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x2) => x2.format)) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...schema.errorMessage && refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format } - } - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else { - setResponseValueAndErrors(schema, "format", value, message, refs); - } -} -function addPattern(schema, regex2, message, refs) { - if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...schema.errorMessage && refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern } - } - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex2, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else { - setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex2, refs), message, refs); - } -} -function stringifyRegExpWithFlags(regex2, refs) { - if (!refs.applyRegexFlags || !regex2.flags) { - return regex2.source; - } - const flags = { - i: regex2.flags.includes("i"), - m: regex2.flags.includes("m"), - s: regex2.flags.includes("s") - // `.` matches newlines - }; - const source = flags.i ? regex2.source.toLowerCase() : regex2.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i3 = 0; i3 < source.length; i3++) { - if (isEscaped) { - pattern += source[i3]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i3].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i3]; - pattern += `${source[i3 - 2]}-${source[i3]}`.toUpperCase(); - inCharRange = false; - } else if (source[i3 + 1] === "-" && source[i3 + 2]?.match(/[a-z]/)) { - pattern += source[i3]; - inCharRange = true; - } else { - pattern += `${source[i3]}${source[i3].toUpperCase()}`; - } - continue; - } - } else if (source[i3].match(/[a-z]/)) { - pattern += `[${source[i3]}${source[i3].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i3] === "^") { - pattern += `(^|(?<=[\r -]))`; - continue; - } else if (source[i3] === "$") { - pattern += `($|(?=[\r -]))`; - continue; - } - } - if (flags.s && source[i3] === ".") { - pattern += inCharGroup ? `${source[i3]}\r -` : `[${source[i3]}\r -]`; - continue; - } - pattern += source[i3]; - if (source[i3] === "\\") { - isEscaped = true; - } else if (inCharGroup && source[i3] === "]") { - inCharGroup = false; - } else if (!inCharGroup && source[i3] === "[") { - inCharGroup = true; - } - } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex2.source; - } - return pattern; -} -var emojiRegex2, zodPatterns, ALPHA_NUMERIC; -var init_string = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() { - init_errorMessages(); - emojiRegex2 = void 0; - zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (emojiRegex2 === void 0) { - emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - } - return emojiRegex2; - }, - /** - * Unused - */ - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - /** - * Unused - */ - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ - }; - ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/record.js -function parseRecordDef(def, refs) { - if (refs.target === "openAi") { - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - } - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", key] - }) ?? {} - }), {}), - additionalProperties: false - }; - } - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? {} - }; - if (refs.target === "openApi3") { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const { type, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values - } - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { - const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } - return schema; -} -var init_record = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() { - init_lib(); - init_parseDef(); - init_string(); - init_branded(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/map.js -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") { - return parseRecordDef(def, refs); - } - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "0"] - }) || {}; - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "1"] - }) || {}; - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2 - } - }; -} -var init_map = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() { - init_parseDef(); - init_record(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues - }; -} -var init_nativeEnum = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef() { - return { - not: {} - }; -} -var init_never = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/null.js -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { - type: "null" - }; -} -var init_null = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/union.js -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) { - const types = options.reduce((types2, x2) => { - const type = primitiveMappings[x2._def.typeName]; - return type && !types2.includes(type) ? [...types2, type] : types2; - }, []); - return { - type: types.length > 1 ? types : types[0] - }; - } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) { - const types = options.reduce((acc, x2) => { - const type = typeof x2._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x2._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; - } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x2, i3, a3) => a3.indexOf(x2) === i3); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x2) => { - return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value]; - }, []) - }; - } - } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x2) => [ - ...acc, - ...x2._def.values.filter((x3) => !acc.includes(x3)) - ], []) - }; - } - return asAnyOf(def, refs); -} -var primitiveMappings, asAnyOf; -var init_union = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() { - init_parseDef(); - primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" - }; - asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i3) => parseDef(x2._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", `${i3}`] - })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)); - return anyOf.length ? { anyOf } : void 0; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - } - return { - type: [ - primitiveMappings[def.innerType._def.typeName], - "null" - ] - }; - } - if (refs.target === "openApi3") { - const base2 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base2 && "$ref" in base2) - return { allOf: [base2], nullable: true }; - return base2 && { ...base2, nullable: true }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "0"] - }); - return base && { anyOf: [base, { type: "null" }] }; -} -var init_nullable = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() { - init_parseDef(); - init_union(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/number.js -function parseNumberDef(def, refs) { - const res = { - type: "number" - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} -var init_number = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() { - init_errorMessages(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/object.js -function decideAdditionalProperties(def, refs) { - if (refs.removeAdditionalStrategy === "strict") { - return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? true; - } else { - return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? true; - } -} -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { - if (propDef === void 0 || propDef._def === void 0) - return acc; - let propOptional = propDef.isOptional(); - if (propOptional && forceOptionalIntoNullable) { - if (propDef instanceof ZodOptional) { - propDef = propDef._def.innerType; - } - if (!propDef.isNullable()) { - propDef = propDef.nullable(); - } - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", propName], - propertyPath: [...refs.currentPath, "properties", propName] - }); - if (parsedDef === void 0) - return acc; - return { - properties: { ...acc.properties, [propName]: parsedDef }, - required: propOptional ? acc.required : [...acc.required, propName] - }; - }, { properties: {}, required: [] }), - additionalProperties: decideAdditionalProperties(def, refs) - }; - if (!result.required.length) - delete result.required; - return result; -} -var init_object = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() { - init_lib(); - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js -var parseOptionalDef; -var init_optional = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() { - init_parseDef(); - parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) { - return parseDef(def.innerType._def, refs); - } - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "1"] - }); - return innerSchema ? { - anyOf: [ - { - not: {} - }, - innerSchema - ] - } : {}; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js -var parsePipelineDef; -var init_pipeline = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() { - init_parseDef(); - parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return parseDef(def.in._def, refs); - } else if (refs.pipeStrategy === "output") { - return parseDef(def.out._def, refs); - } - const a3 = parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }); - const b3 = parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"] - }); - return { - allOf: [a3, b3].filter((x2) => x2 !== void 0) - }; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} -var init_promise = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() { - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/set.js -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - const schema = { - type: "array", - uniqueItems: true, - items - }; - if (def.minSize) { - setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} -var init_set = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() { - init_errorMessages(); - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items.map((x2, i3) => parseDef(x2._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i3}`] - })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - } else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x2, i3) => parseDef(x2._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i3}`] - })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []) - }; - } -} -var init_tuple = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() { - init_parseDef(); - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef() { - return { - not: {} - }; -} -var init_undefined = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef() { - return {}; -} -var init_unknown = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() { - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js -var parseReadonlyDef; -var init_readonly = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() { - init_parseDef(); - parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/parseDef.js -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== void 0) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; - refs.seen.set(def, newItem); - const jsonSchema = selectParser(def, def.typeName, refs); - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -var get$ref, getRelativePath, selectParser, addMeta; -var init_parseDef = __esm({ - "node_modules/zod-to-json-schema/dist/esm/parseDef.js"() { - init_lib(); - init_any(); - init_array(); - init_bigint(); - init_boolean(); - init_branded(); - init_catch(); - init_date(); - init_default(); - init_effects(); - init_enum(); - init_intersection(); - init_literal(); - init_map(); - init_nativeEnum(); - init_never(); - init_null(); - init_nullable(); - init_number(); - init_object(); - init_optional(); - init_pipeline(); - init_promise(); - init_record(); - init_set(); - init_string(); - init_tuple(); - init_undefined(); - init_union(); - init_unknown(); - init_readonly(); - init_Options(); - get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; - } - return refs.$refStrategy === "seen" ? {} : void 0; - } - } - }; - getRelativePath = (pathA, pathB) => { - let i3 = 0; - for (; i3 < pathA.length && i3 < pathB.length; i3++) { - if (pathA[i3] !== pathB[i3]) - break; - } - return [(pathA.length - i3).toString(), ...pathB.slice(i3)].join("/"); - }; - selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(); - case ZodFirstPartyTypeKind.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return parseDef(def.getter()._def, refs); - case ZodFirstPartyTypeKind.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(); - case ZodFirstPartyTypeKind.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(); - case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(); - case ZodFirstPartyTypeKind.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return void 0; - default: - return ((_2) => void 0)(typeName); - } - }; - addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js -var zodToJsonSchema; -var init_zodToJsonSchema = __esm({ - "node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() { - init_parseDef(); - init_Refs(); - zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ - ...acc, - [name2]: parseDef(schema2._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name2] - }, true) ?? {} - }), {}) : void 0; - const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; - const main = parseDef(schema._def, name === void 0 ? refs : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name] - }, false) ?? {}; - const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; - if (title !== void 0) { - main.title = title; - } - const combined = name === void 0 ? definitions ? { - ...main, - [refs.definitionPath]: definitions - } : main : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main - } - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - } - return combined; - }; - } -}); - -// node_modules/zod-to-json-schema/dist/esm/index.js -var init_esm = __esm({ - "node_modules/zod-to-json-schema/dist/esm/index.js"() { - init_Options(); - init_Refs(); - init_errorMessages(); - init_parseDef(); - init_any(); - init_array(); - init_bigint(); - init_boolean(); - init_branded(); - init_catch(); - init_date(); - init_default(); - init_effects(); - init_enum(); - init_intersection(); - init_literal(); - init_map(); - init_nativeEnum(); - init_never(); - init_null(); - init_nullable(); - init_number(); - init_object(); - init_optional(); - init_pipeline(); - init_promise(); - init_readonly(); - init_record(); - init_set(); - init_string(); - init_tuple(); - init_undefined(); - init_union(); - init_unknown(); - init_zodToJsonSchema(); - init_zodToJsonSchema(); - } -}); - -// node_modules/@langchain/core/dist/runnables/graph_mermaid.js -function _escapeNodeLabel(nodeLabel) { - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); -} -function _generateMermaidGraphStyles(nodeColors) { - let styles2 = ""; - for (const [className, color2] of Object.entries(nodeColors)) { - styles2 += ` classDef ${className} ${color2}; -`; - } - return styles2; -} -function drawMermaid(nodes, edges, config) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {}; - let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%% + https://smith.langchain.com/prompts`);let[o,i,a]=gS(t);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let s={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=await this.caller.call(wt(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(u,"create prompt");let{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[o,i,a]=gS(t),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=await this.caller.call(wt(),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=ef(a.outputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${s}.attachment.${d}`,m)}if(a.attachments_operations){let d=ef(a.attachments_operations),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=(a.id??dO()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});n.append(s,c);let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});if(n.append(`${s}.inputs`,f),a.outputs){let p=ef(a.outputs),h=new Blob([p],{type:"application/json"});n.append(`${s}.outputs`,h)}if(a.attachments)for(let[p,h]of Object.entries(a.attachments)){let m,_;Array.isArray(h)?[m,_]=h:(m=h.mimeType,_=h.data);let g=new Blob([_],{type:`${m}; length=${_.byteLength}`});n.append(`${s}.attachment.${p}`,g)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"POST",headers:this.headers,body:n})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=gS(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=await this.caller.call(wt(),`${this.apiUrl}/repos/${n}/${o}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"update prompt"),a.json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[r,n,o]=gS(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return await(await this.caller.call(wt(),`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async pullPromptCommit(t,r){let[n,o,i]=gS(t),a=await this.caller.call(wt(),`${this.apiUrl}/commits/${n}/${o}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(a,"pull prompt commit");let s=await a.json();return{owner:n,repo:o,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async _pullPrompt(t,r){let n=await this.pullPromptCommit(t,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(t,r){return await this.promptExists(t)?r&&Object.keys(r).some(o=>o!=="object")&&await this.updatePrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(t,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(t,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:o}=r,[i,a]=this.parseTokenOrUrl(t,n),s=new e({apiUrl:i,apiKey:"placeholder"}),u=await s.readSharedDataset(a),l=o||u.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let c=await s.listSharedExamples(a),d=await this.createDataset(l,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:c.map(f=>f.inputs),outputs:c.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(t,r,n=2,o="dataset"){try{return en(t),[r,t]}catch{}try{let a=new URL(t).pathname.split("/").filter(s=>s!=="");if(a.length>=n){let s=a[a.length-n];return[r,s]}else throw new Error(`Invalid public ${o} URL: ${t}`)}catch{throw new Error(`Invalid public ${o} URL or token: ${t}`)}}awaitPendingTraceBatches(){return this.manualFlushMode?(console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve()):Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()])}}});var K6,Y6=C(()=>{use();Q6();N6();K6="0.2.14"});function Z6(){if(lse===void 0){let e=t9t(),t=n9t();lse={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:K6,...t}}return lse}function INe(){let e=r9t()||{},t={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,o]of Object.entries(e))(n.startsWith("LANGCHAIN_")||n.startsWith("LANGSMITH_"))&&typeof o=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?t.revision_id=o:t[n]=o);return t}function r9t(){try{return typeof process<"u"&&process.env?Object.entries(process.env).reduce((e,[t,r])=>(e[t]=String(r),e),{}):void 0}catch{return}}function ey(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function yS(e){return ey(`LANGSMITH_${e}`)||ey(`LANGCHAIN_${e}`)}function n9t(){if(cse!==void 0)return cse;let e=["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"],t={};for(let r of e){let n=ey(r);n!==void 0&&(t[r]=n)}return cse=t,t}var _S,Z5t,X5t,Q5t,ANe,e9t,t9t,lse,cse,X6=C(()=>{Y6();Z5t=()=>typeof window<"u"&&typeof window.document<"u",X5t=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Q5t=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),ANe=()=>typeof Deno<"u",e9t=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!ANe(),t9t=()=>_S||(Z5t()?_S="browser":e9t()?_S="node":X5t()?_S="webworker":Q5t()?_S="jsdom":ANe()?_S="deno":_S="other",_S)});var RNe,DNe=C(()=>{X6();RNe=e=>e!==void 0?e:!!["TRACING_V2","TRACING"].find(r=>yS(r)==="true")});var eV,jNe=C(()=>{eV=Symbol.for("lc:context_variables")});function o9t(e){return e.replace(/[-:.]/g,"")}function i9t(e,t,r=1){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return o9t(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}function rV(e){return e!==void 0&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function LNe(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function NNe(e){return Array.isArray(e)&&e.some(t=>LNe(t))}function a9t(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function s9t(e){return e!==void 0&&typeof e.callbacks=="object"&&(NNe(e.callbacks?.handlers)||NNe(e.callbacks))}var tV,bS,Q6=C(()=>{M6();X6();use();DNe();kae();jNe();tV=class e{constructor(t,r){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=t,this.tags=r}static fromHeader(t){let r=t.split(","),n={},o=[];for(let i of r){let[a,s]=i.split("="),u=decodeURIComponent(s);a==="langsmith-metadata"?n=JSON.parse(u):a==="langsmith-tags"&&(o=u.split(","))}return new e(n,o)}toHeader(){let t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),t.join(",")}},bS=class e{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),rV(t)){Object.assign(this,{...t});return}let r=e.getDefaultConfig(),{metadata:n,...o}=t,i=o.client??e.getSharedClient(),a={...n,...o?.extra?.metadata};if(o.extra={...o.extra,metadata:a},Object.assign(this,{...r,...o,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),!this.dotted_order){let s=i9t(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+s:this.dotted_order=s}}static getDefaultConfig(){return{id:dO(),run_type:"chain",project_name:ey("LANGCHAIN_PROJECT")??ey("LANGCHAIN_SESSION")??"default",child_runs:[],api_url:ey("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ey("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||(e.sharedClient=new RM),e.sharedClient}createChild(t){let r=this.child_execution_order+1,n=new e({...t,parent_run:this,project_name:this.project_name,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});eV in this&&(n[eV]=this[eV]);let o=Symbol.for("lc:child_config"),i=t.extra?.[o]??this.extra[o];if(s9t(i)){let u={...i},l=a9t(u.callbacks)?u.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:n.id}),l.handlers?.find(LNe)?.updateFromRunTree?.(n),u.callbacks=l),n.extra[o]=u}let a=new Set,s=this;for(;s!=null&&!a.has(s.id);)a.add(s.id),s.child_execution_order=Math.max(s.child_execution_order,r),s=s.parent_run;return this.child_runs.push(n),n}async end(t,r,n=Date.now(),o){this.outputs=this.outputs??t,this.error=this.error??r,this.end_time=this.end_time??n,o&&Object.keys(o).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...o}}:{metadata:o})}_convertToCreate(t,r,n=!0){let o=t.extra??{};if(o.runtime||(o.runtime={}),r)for(let[u,l]of Object.entries(r))o.runtime[u]||(o.runtime[u]=l);let i,a;return n?(a=t.parent_run?.id,i=[]):(i=t.child_runs.map(u=>this._convertToCreate(u,r,n)),a=void 0),{id:t.id,name:t.name,start_time:t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:o,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:i,parent_run_id:a,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments}}async postRun(t=!0){try{let r=Z6(),n=await this._convertToCreate(this,r,!0);if(await this.client.createRun(n),!t){F6("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let o of this.child_runs)await o.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(){try{let t={end_time:this.end_time,error:this.error,inputs:this.inputs,outputs:this.outputs,parent_run_id:this.parent_run?.id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments};await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}static fromRunnableConfig(t,r){let n=t?.callbacks,o,i,a,s=RNe();if(n){let l=n?.getParentRunId?.()??"",c=n?.handlers?.find(d=>d?.name=="langchain_tracer");o=c?.getRun?.(l),i=c?.projectName,a=c?.client,s=s||!!c}return o?new e({name:o.name,id:o.id,trace_id:o.trace_id,dotted_order:o.dotted_order,client:a,tracingEnabled:s,project_name:i,tags:[...new Set((o?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...o?.extra?.metadata,...t?.metadata}}}).createChild(r):new e({...r,client:a,tracingEnabled:s,project_name:i})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,r){let n="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,o=n["langsmith-trace"];if(!o||typeof o!="string")return;let i=o.trim(),a=i.split(".").map(l=>{let[c,d]=l.split("Z");return{strTime:c,time:Date.parse(c+"Z"),uuid:d}}),s=a[0].uuid,u={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:s,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let l=tV.fromHeader(n.baggage);u.metadata=l.metadata,u.tags=l.tags}return new e(u)}toHeaders(t){let r={"langsmith-trace":this.dotted_order,baggage:new tV(this.extra?.metadata,this.tags).toHeader()};if(t)for(let[n,o]of Object.entries(r))t.set(n,o);return r}};Object.defineProperty(bS,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})});function nV(e){return typeof e=="function"&&"langsmith:traceable"in e}var fse,dse,u9t,pse,l9t,FNe,Qyn,kNe=C(()=>{Q6();fse=class{getStore(){}run(t,r){return r()}},dse=Symbol.for("ls:tracing_async_local_storage"),u9t=new fse,pse=class{getInstance(){return globalThis[dse]??u9t}initializeGlobalInstance(t){globalThis[dse]===void 0&&(globalThis[dse]=t)}},l9t=new pse,FNe=()=>{let e=l9t.getInstance().getStore();if(!rV(e))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(` +`));return e},Qyn=Symbol.for("langsmith:traceable:root")});var hse=C(()=>{kNe()});function iV(e,t){return c9t.call(e,t)}function aV(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n=48&&n<=57){t++;continue}return!1}return!0}function ty(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function N$(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function oV(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r{c9t=Object.prototype.hasOwnProperty;DM=class extends Error{constructor(t,r,n,o,i){super(BNe(t,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=BNe(t,{name:r,index:n,operation:o,tree:i})}}});var mse={};Kd(mse,{JsonPatchError:()=>Pa,_areEquals:()=>F$,applyOperation:()=>jM,applyPatch:()=>fO,applyReducer:()=>p9t,deepClone:()=>d9t,getValueByPointer:()=>uV,validate:()=>$Ne,validator:()=>lV});function uV(e,t){if(t=="")return e;var r={op:"_get",path:t};return jM(e,r),r.value}function jM(e,t,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):lV(t,0)),t.path===""){let a={newDocument:e};if(t.op==="add")return a.newDocument=t.value,a;if(t.op==="replace")return a.newDocument=t.value,a.removed=e,a;if(t.op==="move"||t.op==="copy")return a.newDocument=uV(e,t.from),t.op==="move"&&(a.removed=e),a;if(t.op==="test"){if(a.test=F$(e,t.value),a.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a.newDocument=e,a}else{if(t.op==="remove")return a.removed=e,a.newDocument=null,a;if(t.op==="_get")return t.value=e,a;if(r)throw new Pa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return a}}else{n||(e=Dc(e));let s=(t.path||"").split("/"),u=e,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lV;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=N$(f)),o&&(f=="__proto__"||f=="prototype"&&l>0&&s[l-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(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!sV(f))throw new Pa("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",i,t,e);sV(f)&&(f=~~f)}if(l>=c){if(r&&t.op==="add"&&f>u.length)throw new Pa("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);let h=f9t[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}}else if(l>=c){let h=TD[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}if(u=u[f],r&&l0)throw new Pa('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new Pa("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new Pa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&oV(e.value))throw new Pa("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r){if(e.op=="add"){var o=e.path.split("/").length,i=n.split("/").length;if(o!==i+1&&o!==i)throw new Pa("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==n)throw new Pa("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if(e.op==="move"||e.op==="copy"){var a={op:"_get",path:e.from,value:void 0},s=$Ne([a],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new Pa("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}}else throw new Pa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r)}function $Ne(e,t,r){try{if(!Array.isArray(e))throw new Pa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)fO(Dc(t),Dc(e),r||!0);else{r=r||lV;for(var n=0;n{L$();Pa=DM,d9t=Dc,TD={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=uV(r,this.path);n&&(n=Dc(n));let o=jM(r,{op:"remove",path:this.from}).removed;return jM(r,{op:"add",path:this.path,value:o}),{newDocument:r,removed:n}},copy:function(e,t,r){let n=uV(r,this.from);return jM(r,{op:"add",path:this.path,value:Dc(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:F$(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}},f9t={add:function(e,t,r){return sV(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){var n=e.splice(t,1);return{newDocument:r,removed:n[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:TD.move,copy:TD.copy,test:TD.test,_get:TD._get}});function qNe(e,t,r,n,o){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var i=aV(t),a=aV(e),s=!1,u=!1,l=a.length-1;l>=0;l--){var c=a[l],d=e[c];if(iV(t,c)&&!(t[c]===void 0&&d!==void 0&&Array.isArray(t)===!1)){var f=t[c];typeof d=="object"&&d!=null&&typeof f=="object"&&f!=null&&Array.isArray(d)===Array.isArray(f)?qNe(d,f,r,n+"/"+ty(c),o):d!==f&&(s=!0,o&&r.push({op:"test",path:n+"/"+ty(c),value:Dc(d)}),r.push({op:"replace",path:n+"/"+ty(c),value:Dc(f)}))}else Array.isArray(e)===Array.isArray(t)?(o&&r.push({op:"test",path:n+"/"+ty(c),value:Dc(d)}),r.push({op:"remove",path:n+"/"+ty(c)}),u=!0):(o&&r.push({op:"test",path:n,value:e}),r.push({op:"replace",path:n,value:t}),s=!0)}if(!(!u&&i.length==a.length))for(var l=0;l{L$();cV();});var lbn,gse=C(()=>{cV();UNe();L$();cV();L$();lbn={...mse,JsonPatchError:DM,deepClone:Dc,escapePathComponent:ty,unescapePathComponent:N$}});var HNe=b((hbn,zNe)=>{"use strict";zNe.exports=function(e,t){if(typeof e!="string")throw new TypeError("Expected a string");return t=typeof t>"u"?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}});var ZNe=b((mbn,yse)=>{"use strict";var h9t=/[\p{Lu}]/u,m9t=/[\p{Ll}]/u,VNe=/^[\p{Lu}](?![\p{Lu}])/gu,GNe=/([\p{Alpha}\p{N}_]|$)/u,KNe=/[_.\- ]+/,g9t=new RegExp("^"+KNe.source),WNe=new RegExp(KNe.source+GNe.source,"gu"),JNe=new RegExp("\\d+"+GNe.source,"gu"),y9t=(e,t,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a(VNe.lastIndex=0,e.replace(VNe,r=>t(r))),_9t=(e,t)=>(WNe.lastIndex=0,JNe.lastIndex=0,e.replace(WNe,(r,n)=>t(n)).replace(JNe,r=>t(r))),YNe=(e,t)=>{if(!(typeof e=="string"||Array.isArray(e)))throw new TypeError("Expected the input to be `string | string[]`");if(t={pascalCase:!1,preserveConsecutiveUppercase:!1,...t},Array.isArray(e)?e=e.map(i=>i.trim()).filter(i=>i.length).join("-"):e=e.trim(),e.length===0)return"";let r=t.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(t.locale),n=t.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(t.locale);return e.length===1?t.pascalCase?n(e):r(e):(e!==r(e)&&(e=y9t(e,r,n)),e=e.replace(g9t,""),t.preserveConsecutiveUppercase?e=b9t(e,r):e=r(e),t.pascalCase&&(e=n(e.charAt(0))+e.slice(1)),_9t(e,n))};yse.exports=YNe;yse.exports.default=YNe});function QNe(e,t){return t?.[e]||(0,XNe.default)(e)}function eLe(e,t,r){let n={};for(let o in e)Object.hasOwn(e,o)&&(n[t(o,r)]=e[o]);return n}var XNe,v9t,tLe=C(()=>{XNe=B(HNe(),1),v9t=B(ZNe(),1)});function rLe(e){return Array.isArray(e)?[...e]:{...e}}function w9t(e,t){let r=rLe(e);for(let[n,o]of Object.entries(t)){let[i,...a]=n.split(".").reverse(),s=r;for(let u of a.reverse()){if(s[u]===void 0)break;s[u]=rLe(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function bse(e){let t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var tf,NM=C(()=>{tLe();tf=class e{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,bse(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...r){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof e||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let t={},r={},n=Object.keys(this.lc_kwargs).reduce((o,i)=>(o[i]=i in this?this[i]:this.lc_kwargs[i],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(t,Reflect.get(o,"lc_aliases",this)),Object.assign(r,Reflect.get(o,"lc_secrets",this)),Object.assign(n,Reflect.get(o,"lc_attributes",this));return Object.keys(r).forEach(o=>{let i=this,a=n,[s,...u]=o.split(".").reverse();for(let l of u.reverse()){if(!(l in i)||i[l]===void 0)return;(!(l in a)||a[l]===void 0)&&(typeof i[l]=="object"&&i[l]!=null?a[l]={}:Array.isArray(i[l])&&(a[l]=[])),i=i[l],a=a[l]}s in i&&i[s]!==void 0&&(a[s]=a[s]||i[s])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:eLe(Object.keys(r).length?w9t(n,r):n,QNe,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});async function nLe(){return _se===void 0&&(_se={library:"langchain-js",runtime:E9t()}),_se}function Jt(e){try{return typeof process<"u"?process.env?.[e]:vse()?Deno?.env.get(e):void 0}catch{return}}var S9t,x9t,C9t,vse,O9t,E9t,_se,LM=C(()=>{S9t=()=>typeof window<"u"&&typeof window.document<"u",x9t=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",C9t=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),vse=()=>typeof Deno<"u",O9t=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!vse(),E9t=()=>{let e;return S9t()?e="browser":O9t()?e="node":x9t()?e="webworker":C9t()?e="jsdom":vse()?e="deno":e="other",e}});function Sse(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var wse,FM,oLe,k$=C(()=>{O$();NM();LM();wse=class{};FM=class e extends wse{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,bse(this.constructor)]}constructor(t){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:Jt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return tf.prototype.toJSON.call(this)}toJSONNotImplemented(){return tf.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class r extends e{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Xd()}),Object.assign(this,t)}}return new r}},oLe=e=>{let t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"}});function xse(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function P9t(e){return e.replace(/[-:.]/g,"")}function T9t(e,t,r){let n=r.toFixed(0).slice(0,3).padStart(3,"0");return P9t(`${new Date(e).toISOString().slice(0,-1)}${n}Z`)+t}function MD(e){return typeof e._addRunToRunMap=="function"}var Xp,kM=C(()=>{k$();Xp=class extends FM{constructor(t){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}copy(){return this}stringifyError(t){return t instanceof Error?t.message+(t?.stack?` + +${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,r){t.child_runs.push(r)}_addRunToRunMap(t){let r=T9t(t.start_time,t.id,t.execution_order),n={...t};if(n.parent_run_id!==void 0){let o=this.runMap.get(n.parent_run_id);o&&(this._addChildRun(o,n),o.child_execution_order=Math.max(o.child_execution_order,n.child_execution_order),n.trace_id=o.trace_id,o.dotted_order!==void 0&&(n.dotted_order=[o.dotted_order,r].join(".")))}else n.trace_id=n.id,n.dotted_order=r;return this.runMap.set(n.id,n),n}async _endTrace(t){let r=t.parent_run_id!==void 0&&this.runMap.get(t.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,t.child_execution_order):await this.persistRun(t),this.runMap.delete(t.id),await this.onRunUpdate?.(t)}_getExecutionOrder(t){let r=t!==void 0&&this.runMap.get(t);return r?r.child_execution_order+1:1}_createRunForLLMStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForLLMStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChatModelStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:r,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChainStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=xse(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??t.id[t.id.length-1],parent_run_id:o,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleToolStart(t,r,n,o,i,a,s){let u=this.runMap.get(n)??this._createRunForToolStart(t,r,n,o,i,a,s);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(t,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:t},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(t,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(t),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(t,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="chain")return;let o=n;o.actions=o.actions||[],o.actions.push(t),o.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(n)}async handleAgentEnd(t,r){let n=this.runMap.get(r);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(t,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??t.id[t.id.length-1],parent_run_id:o,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:r},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleRetrieverStart(t,r,n,o,i,a,s){let u=this.runMap.get(n)??this._createRunForRetrieverStart(t,r,n,o,i,a,s);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(t,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:t},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(t,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(t),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(t,r){let n=this.runMap.get(r);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(n))}async handleLLMNewToken(t,r,n,o,i,a){let s=this.runMap.get(n);if(!s||s?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:r,chunk:a?.chunk}}),await this.onLLMNewToken?.(s,t,{chunk:a?.chunk}),s}}});var uLe=b((Obn,sLe)=>{"use strict";var iLe=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,aLe=(e=0)=>(t,r,n)=>`\x1B[${38+e};2;${t};${r};${n}m`;function M9t(){let e=new Map,t={modifier:{reset:[0,0],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],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],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[r,n]of Object.entries(t)){for(let[o,i]of Object.entries(n))t[o]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[o]=t[o],e.set(i[0],i[1]);Object.defineProperty(t,r,{value:n,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="\x1B[39m",t.bgColor.close="\x1B[49m",t.color.ansi256=iLe(),t.color.ansi16m=aLe(),t.bgColor.ansi256=iLe(10),t.bgColor.ansi16m=aLe(10),Object.defineProperties(t,{rgbToAnsi256:{value:(r,n,o)=>r===n&&n===o?r<8?16:r>248?231:Math.round((r-8)/247*24)+232:16+36*Math.round(r/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5),enumerable:!1},hexToRgb:{value:r=>{let n=/(?[a-f\d]{6}|[a-f\d]{3})/i.exec(r.toString(16));if(!n)return[0,0,0];let{colorString:o}=n.groups;o.length===3&&(o=o.split("").map(a=>a+a).join(""));let i=Number.parseInt(o,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:r=>t.rgbToAnsi256(...t.hexToRgb(r)),enumerable:!1}}),t}Object.defineProperty(sLe,"exports",{enumerable:!0,get:M9t})});function Sd(e,t){return`${e.open}${t}${e.close}`}function Qp(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function lLe(e){return typeof e=="string"?e.trim():e==null?e:Qp(e,e.toString())}function pO(e){if(!e.end_time)return"";let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var Cse,rf,B$,cLe=C(()=>{Cse=B(uLe(),1);kM();({color:rf}=Cse.default),B$=class extends Xp{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(t){return Promise.resolve()}getParents(t){let r=[],n=t;for(;n.parent_run_id;){let o=this.runMap.get(n.parent_run_id);if(o)r.push(o),n=o;else break}return r}getBreadcrumbs(t){let n=[...this.getParents(t).reverse(),t].map((o,i,a)=>{let s=`${o.execution_order}:${o.run_type}:${o.name}`;return i===a.length-1?Sd(Cse.default.bold,s):s}).join(" > ");return Sd(rf.grey,n)}onChainStart(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.green,"[chain/start]")} [${r}] Entering Chain run with input: ${Qp(t.inputs,"[inputs]")}`)}onChainEnd(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.cyan,"[chain/end]")} [${r}] [${pO(t)}] Exiting Chain run with output: ${Qp(t.outputs,"[outputs]")}`)}onChainError(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.red,"[chain/error]")} [${r}] [${pO(t)}] Chain run errored with error: ${Qp(t.error,"[error]")}`)}onLLMStart(t){let r=this.getBreadcrumbs(t),n="prompts"in t.inputs?{prompts:t.inputs.prompts.map(o=>o.trim())}:t.inputs;console.log(`${Sd(rf.green,"[llm/start]")} [${r}] Entering LLM run with input: ${Qp(n,"[inputs]")}`)}onLLMEnd(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.cyan,"[llm/end]")} [${r}] [${pO(t)}] Exiting LLM run with output: ${Qp(t.outputs,"[response]")}`)}onLLMError(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.red,"[llm/error]")} [${r}] [${pO(t)}] LLM run errored with error: ${Qp(t.error,"[error]")}`)}onToolStart(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.green,"[tool/start]")} [${r}] Entering Tool run with input: "${lLe(t.inputs.input)}"`)}onToolEnd(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.cyan,"[tool/end]")} [${r}] [${pO(t)}] Exiting Tool run with output: "${lLe(t.outputs?.output)}"`)}onToolError(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.red,"[tool/error]")} [${r}] [${pO(t)}] Tool run errored with error: ${Qp(t.error,"[error]")}`)}onRetrieverStart(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.green,"[retriever/start]")} [${r}] Entering Retriever run with input: ${Qp(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.cyan,"[retriever/end]")} [${r}] [${pO(t)}] Exiting Retriever run with output: ${Qp(t.outputs,"[outputs]")}`)}onRetrieverError(t){let r=this.getBreadcrumbs(t);console.log(`${Sd(rf.red,"[retriever/error]")} [${r}] [${pO(t)}] Retriever run errored with error: ${Qp(t.error,"[error]")}`)}onAgentAction(t){let r=t,n=this.getBreadcrumbs(t);console.log(`${Sd(rf.blue,"[agent/action]")} [${n}] Agent selected action: ${Qp(r.actions[r.actions.length-1],"[action]")}`)}}});function hO(e,t){return e.lc_error_code=t,e.message=`${e.message} + +Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/ +`,e}var $$=C(()=>{});function AD(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}var ID,fV=C(()=>{ID=class extends Error{constructor(t,r){super(t),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=r}}});function Ose(e,t=RD){e=e.trim();let r=/```(json)?(.*)```/s.exec(e);return t(r?r[2]:e)}function RD(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="",r=[],n=!1,o=!1;for(let i of e){if(n)i==='"'&&!o?n=!1:i===` +`&&!o?i="\\n":i==="\\"?o=!o:o=!1;else if(i==='"')n=!0,o=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;t+=i}n&&(t+='"');for(let i=r.length-1;i>=0;i-=1)t+=r[i];try{return JSON.parse(t)}catch{return null}}var Ese=C(()=>{});function eh(e,t){return typeof e=="string"?typeof t=="string"?e+t:[{type:"text",text:e},...t]:Array.isArray(t)?q$(e,t)??[...e,...t]:[...e,{type:"text",text:t}]}function dLe(e,t){return e==="error"||t==="error"?"error":"success"}function I9t(e,t){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=t)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(e,0),null,2)}function qa(e,t){let r={...e};for(let[n,o]of Object.entries(t))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;r[n]+=o}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=qa(r[n],o);else if(Array.isArray(r[n]))r[n]=q$(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function q$(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{let r=[...e];for(let n of t)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=qa(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function fLe(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types. +Left ${typeof e} +Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return q$(e,t);if(typeof e=="object"&&typeof t=="object")return qa(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types. +Left ${e} +Right ${t}`)}function pLe(e){return typeof e.role=="string"}function th(e){return typeof e?._getType=="function"}function Pse(e){return th(e)&&typeof e.concat=="function"}var Lu,nf,rh=C(()=>{NM();Lu=class extends tf{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:""}getType(){return this._getType()}constructor(t,r){typeof t=="string"&&(t={content:t,additional_kwargs:r,response_metadata:{}}),t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.content=t.content,this.additional_kwargs=t.additional_kwargs,this.response_metadata=t.response_metadata,this.id=t.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let r=I9t(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${r}`}};nf=class extends Lu{}});function hLe(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}function mLe(e){let t=[],r=[];for(let n of e)if(n.function){let o=n.function.name;try{let i=JSON.parse(n.function.arguments),a={name:o||"",args:i||{},id:n.id};t.push(a)}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[t,r]}var vS,mO,DD=C(()=>{rh();vS=class extends Lu{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(t,r,n){typeof t=="string"&&(t={content:t,name:n,tool_call_id:r}),super(t),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}_getType(){return"tool"}static isInstance(t){return t._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},mO=class e extends nf{constructor(t){super(t),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),artifact:fLe(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:dLe(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function Fu(e){return e._getType()==="ai"}function Tse(e){return e._getType()==="ai"}var Po,Jr,BM=C(()=>{Ese();rh();DD();Po=class extends Lu{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t,r){let n;if(typeof t=="string")n={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:r??{}};else{n=t;let o=n.additional_kwargs?.tool_calls,i=n.tool_calls;o!=null&&o.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling. + +Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(o!=null&&i===void 0){let[a,s]=mLe(o);n.tool_calls=a??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.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}}};Jr=class e extends nf{constructor(t){let r;if(typeof t=="string")r={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0)r={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{let n=[],o=[];for(let i of t.tool_call_chunks){let a={};try{if(a=RD(i.args||"{}"),a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i.name??"",args:a,id:i.id,type:"tool_call"})}catch{o.push({name:i.name,args:i.args,id:i.id,error:"Malformed args.",type:"invalid_tool_call"})}}r={...t,tool_calls:n,invalid_tool_calls:o,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=r.tool_call_chunks??this.tool_call_chunks,this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=r.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(t){let r={content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){let n=q$(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(r.tool_call_chunks=n)}if(this.usage_metadata!==void 0||t.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||t.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(t.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||t.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(t.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||t.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(t.usage_metadata?.input_token_details?.cache_creation??0)}},o={...(this.usage_metadata?.output_token_details?.audio!==void 0||t.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(t.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||t.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(t.usage_metadata?.output_token_details?.reasoning??0)}},i=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=t.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},s={input_tokens:i.input_tokens+a.input_tokens,output_tokens:i.output_tokens+a.output_tokens,total_tokens:i.total_tokens+a.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(o).length>0&&{output_token_details:o}};r.usage_metadata=s}return new e(r)}}});var xd,Dm,pV=C(()=>{rh();xd=class e extends Lu{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return e}constructor(t,r){typeof t=="string"&&(t={content:t,role:r}),super(t),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=t.role}_getType(){return"generic"}static isInstance(t){return t._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Dm=class e extends nf{static lc_name(){return"ChatMessageChunk"}constructor(t,r){typeof t=="string"&&(t={content:t,role:r}),super(t),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=t.role}_getType(){return"generic"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}});var wS,hV=C(()=>{rh();wS=class e extends nf{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}}});var Ua,jm,U$=C(()=>{rh();Ua=class extends Lu{static lc_name(){return"HumanMessage"}_getType(){return"human"}},jm=class e extends nf{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),id:this.id??t.id})}}});var SS,ry,mV=C(()=>{rh();SS=class extends Lu{static lc_name(){return"SystemMessage"}_getType(){return"system"}},ry=class e extends nf{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),id:this.id??t.id})}}});function R9t(e){return AD(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function D9t(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function Mse(e){let t,r;if(D9t(e)){let n=e.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?t="user":n==="AIMessage"||n==="AIMessageChunk"?t="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?t="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?t="function":n==="ToolMessage"||n==="ToolMessageChunk"?t="tool":t="unknown",r=e.kwargs}else{let{type:n,...o}=e;t=n,r=o}if(t==="human"||t==="user")return new Ua(r);if(t==="ai"||t==="assistant"){let{tool_calls:n,...o}=r;if(!Array.isArray(n))return new Po(r);let i=n.map(R9t);return new Po({...o,tool_calls:i})}else{if(t==="system")return new SS(r);if(t==="developer")return new SS({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in r)return new vS({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});throw hO(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. + +Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Nm(e){if(typeof e=="string")return new Ua(e);if(th(e))return e;if(Array.isArray(e)){let[t,r]=e;return Mse({type:t,content:r})}else if(pLe(e)){let{role:t,...r}=e;return Mse({...r,type:t})}else return Mse(e)}function of(e,t="Human",r="AI"){let n=[];for(let o of e){let i;if(o._getType()==="human")i=t;else if(o._getType()==="ai")i=r;else if(o._getType()==="system")i="System";else if(o._getType()==="function")i="Function";else if(o._getType()==="tool")i="Tool";else if(o._getType()==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o._getType()}`);let a=o.name?`${o.name}, `:"",s=typeof o.content=="string"?o.content:JSON.stringify(o.content,null,2);n.push(`${i}: ${a}${s}`)}return n.join(` +`)}function Ise(e){let t=e._getType();if(t==="human")return new jm({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Jr({...r})}else{if(t==="system")return new ry({...e});if(t==="function")return new wS({...e});if(xd.isInstance(e))return new Dm({...e});throw new Error("Unknown message type.")}}var gO=C(()=>{$$();fV();BM();rh();pV();hV();U$();mV();DD()});var Ase=C(()=>{Q6()});var Rse=C(()=>{Y6()});var Dse,gLe,yLe=C(()=>{Rse();LM();gLe=()=>{if(Dse===void 0){let e=Jt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Dse=new RM(e)}return Dse}});var jD,bLe=C(()=>{Ase();hse();LM();kM();yLe();jD=class e extends Xp{constructor(t={}){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:r,projectName:n,client:o}=t;this.projectName=n??Jt("LANGCHAIN_PROJECT")??Jt("LANGCHAIN_SESSION"),this.exampleId=r,this.client=o??gLe();let i=e.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(t,r=void 0){return{...t,extra:{...t.extra,runtime:await nLe()},child_runs:void 0,session_name:this.projectName,reference_example_id:t.parent_run_id?void 0:r}}async persistRun(t){}async onRunCreate(t){let r=await this._convertToCreate(t,this.exampleId);await this.client.createRun(r)}async onRunUpdate(t){let r={end_time:t.end_time,error:t.error,outputs:t.outputs,events:t.events,inputs:t.inputs,trace_id:t.trace_id,dotted_order:t.dotted_order,parent_run_id:t.parent_run_id,extra:t.extra};await this.client.updateRun(t.id,r)}getRun(t){return this.runMap.get(t)}updateFromRunTree(t){let r=t,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let o=[r];for(;o.length>0;){let i=o.shift();!i||n.has(i.id)||(n.add(i.id),this.runMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=t.client??this.client,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}convertToRunTree(t){let r={},n=[];for(let[o,i]of this.runMap){let a=new bS({...i,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});r[o]=a,n.push([o,i.dotted_order])}n.sort((o,i)=>!o[1]||!i[1]?0:o[1].localeCompare(i[1]));for(let[o]of n){let i=this.runMap.get(o),a=r[o];if(!(!i||!a)&&i.parent_run_id){let s=r[i.parent_run_id];s&&(s.child_runs.push(a),a.parent_run=s)}}return r[t]}static getTraceableRunTree(){try{return FNe()}catch{return}}}});var _Le,$M,vLe,yO,z$=C(()=>{_Le=Symbol.for("ls:tracing_async_local_storage"),$M=Symbol.for("lc:context_variables"),vLe=e=>{globalThis[_Le]=e},yO=()=>globalThis[_Le]});function j9t(){let e="default"in gV.default?gV.default.default:gV.default;return new e({autoStart:!0,concurrency:1})}function N9t(){return typeof H$>"u"&&(H$=j9t()),H$}async function za(e,t){if(t===!0){let r=yO();r!==void 0?await r.run(void 0,async()=>e()):await e()}else H$=N9t(),H$.add(async()=>{let r=yO();r!==void 0?await r.run(void 0,async()=>e()):await e()})}var gV,H$,wLe=C(()=>{gV=B(j6(),1);z$()});var SLe=C(()=>{wLe()});var xLe,CLe=C(()=>{LM();xLe=e=>e!==void 0?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Jt(r)==="true")});function jse(e){let t=yO();return t===void 0?void 0:t.getStore()?.[$M]?.[e]}var L9t,OLe,ELe=C(()=>{Ase();z$();L9t=Symbol("lc:configure_hooks"),OLe=()=>jse(L9t)||[]});function qM(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}function V$(e){return"name"in e?e:FM.fromMethods(e)}var Nse,ND,Lse,yV,Fse,kse,ns,bO=C(()=>{O$();k$();cLe();gO();LM();bLe();SLe();CLe();kM();ELe();Nse=class{setHandler(t){return this.setHandlers([t])}},ND=class{constructor(t,r,n,o,i,a,s,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(r=>za(async()=>{try{await r.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleText: ${n}`),r.raiseError)throw n}},r.awaitHandlers)))}async handleCustomEvent(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{try{await a.handleCustomEvent?.(t,r,this.runId,this.tags,this.metadata)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}},Lse=class extends ND{getChild(t){let r=new ns(this.runId);return r.setHandlers(this.inheritableHandlers),r.addTags(this.inheritableTags),r.addMetadata(this.inheritableMetadata),t&&r.addTags([t],!1),r}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreRetriever)try{await r.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetriever`),r.raiseError)throw n}},r.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreRetriever)try{await r.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverError: ${n}`),r.raiseError)throw t}},r.awaitHandlers)))}},yV=class extends ND{async handleLLMNewToken(t,r,n,o,i,a){await Promise.all(this.handlers.map(s=>za(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(t,r??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(u){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${u}`),s.raiseError)throw u}},s.awaitHandlers)))}async handleLLMError(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{if(!a.ignoreLLM)try{await a.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMError: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleLLMEnd(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{if(!a.ignoreLLM)try{await a.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMEnd: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}},Fse=class extends ND{getChild(t){let r=new ns(this.runId);return r.setHandlers(this.inheritableHandlers),r.addTags(this.inheritableTags),r.addMetadata(this.inheritableMetadata),t&&r.addTags([t],!1),r}async handleChainError(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{if(!a.ignoreChain)try{await a.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainError: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleChainEnd(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{if(!a.ignoreChain)try{await a.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainEnd: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreAgent)try{await r.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleAgentAction: ${n}`),r.raiseError)throw n}},r.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreAgent)try{await r.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleAgentEnd: ${n}`),r.raiseError)throw n}},r.awaitHandlers)))}},kse=class extends ND{getChild(t){let r=new ns(this.runId);return r.setHandlers(this.inheritableHandlers),r.addTags(this.inheritableTags),r.addMetadata(this.inheritableMetadata),t&&r.addTags([t],!1),r}async handleToolError(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreAgent)try{await r.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolError: ${n}`),r.raiseError)throw n}},r.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(r=>za(async()=>{if(!r.ignoreAgent)try{await r.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolEnd: ${n}`),r.raiseError)throw n}},r.awaitHandlers)))}},ns=class e extends Nse{constructor(t,r){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,r,n=void 0,o=void 0,i=void 0,a=void 0,s=void 0,u=void 0){return Promise.all(r.map(async(l,c)=>{let d=c===0&&n?n:Xd();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return MD(f)&&f._createRunForLLMStart(t,[l],d,this._parentRunId,i,this.tags,this.metadata,u),za(async()=>{try{await f.handleLLMStart?.(t,[l],d,this._parentRunId,i,this.tags,this.metadata,u)}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new yV(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,r,n=void 0,o=void 0,i=void 0,a=void 0,s=void 0,u=void 0){return Promise.all(r.map(async(l,c)=>{let d=c===0&&n?n:Xd();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return MD(f)&&f._createRunForChatModelStart(t,[l],d,this._parentRunId,i,this.tags,this.metadata,u),za(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[l],d,this._parentRunId,i,this.tags,this.metadata,u);else if(f.handleLLMStart){let p=of(l);await f.handleLLMStart?.(t,[p],d,this._parentRunId,i,this.tags,this.metadata,u)}}catch(p){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${p}`),f.raiseError)throw p}},f.awaitHandlers)})),new yV(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,r,n=Xd(),o=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return MD(u)&&u._createRunForChainStart(t,r,n,this._parentRunId,this.tags,this.metadata,o,s),za(async()=>{try{await u.handleChainStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,o,s)}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new Fse(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,r,n=Xd(),o=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return MD(u)&&u._createRunForToolStart(t,r,n,this._parentRunId,this.tags,this.metadata,s),za(async()=>{try{await u.handleToolStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,s)}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new kse(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,r,n=Xd(),o=void 0,i=void 0,a=void 0,s=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return MD(u)&&u._createRunForRetrieverStart(t,r,n,this._parentRunId,this.tags,this.metadata,s),za(async()=>{try{await u.handleRetrieverStart?.(t,r,n,this._parentRunId,this.tags,this.metadata,s)}catch(l){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${l}`),u.raiseError)throw l}},u.awaitHandlers)})),new Lse(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,r,n,o,i){await Promise.all(this.handlers.map(a=>za(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(t,r,n,this.tags,this.metadata)}catch(s){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${s}`),a.raiseError)throw s}},a.awaitHandlers)))}addHandler(t,r=!0){this.handlers.push(t),r&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(r=>r!==t),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==t)}setHandlers(t,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of t)this.addHandler(n,r)}addTags(t,r=!0){this.removeTags(t),this.tags.push(...t),r&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(r=>!t.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!t.includes(r))}addMetadata(t,r=!0){this.metadata={...this.metadata,...t},r&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(let r of Object.keys(t))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(t=[],r=!0){let n=new e(this._parentRunId);for(let o of this.handlers){let i=this.inheritableHandlers.includes(o);n.addHandler(o,i)}for(let o of this.tags){let i=this.inheritableTags.includes(o);n.addTags([o],i)}for(let o of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(o);n.addMetadata({[o]:this.metadata[o]},i)}for(let o of t)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===o.name)||n.addHandler(o,r);return n}static fromHandlers(t){class r extends FM{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:Xd()}),Object.assign(this,t)}}let n=new this;return n.addHandler(new r),n}static configure(t,r,n,o,i,a,s){return this._configureSync(t,r,n,o,i,a,s)}static _configureSync(t,r,n,o,i,a,s){let u;(t||r)&&(Array.isArray(t)||!t?(u=new e,u.setHandlers(t?.map(V$)??[],!0)):u=t,u=u.copy(Array.isArray(r)?r.map(V$):r?.handlers,!1));let l=Jt("LANGCHAIN_VERBOSE")==="true"||s?.verbose,c=jD.getTraceableRunTree()?.tracingEnabled||xLe(),d=c||(Jt("LANGCHAIN_TRACING")??!1);if(l||d){if(u||(u=new e),l&&!u.handlers.some(f=>f.name===B$.prototype.name)){let f=new B$;u.addHandler(f,!0)}if(d&&!u.handlers.some(f=>f.name==="langchain_tracer")&&c){let f=new jD;u.addHandler(f,!0),u._parentRunId=jD.getTraceableRunTree()?.id??u._parentRunId}}for(let{contextVar:f,inheritable:p=!0,handlerClass:h,envVar:m}of OLe()){let _=m&&Jt(m)==="true"&&h,g,v=f!==void 0?jse(f):void 0;v&&oLe(v)?g=v:_&&(g=new h({})),g!==void 0&&(u||(u=new e),u.handlers.some(S=>S.name===g.name)||u.addHandler(g,p))}return(n||o)&&u&&(u.addTags(n??[]),u.addTags(o??[],!1)),(i||a)&&u&&(u.addMetadata(i??{}),u.addMetadata(a??{},!1)),u}}});var bV,F9t,PLe,Bse,jc,TLe=C(()=>{Rse();z$();bO();bV=class{getStore(){}run(t,r){return r()}enterWith(t){}},F9t=new bV,PLe=Symbol.for("lc:child_config"),Bse=class{getInstance(){return yO()??F9t}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[PLe]}runWithConfig(t,r,n){let o=ns._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),a=i.getStore(),s=o?.getParentRunId(),u=o?.handlers?.find(c=>c?.name==="langchain_tracer"),l;return u&&s?l=u.convertToRunTree(s):n||(l=new bS({name:"",tracingEnabled:!1})),l&&(l.extra={...l.extra,[PLe]:t}),a!==void 0&&a[$M]!==void 0&&(l[$M]=a[$M]),i.run(l,r)}initializeGlobalInstance(t){yO()===void 0&&vLe(t)}},jc=new Bse});var LD=C(()=>{TLe();z$()});async function af(e){return ns._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function vV(...e){let t={};for(let r of e.filter(n=>!!n))for(let n of Object.keys(r))if(n==="metadata")t[n]={...t[n],...r[n]};else if(n==="tags"){let o=t[n]??[];t[n]=[...new Set(o.concat(r[n]??[]))]}else if(n==="configurable")t[n]={...t[n],...r[n]};else if(n==="timeout")t.timeout===void 0?t.timeout=r.timeout:r.timeout!==void 0&&(t.timeout=Math.min(t.timeout,r.timeout));else if(n==="signal")t.signal===void 0?t.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if(n==="callbacks"){let o=t.callbacks,i=r.callbacks;if(Array.isArray(i))if(!o)t.callbacks=i;else if(Array.isArray(o))t.callbacks=o.concat(i);else{let a=o.copy();for(let s of i)a.addHandler(V$(s),!0);t.callbacks=a}else if(i)if(!o)t.callbacks=i;else if(Array.isArray(o)){let a=i.copy();for(let s of o)a.addHandler(V$(s),!0);t.callbacks=a}else t.callbacks=new ns(i._parentRunId,{handlers:o.handlers.concat(i.handlers),inheritableHandlers:o.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(o.tags.concat(i.tags))),inheritableTags:Array.from(new Set(o.inheritableTags.concat(i.inheritableTags))),metadata:{...o.metadata,...i.metadata}})}else{let o=n;t[o]=r[o]??t[o]}return t}function Rr(e){let t=jc.getRunnableConfig(),r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:n,runName:o,...i}=t;r=Object.entries(i).reduce((a,[s,u])=>(u!==void 0&&(a[s]=u),a),r)}if(e&&(r=Object.entries(e).reduce((n,[o,i])=>(i!==void 0&&(n[o]=i),n),r)),r?.configurable)for(let n of Object.keys(r.configurable))k9t.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");let n=AbortSignal.timeout(r.timeout);r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,n])):r.signal=n,delete r.timeout}return r}function Ta(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:o,configurable:i,runId:a}={}){let s=Rr(e);return t!==void 0&&(delete s.runName,s.callbacks=t),n!==void 0&&(s.recursionLimit=n),r!==void 0&&(s.maxConcurrency=r),o!==void 0&&(s.runName=o),i!==void 0&&(s.configurable={...s.configurable,...i}),a!==void 0&&delete s.runId,s}function Xf(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}var _V,k9t,ny=C(()=>{bO();LD();_V=25;k9t=new Set(["string","number","boolean"])});async function oy(e,t){if(t===void 0)return e;let r;return Promise.race([e.catch(n=>{if(!t?.aborted)throw n}),new Promise((n,o)=>{r=()=>{o(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&o(new Error("Aborted"))})]).finally(()=>t.removeEventListener("abort",r))}var $se=C(()=>{});function qse(e,t=2){let r=Array.from({length:t},()=>[]);return r.map(async function*(o){for(;;)if(o.length===0){let i=await e.next();for(let a of r)a.push(i)}else{if(o[0].done)return;yield o.shift().value}})}function al(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){let r={...e};for(let[n,o]of Object.entries(t))n in r&&!Array.isArray(r[n])?r[n]=al(r[n],o):r[n]=o;return r}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}async function MLe(e,t,r,n,...o){let i=new xS({generator:t,startSetup:r,signal:n}),a=await i.setup;return{output:e(i,a,...o),setup:a}}var Nc,xS,iy=C(()=>{ny();LD();$se();Nc=class e extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){let t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let r=t.getReader();return new e({start(n){return o();function o(){return r.read().then(({done:i,value:a})=>{if(i){n.close();return}return n.enqueue(a),o()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(r){let{value:n,done:o}=await t.next();o&&r.close(),r.enqueue(n)},async cancel(r){await t.return(r)}})}};xS=class{constructor(t){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((r,n)=>{jc.runWithConfig(Xf(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(r,n):this.firstResult.then(o=>r(void 0),n)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?jc.runWithConfig(Xf(this.config),this.signal?async()=>oy(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}});async function ILe(e,t){if(t==="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.");let{inputs:r}=e;if(["retriever","llm","prompt"].includes(e.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function ALe(e,t){let{outputs:r}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function B9t(e){return e!==void 0&&e.message!==void 0}var Lm,W$,RLe,J$,DLe=C(()=>{gse();kM();iy();BM();Lm=class{constructor(t){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=t.ops??[]}concat(t){let r=this.ops.concat(t.ops),n=fO({},r);return new W$({ops:r,state:n[n.length-1].newDocument})}},W$=class e extends Lm{constructor(t){super(t),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=t.state}concat(t){let r=this.ops.concat(t.ops),n=fO(this.state,t.ops);return new e({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(t){let r=fO({},t.ops);return new e({ops:t.ops,state:r[r.length-1].newDocument})}},RLe=e=>e.name==="log_stream_tracer";J$=class extends Xp{constructor(t){super({_awaitHandler:!0,...t}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Nc.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;let r=t.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(n=n||r.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(n=n&&r.every(o=>!this.excludeTags?.includes(o))),n}async*tapOutputIterable(t,r){for await(let n of r){if(t!==this.rootId){let o=this.keyMapByRunId[t];o&&await this.writer.write(new Lm({ops:[{op:"add",path:`/logs/${o}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new Lm({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;let r=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=r===1?t.name:`${t.name}:${r}`;let n={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await ILe(t,this._schemaFormat)),await this.writer.write(new Lm({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:n}]}))}async onRunUpdate(t){try{let r=this.keyMapByRunId[t.id];if(r===void 0)return;let n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${r}/inputs`,value:await ILe(t,this._schemaFormat)}),n.push({op:"add",path:`/logs/${r}/final_output`,value:await ALe(t,this._schemaFormat)}),t.end_time!==void 0&&n.push({op:"add",path:`/logs/${r}/end_time`,value:new Date(t.end_time).toISOString()});let o=new Lm({ops:n});await this.writer.write(o)}finally{if(t.id===this.rootId){let r=new Lm({ops:[{op:"replace",path:"/final_output",value:await ALe(t,this._schemaFormat)}]});await this.writer.write(r),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,r,n){let o=this.keyMapByRunId[t.id];if(o===void 0)return;let i=t.inputs.messages!==void 0,a;i?B9t(n?.chunk)?a=n?.chunk:a=new Jr({id:`run-${t.id}`,content:r}):a=r;let s=new Lm({ops:[{op:"add",path:`/logs/${o}/streamed_output_str/-`,value:r},{op:"add",path:`/logs/${o}/streamed_output/-`,value:a}]});await this.writer.write(s)}}});var G$,nh,oi,FD=C(()=>{G$="__run",nh=class e{constructor(t){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},oi=class e extends nh{constructor(t){super(t),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=t.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}}});function wV({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}var jLe,SV,NLe=C(()=>{kM();iy();BM();FD();jLe=e=>e.name==="event_stream_tracer",SV=class extends Xp{constructor(t){super({_awaitHandler:!0,...t}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Nc.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){let r=t.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(n=n||r.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(n=n&&r.every(o=>!this.excludeTags?.includes(o))),n}async*tapOutputIterable(t,r){let n=await r.next();if(n.done)return;let o=this.runInfoMap.get(t);if(o===void 0){yield n.value;return}function i(s,u){return s==="llm"&&typeof u=="string"?new nh({text:u}):u}let a=this.tappedPromises.get(t);if(a===void 0){let s;a=new Promise(u=>{s=u}),this.tappedPromises.set(t,a);try{let u={event:`on_${o.runType}_stream`,run_id:t,name:o.name,tags:o.tags,metadata:o.metadata,data:{}};await this.send({...u,data:{chunk:i(o.runType,n.value)}},o),yield n.value;for await(let l of r)o.runType!=="tool"&&o.runType!=="retriever"&&await this.send({...u,data:{chunk:i(o.runType,l)}},o),yield l}finally{s()}}else{yield n.value;for await(let s of r)yield s}}async send(t,r){this._includeRun(r)&&await this.writer.write(t)}async sendEndEvent(t,r){let n=this.tappedPromises.get(t.run_id);n!==void 0?n.then(()=>{this.send(t,r)}):await this.send(t,r)}async onLLMStart(t){let r=wV(t),n=t.inputs.messages!==void 0?"chat_model":"llm",o={tags:t.tags??[],metadata:t.extra?.metadata??{},name:r,runType:n,inputs:t.inputs};this.runInfoMap.set(t.id,o);let i=`on_${n}_start`;await this.send({event:i,data:{input:t.inputs},name:r,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},o)}async onLLMNewToken(t,r,n){let o=this.runInfoMap.get(t.id),i,a;if(o===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(o.runType==="chat_model")a="on_chat_model_stream",n?.chunk===void 0?i=new Jr({content:r,id:`run-${t.id}`}):i=n.chunk.message;else if(o.runType==="llm")a="on_llm_stream",n?.chunk===void 0?i=new nh({text:r}):i=n.chunk;else throw new Error(`Unexpected run type ${o.runType}`);await this.send({event:a,data:{chunk:i},run_id:t.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(t){let r=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let n;if(r===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);let o=t.outputs?.generations,i;if(r.runType==="chat_model"){for(let a of o??[]){if(i!==void 0)break;i=a[0]?.message}n="on_chat_model_end"}else if(r.runType==="llm")i={generations:o?.map(a=>a.map(s=>({text:s.text,generationInfo:s.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${r.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:r.inputs},run_id:t.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}async onChainStart(t){let r=wV(t),n=t.run_type??"chain",o={tags:t.tags??[],metadata:t.extra?.metadata??{},name:r,runType:t.run_type},i={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(i={},o.inputs={}):t.inputs.input!==void 0?(i.input=t.inputs.input,o.inputs=t.inputs.input):(i.input=t.inputs,o.inputs=t.inputs),this.runInfoMap.set(t.id,o),await this.send({event:`on_${n}_start`,data:i,name:r,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},o)}async onChainEnd(t){let r=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),r===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);let n=`on_${t.run_type}_end`,o=t.inputs??r.inputs??{},a={output:t.outputs?.output??t.outputs,input:o};o.input&&Object.keys(o).length===1&&(a.input=o.input,r.inputs=o.input),await this.sendEndEvent({event:n,data:a,run_id:t.id,name:r.name,tags:r.tags,metadata:r.metadata??{}},r)}async onToolStart(t){let r=wV(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:r,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,n),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:r,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},n)}async onToolEnd(t){let r=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),r===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(r.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);let n=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:r.inputs},run_id:t.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}async onRetrieverStart(t){let r=wV(t),o={tags:t.tags??[],metadata:t.extra?.metadata??{},name:r,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,o),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:r,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},o)}async onRetrieverEnd(t){let r=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),r===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:r.inputs},run_id:t.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}async handleCustomEvent(t,r,n){let o=this.runInfoMap.get(n);if(o===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:t,tags:o.tags,metadata:o.metadata,data:r},o)}async finish(){let t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}}});var LLe,xV,$9t,q9t,Qf,kD=C(()=>{LLe=B(C6(),1),xV=B(j6(),1),$9t=[400,401,402,403,404,405,406,407,409],q9t=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;let t=e?.response?.status??e?.status;if(t&&$9t.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){let r=new Error(e?.message);throw r.name="InsufficientQuotaError",r}},Qf=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??q9t;let r="default"in xV.default?xV.default.default:xV.default;this.queue=new r({concurrency:this.maxConcurrency})}call(t,...r){return this.queue.add(()=>(0,LLe.default)(()=>t(...r).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,r,...n){return t.signal?Promise.race([this.call(r,...n),new Promise((o,i)=>{t.signal?.addEventListener("abort",()=>{i(new Error("AbortError"))})})]):this.call(r,...n)}fetch(...t){return this.call(()=>fetch(...t).then(r=>r.ok?r:Promise.reject(r)))}}});var K$,FLe=C(()=>{kM();K$=class extends Xp{constructor({config:t,onStart:r,onEnd:n,onError:o}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=t,this.argOnStart=r,this.argOnEnd=n,this.argOnError=o}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}}});function Y$(e){return e?e.lc_runnable:!1}var CV,Use=C(()=>{CV=class{constructor(t){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,r){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,o=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(r)),this.includeTags!==void 0&&(n=n||o.some(i=>this.includeTags?.includes(i))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(r)),this.excludeTags!==void 0&&(n=n&&o.every(i=>!this.excludeTags?.includes(i))),n}}});var BLe,kLe,$Le,OV=C(()=>{BLe=Symbol("Let zodToJsonSchema decide on which parser to use"),kLe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},$Le=e=>typeof e=="string"?{...kLe,name:e}:{...kLe,...e}});var qLe,zse=C(()=>{OV();qLe=e=>{let t=$Le(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}}});function Hse(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function mn(e,t,r,n,o){e[t]=r,Hse(e,t,n,o)}var _O=C(()=>{});function ULe(){return{}}var Vse=C(()=>{});function zLe(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==re.ZodAny&&(r.items=Lt(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&mn(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&mn(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(mn(r,"minItems",e.exactLength.value,e.exactLength.message,t),mn(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}var Wse=C(()=>{bd();_O();os()});function HLe(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?mn(r,"minimum",n.value,n.message,t):mn(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),mn(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?mn(r,"maximum",n.value,n.message,t):mn(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),mn(r,"maximum",n.value,n.message,t));break;case"multipleOf":mn(r,"multipleOf",n.value,n.message,t);break}return r}var Jse=C(()=>{_O()});function VLe(){return{type:"boolean"}}var Gse=C(()=>{});function EV(e,t){return Lt(e.type._def,t)}var PV=C(()=>{os()});var WLe,Kse=C(()=>{os();WLe=(e,t)=>Lt(e.innerType._def,t)});function Yse(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Yse(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return U9t(e,t)}}var U9t,Zse=C(()=>{_O();U9t=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":mn(r,"minimum",n.value,n.message,t);break;case"max":mn(r,"maximum",n.value,n.message,t);break}return r}});function JLe(e,t){return{...Lt(e.innerType._def,t),default:e.defaultValue()}}var Xse=C(()=>{os()});function GLe(e,t){return t.effectStrategy==="input"?Lt(e.schema._def,t):{}}var Qse=C(()=>{os()});function KLe(e){return{type:"string",enum:Array.from(e.values)}}var eue=C(()=>{});function YLe(e,t){let r=[Lt(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Lt(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(i=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(i=>{if(z9t(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...u}=i;a=u}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}var z9t,tue=C(()=>{os();z9t=e=>"type"in e&&e.type==="string"?!1:"allOf"in e});function ZLe(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var rue=C(()=>{});function TV(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":mn(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":mn(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":km(r,"email",n.message,t);break;case"format:idn-email":km(r,"idn-email",n.message,t);break;case"pattern:zod":Cd(r,Fm.email,n.message,t);break}break;case"url":km(r,"uri",n.message,t);break;case"uuid":km(r,"uuid",n.message,t);break;case"regex":Cd(r,n.regex,n.message,t);break;case"cuid":Cd(r,Fm.cuid,n.message,t);break;case"cuid2":Cd(r,Fm.cuid2,n.message,t);break;case"startsWith":Cd(r,RegExp(`^${oue(n.value,t)}`),n.message,t);break;case"endsWith":Cd(r,RegExp(`${oue(n.value,t)}$`),n.message,t);break;case"datetime":km(r,"date-time",n.message,t);break;case"date":km(r,"date",n.message,t);break;case"time":km(r,"time",n.message,t);break;case"duration":km(r,"duration",n.message,t);break;case"length":mn(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),mn(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Cd(r,RegExp(oue(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&km(r,"ipv4",n.message,t),n.version!=="v4"&&km(r,"ipv6",n.message,t);break}case"base64url":Cd(r,Fm.base64url,n.message,t);break;case"jwt":Cd(r,Fm.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Cd(r,Fm.ipv4Cidr,n.message,t),n.version!=="v4"&&Cd(r,Fm.ipv6Cidr,n.message,t);break}case"emoji":Cd(r,Fm.emoji(),n.message,t);break;case"ulid":{Cd(r,Fm.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{km(r,"binary",n.message,t);break}case"contentEncoding:base64":{mn(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Cd(r,Fm.base64,n.message,t);break}}break}case"nanoid":Cd(r,Fm.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function oue(e,t){return t.patternStrategy==="escape"?V9t(e):e}function V9t(e){let t="";for(let r=0;ro.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):mn(e,"format",t,r,n)}function Cd(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:XLe(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):mn(e,"pattern",XLe(t,n),r,n)}function XLe(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,a=!1,s=!1;for(let u=0;u{_O();Fm={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nue===void 0&&(nue=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nue),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}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};H9t=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function IV(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===re.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=TV(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===re.ZodBranded&&e.keyType._def.type._def.typeName===re.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=EV(e.keyType._def,t);return{...r,propertyNames:o}}}return r}var AV=C(()=>{bd();os();MV();PV()});function QLe(e,t){if(t.mapStrategy==="record")return IV(e,t);let r=Lt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var iue=C(()=>{os();AV()});function eFe(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var aue=C(()=>{});function tFe(){return{not:{}}}var sue=C(()=>{});function rFe(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var uue=C(()=>{});function oFe(e,t){if(t.target==="openApi3")return nFe(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Z$&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Z$[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return nFe(e,t)}var Z$,nFe,RV=C(()=>{os();Z$={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};nFe=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Lt(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function iFe(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Z$[e.innerType._def.typeName],nullable:!0}:{type:[Z$[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=Lt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Lt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var lue=C(()=>{os();RV()});function aFe(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Hse(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?mn(r,"minimum",n.value,n.message,t):mn(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),mn(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?mn(r,"maximum",n.value,n.message,t):mn(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),mn(r,"maximum",n.value,n.message,t));break;case"multipleOf":mn(r,"multipleOf",n.value,n.message,t);break}return r}var cue=C(()=>{_O()});function W9t(e,t){return t.removeAdditionalStrategy==="strict"?e.catchall._def.typeName==="ZodNever"?e.unknownKeys!=="strict":Lt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:e.catchall._def.typeName==="ZodNever"?e.unknownKeys==="passthrough":Lt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function sFe(e,t){let r=t.target==="openAi",n={type:"object",...Object.entries(e.shape()).reduce((o,[i,a])=>{if(a===void 0||a._def===void 0)return o;let s=a.isOptional();s&&r&&(a instanceof Yd&&(a=a._def.innerType),a.isNullable()||(a=a.nullable()),s=!1);let u=Lt(a._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});return u===void 0?o:{properties:{...o.properties,[i]:u},required:s?o.required:[...o.required,i]}},{properties:{},required:[]}),additionalProperties:W9t(e,t)};return n.required.length||delete n.required,n}var due=C(()=>{bd();os()});var uFe,fue=C(()=>{os();uFe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Lt(e.innerType._def,t);let r=Lt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}}});var lFe,pue=C(()=>{os();lFe=(e,t)=>{if(t.pipeStrategy==="input")return Lt(e.in._def,t);if(t.pipeStrategy==="output")return Lt(e.out._def,t);let r=Lt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Lt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function cFe(e,t){return Lt(e.type._def,t)}var hue=C(()=>{os()});function dFe(e,t){let n={type:"array",uniqueItems:!0,items:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&mn(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&mn(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}var mue=C(()=>{_O();os()});function fFe(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Lt(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Lt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Lt(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var gue=C(()=>{os()});function pFe(){return{not:{}}}var yue=C(()=>{});function hFe(){return{}}var bue=C(()=>{});var mFe,_ue=C(()=>{os();mFe=(e,t)=>Lt(e.innerType._def,t)});function Lt(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==BLe)return a}if(n&&!r){let a=J9t(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=K9t(e,e.typeName,t);return i&&Y9t(e,t,i),o.jsonSchema=i,i}var J9t,G9t,K9t,Y9t,os=C(()=>{bd();Vse();Wse();Jse();Gse();PV();Kse();Zse();Xse();Qse();eue();tue();rue();iue();aue();sue();uue();lue();cue();due();fue();pue();hue();AV();mue();MV();gue();yue();RV();bue();_ue();OV();J9t=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:G9t(t.currentPath,e.path)};case"none":case"seen":return e.path.lengtht.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):t.$refStrategy==="seen"?{}:void 0}},G9t=(e,t)=>{let r=0;for(;r{switch(t){case re.ZodString:return TV(e,r);case re.ZodNumber:return aFe(e,r);case re.ZodObject:return sFe(e,r);case re.ZodBigInt:return HLe(e,r);case re.ZodBoolean:return VLe();case re.ZodDate:return Yse(e,r);case re.ZodUndefined:return pFe();case re.ZodNull:return rFe(r);case re.ZodArray:return zLe(e,r);case re.ZodUnion:case re.ZodDiscriminatedUnion:return oFe(e,r);case re.ZodIntersection:return YLe(e,r);case re.ZodTuple:return fFe(e,r);case re.ZodRecord:return IV(e,r);case re.ZodLiteral:return ZLe(e,r);case re.ZodEnum:return KLe(e);case re.ZodNativeEnum:return eFe(e);case re.ZodNullable:return iFe(e,r);case re.ZodOptional:return uFe(e,r);case re.ZodMap:return QLe(e,r);case re.ZodSet:return dFe(e,r);case re.ZodLazy:return Lt(e.getter()._def,r);case re.ZodPromise:return cFe(e,r);case re.ZodNaN:case re.ZodNever:return tFe();case re.ZodEffects:return GLe(e,r);case re.ZodAny:return ULe();case re.ZodUnknown:return hFe();case re.ZodDefault:return JLe(e,r);case re.ZodBranded:return EV(e,r);case re.ZodReadonly:return mFe(e,r);case re.ZodCatch:return WLe(e,r);case re.ZodPipeline:return lFe(e,r);case re.ZodFunction:case re.ZodVoid:case re.ZodSymbol:return;default:return(n=>{})(t)}},Y9t=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r)});var Li,vue=C(()=>{os();zse();Li=(e,t)=>{let r=qLe(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((u,[l,c])=>({...u,[l]:Lt(c._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??{}}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Lt(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??{},a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(i.title=a);let s=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s}});var oh=C(()=>{OV();zse();_O();os();Vse();Wse();Jse();Gse();PV();Kse();Zse();Xse();Qse();eue();tue();rue();iue();aue();sue();uue();lue();cue();due();fue();pue();hue();_ue();AV();mue();MV();gue();yue();RV();bue();vue();vue()});function wue(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}function X9t(e){let t="";for(let[r,n]of Object.entries(e))t+=` classDef ${r} ${n}; +`;return t}function gFe(e,t,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%% graph TD; -` : "graph TD;\n"; - if (withStyles) { - const defaultClassLabel = "default"; - const formatDict = { - [defaultClassLabel]: "{0}({1})" - }; - if (firstNode !== void 0) { - formatDict[firstNode] = "{0}([{1}]):::first"; - } - if (lastNode !== void 0) { - formatDict[lastNode] = "{0}([{1}]):::last"; - } - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

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

${g}

`:g;Object.keys(_.metadata??{}).length&&(S+=`
${Object.entries(_.metadata??{}).map(([O,T])=>`${O} = ${T}`).join(` +`)}`);let x=(h[m]??h[p]).replace("{0}",wue(m)).replace("{1}",S);l+=` ${x} +`}}let c={};for(let p of t){let h=p.source.split(":"),m=p.target.split(":"),_=h.filter((g,v)=>g===m[v]).join(":");c[_]||(c[_]=[]),c[_].push(p)}let d=new Set;function f(p,h){let m=p.length===1&&p[0].source===p[0].target;if(h&&!m){let _=h.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${_}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(_),l+=` subgraph ${_} +`}for(let _ of p){let{source:g,target:v,data:S,conditional:x}=_,O="";if(S!==void 0){let T=S,E=T.split(" ");E.length>u&&(T=Array.from({length:Math.ceil(E.length/u)},(M,A)=>E.slice(A*u,(A+1)*u).join(" ")).join(" 
 ")),O=x?` -.  ${T}  .-> `:` --  ${T}  --> `}else O=x?" -.-> ":" --> ";l+=` ${wue(g)}${O}${wue(v)}; +`}for(let _ in c)_.startsWith(`${h}:`)&&_!==h&&f(c[_],_);h&&!m&&(l+=` end +`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=X9t(i??{})),l}async function yFe(e,t){let{backgroundColor:r="white"}=t??{},n=btoa(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(` +`));return await i.blob()}var Z9t,bFe=C(()=>{Z9t=["*","_","`"]});function Q9t(e,t){if(e!==void 0&&!CD(e))return e;if(Y$(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function eWt(e){return Y$(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Li(e.data.schema),title:e.data.name}}}function _Fe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function vFe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var X$,wFe=C(()=>{oh();O$();Use();bFe();X$=class e{constructor(t){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=CD(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...eWt(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??Xd(),i={id:o,data:t,name:Q9t(r,t),metadata:n};return this.nodes[o]=i,i}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,o){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:t.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return _Fe(this)}lastNode(){return vFe(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(l=>l.id).every(CD)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(t.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=t.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=t.firstNode(),u=t.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&_Fe(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&vFe(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(t).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=t[o];return CD(o)&&r.get(i)===1?i:o};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=t??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return gFe(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(t){let r=this.drawMermaid(t);return yFe(r,{backgroundColor:t?.backgroundColor})}}});function SFe(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of e)n.enqueue(t.encode(`event: data +data: ${JSON.stringify(o)} -// node_modules/@langchain/core/dist/runnables/graph.js -function nodeDataStr(id, data) { - if (id !== void 0 && !validate_default(id)) { - return id; - } else if (isRunnableInterface(data)) { - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice("Runnable".length) : dataStr; - return dataStr; - } catch (error) { - return data.getName(); - } - } else { - return data.name ?? "UnknownSchema"; - } -} -function nodeDataJson(node) { - if (isRunnableInterface(node.data)) { - return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName() - } - }; - } else { - return { - type: "schema", - data: { ...zodToJsonSchema(node.data.schema), title: node.data.name } - }; - } -} -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !targets.has(node.id)) { - found.push(node); - } - } - return found.length === 1 ? found[0] : void 0; -} -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !sources.has(node.id)) { - found.push(node); - } - } - return found.length === 1 ? found[0] : void 0; -} -var Graph; -var init_graph = __esm({ - "node_modules/@langchain/core/dist/runnables/graph.js"() { - init_esm(); - init_esm_browser(); - init_utils3(); - init_graph_mermaid(); - Graph = class { - constructor(params) { - Object.defineProperty(this, "nodes", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "edges", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; - } - // Convert the graph to a JSON-serializable format. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i3) => { - stableNodeIds[node.id] = validate_default(node.id) ? i3 : node.id; - }); - return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node) - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target] - }; - if (typeof edge.data !== "undefined") { - item.data = edge.data; - } - if (typeof edge.conditional !== "undefined") { - item.conditional = edge.conditional; - } - return item; - }) - }; - } - addNode(data, id, metadata) { - if (id !== void 0 && this.nodes[id] !== void 0) { - throw new Error(`Node with id ${id} already exists`); - } - const nodeId = id ?? v4_default(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - delete this.nodes[node.id]; - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); - } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === void 0) { - throw new Error(`Source node ${source.id} not in graph`); - } - if (this.nodes[target.id] === void 0) { - throw new Error(`Target node ${target.id} not in graph`); - } - const edge = { - source: source.id, - target: target.id, - data, - conditional - }; - this.edges.push(edge); - return edge; - } - firstNode() { - return _firstNode(this); - } - lastNode() { - return _lastNode(this); - } - /** - * Add all nodes and edges from another graph. - * Note this doesn't check for duplicates, nor does it connect the graphs. - */ - extend(graph, prefix = "") { - let finalPrefix = prefix; - const nodeIds = Object.values(graph.nodes).map((node) => node.id); - if (nodeIds.every(validate_default)) { - finalPrefix = ""; - } - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; - }); - const newEdges = graph.edges.map((edge) => { - return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target) - }; - }); - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [ - first ? { id: prefixed(first.id), data: first.data } : void 0, - last ? { id: prefixed(last.id), data: last.data } : void 0 - ]; - } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) { - this.removeNode(firstNode); - } - } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) { - this.removeNode(lastNode); - } - } - /** - * Return a new graph with all nodes re-identified, - * using their unique, readable names where possible. - */ - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = /* @__PURE__ */ new Map(); - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (validate_default(nodeId) && nodeLabelCounts.get(label) === 1) { - return label; - } else { - return nodeId; - } - }; - return new Graph({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ - getNodeId(id), - { ...node, id: getNodeId(id) } - ])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target) - })) - }); - } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc" - }, wrapLabelNWords } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords - }); - } - async drawMermaidPng(params) { - const mermaidSyntax = this.drawMermaid(params); - return drawMermaidPng(mermaidSyntax, { - backgroundColor: params?.backgroundColor - }); - } - }; - } -}); +`));n.enqueue(t.encode(`event: end -// node_modules/@langchain/core/dist/runnables/wrappers.js -function convertToHttpEventStream(stream) { - const encoder = new TextEncoder(); - const finalStream = new ReadableStream({ - async start(controller) { - for await (const chunk of stream) { - controller.enqueue(encoder.encode(`event: data -data: ${JSON.stringify(chunk)} - -`)); - } - controller.enqueue(encoder.encode("event: end\n\n")); - controller.close(); - } - }); - return IterableReadableStream.fromReadableStream(finalStream); -} -var init_wrappers = __esm({ - "node_modules/@langchain/core/dist/runnables/wrappers.js"() { - init_stream(); - } -}); - -// node_modules/@langchain/core/dist/runnables/iter.js -function isIterableIterator(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && // avoid detecting array/set as iterator - typeof thing.next === "function"; -} -function isAsyncIterable(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; -} -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) { - break; - } else { - yield value; - } - } -} -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) { - break; - } else { - yield value; - } - } -} -var isIterator; -var init_iter = __esm({ - "node_modules/@langchain/core/dist/runnables/iter.js"() { - init_singletons(); - init_config(); - isIterator = (x2) => x2 != null && typeof x2 === "object" && "next" in x2 && typeof x2.next === "function"; - } -}); - -// node_modules/@langchain/core/dist/runnables/base.js -function _coerceToDict2(value, defaultKey) { - return value && !Array.isArray(value) && // eslint-disable-next-line no-instanceof/no-instanceof - !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) { - throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); - } -} -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") { - return new RunnableLambda({ func: coerceable }); - } else if (Runnable.isRunnable(coerceable)) { - return coerceable; - } else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) { - runnables[key] = _coerceToRunnable(value); - } - return new RunnableMap({ - steps: runnables - }); - } else { - throw new Error(`Expected a Runnable, function or object. -Instead got an unsupported type.`); - } -} -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? fields.schema?.description; - if (fields.schema.constructor === z.ZodString) { - return new RunnableToolLike({ - name, - description, - schema: z.object({ - input: z.string() - }).transform((input) => input.input), - bound: runnable - }); - } - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable - }); -} -var import_p_retry3, Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableTraceable, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, RunnableToolLike; -var init_base4 = __esm({ - "node_modules/@langchain/core/dist/runnables/base.js"() { - init_lib(); - import_p_retry3 = __toESM(require_p_retry(), 1); - init_esm_browser(); - init_traceable2(); - init_log_stream(); - init_event_stream(); - init_serializable(); - init_stream(); - init_signal(); - init_config(); - init_async_caller2(); - init_root_listener(); - init_utils3(); - init_singletons(); - init_graph(); - init_wrappers(); - init_iter(); - init_utils(); - Runnable = class extends Serializable { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_runnable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - getName(suffix) { - const name = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.name ?? this.constructor.lc_name() ?? this.constructor.name - ); - return suffix ? `${name}${suffix}` : name; - } - /** - * Bind arguments to a Runnable, returning a new Runnable. - * @param kwargs - * @returns A new RunnableBinding that, when invoked, will apply the bound args. - */ - bind(kwargs) { - return new RunnableBinding({ bound: this, kwargs, config: {} }); - } - /** - * Return a new Runnable that maps a list of inputs to a list of outputs, - * by calling invoke() with each input. - */ - map() { - return new RunnableEach({ bound: this }); - } - /** - * Add retry logic to an existing runnable. - * @param kwargs - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - return new RunnableBinding({ - bound: this, - config, - kwargs: {} - }); - } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - return new RunnableWithFallbacks({ - runnable: this, - fallbacks - }); - } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) { - throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - } - if (Array.isArray(options)) { - return options.map(ensureConfig); - } - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_2, i3) => ensureConfig(i3 === 0 ? options : subsequent)); - } - return Array.from({ length }, () => ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const caller2 = new AsyncCaller2({ - maxConcurrency, - onFailedAttempt: (e3) => { - throw e3; - } - }); - const batchCalls = inputs.map((input, i3) => caller2.call(async () => { - try { - const result = await this.invoke(input, configList[i3]); - return result; - } catch (e3) { - if (batchOptions?.returnExceptions) { - return e3; - } - throw e3; - } - })); - return Promise.all(batchCalls); - } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); - } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === void 0) { - runnableConfig = ensureConfig(options); - } else { - runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal - }); - } - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; - } - async _callWithConfig(func, input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName()); - delete config.runId; - let output; - try { - const promise = func.call(this, input, config, runManager); - output = await raceWithSignal(promise, options?.signal); - } catch (e3) { - await runManager?.handleChainError(e3); - throw e3; - } - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - return output; - } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), optionsList[i3].runId, optionsList[i3].runType, void 0, void 0, optionsList[i3].runName ?? this.getName()); - delete optionsList[i3].runId; - return handleStartRes; - })); - let outputs; - try { - const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); - outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); - } catch (e3) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e3))); - throw e3; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(outputs, "output")))); - return outputs; - } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) { - if (finalInput === void 0) { - finalInput = chunk; - } else { - try { - finalInput = concat(finalInput, chunk); - } catch { - finalInput = void 0; - finalInputSupported = false; - } - } - } - yield chunk; - } - } - let runManager; - try { - const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName()), options?.signal, config); - delete config.runId; - runManager = pipe.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe.output; - if (streamEventsHandler !== void 0 && runManager !== void 0) { - iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); - } - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== void 0 && runManager !== void 0) { - iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); - } - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === void 0) { - finalOutput = chunk; - } else { - try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } - } - } catch (e3) { - await runManager?.handleChainError(e3, void 0, void 0, void 0, { - inputs: _coerceToDict2(finalInput, "input") - }); - throw e3; - } - await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict2(finalInput, "input") }); - } - getGraph(_2) { - const graph = new Graph(); - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: z.any() - }); - const runnableNode = graph.addNode(this); - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: z.any() - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; - } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable) - }); - } - /** - * Pick keys from the dict output of this runnable. Returns a new runnable. - */ - pick(keys) { - return this.pipe(new RunnablePick(keys)); - } - /** - * Assigns new fields to the dict output of this runnable. Returns a new runnable. - */ - assign(mapping) { - return this.pipe( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableAssign( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableMap({ steps: mapping }) - ) - ); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === void 0) { - finalChunk = chunk; - } else { - finalChunk = concat(finalChunk, chunk); - } - } - yield* this._streamIterator(finalChunk, ensureConfig(options)); - } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original" - }); - const config = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config); - } - async *_streamLog(input, logStreamCallbackHandler, config) { - const { callbacks } = config; - if (callbacks === void 0) { - config.callbacks = [logStreamCallbackHandler]; - } else if (Array.isArray(callbacks)) { - config.callbacks = callbacks.concat([logStreamCallbackHandler]); - } else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - config.callbacks = copiedCallbacks; - } - const runnableStreamPromise = this.stream(input, config); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: "/streamed_output/-", - value: chunk - } - ] - }); - await logStreamCallbackHandler.writer.write(patch); - } - } finally { - await logStreamCallbackHandler.writer.close(); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) { - yield log; - } - } finally { - await runnableStreamConsumePromise; - } - } - streamEvents(input, options, streamOptions) { - let stream; - if (options.version === "v1") { - stream = this._streamEventsV1(input, options, streamOptions); - } else if (options.version === "v2") { - stream = this._streamEventsV2(input, options, streamOptions); - } else { - throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); - } - if (options.encoding === "text/event-stream") { - return convertToHttpEventStream(stream); - } else { - return IterableReadableStream.fromAsyncGenerator(stream); - } - } - async *_streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false - }); - const config = ensureConfig(options); - const runId = config.runId ?? v4_default(); - config.runId = runId; - const callbacks = config.callbacks; - if (callbacks === void 0) { - config.callbacks = [eventStreamer]; - } else if (Array.isArray(callbacks)) { - config.callbacks = callbacks.concat(eventStreamer); - } else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - config.callbacks = copiedCallbacks; - } - const abortController = new AbortController(); - const outerThis = this; - async function consumeRunnableStream() { - try { - let signal; - if (options?.signal) { - if ("any" in AbortSignal) { - signal = AbortSignal.any([ - abortController.signal, - options.signal - ]); - } else { - signal = options.signal; - options.signal.addEventListener("abort", () => { - abortController.abort(); - }, { once: true }); - } - } else { - signal = abortController.signal; - } - const runnableStream = await outerThis.stream(input, { - ...config, - signal - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - for await (const _2 of tappedStream) { - if (abortController.signal.aborted) - break; - } - } finally { - await eventStreamer.finish(); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; - continue; - } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - if (event.data?.input) { - delete event.data.input; - } - } - yield event; - } - } finally { - abortController.abort(); - await runnableStreamConsumePromise; - } - } - async *_streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config = ensureConfig(options); - const rootTags = config.tags ?? []; - const rootMetadata = config.metadata ?? {}; - const rootName = config.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events" - }); - const rootEventFilter = new _RootEventFilter({ - ...streamOptions - }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config); - for await (const log of logStream) { - if (!runLog) { - runLog = RunLog.fromRunLogPatch(log); - } else { - runLog = runLog.concat(log); - } - if (runLog.state === void 0) { - throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); - } - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state3 = { ...runLog.state }; - const event = { - run_id: state3.id, - event: `on_${state3.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { - input - } - }; - if (rootEventFilter.includeEvent(event, state3.type)) { - yield event; - } - } - const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path]; - if (logEntry.end_time === void 0) { - if (logEntry.streamed_output.length > 0) { - eventType = "stream"; - } else { - eventType = "start"; - } - } else { - eventType = "end"; - } - if (eventType === "start") { - if (logEntry.inputs !== void 0) { - data.input = logEntry.inputs; - } - } else if (eventType === "end") { - if (logEntry.inputs !== void 0) { - data.input = logEntry.inputs; - } - data.output = logEntry.final_output; - } else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); - } - data = { chunk: logEntry.streamed_output[0] }; - logEntry.streamed_output = []; - } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data - }; - } - const { state: state2 } = runLog; - if (state2.streamed_output.length > 0) { - const chunkCount = state2.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`); - } - const data = { chunk: state2.streamed_output[0] }; - state2.streamed_output = []; - const event = { - event: `on_${state2.type}_stream`, - run_id: state2.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data - }; - if (rootEventFilter.includeEvent(event, state2.type)) { - yield event; - } - } - } - const state = runLog?.state; - if (state !== void 0) { - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { - output: state.final_output - } - }; - if (rootEventFilter.includeEvent(event, state.type)) - yield event; - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnable(thing) { - return isRunnableInterface(thing); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError - }) - ] - }) - ] - }); - } - /** - * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` - * which contains the runnable, name, description and schema. - * - * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. - * - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ - asTool(fields) { - return convertRunnableToTool(this, fields); - } - }; - RunnableBinding = class extends Runnable { - static lc_name() { - return "RunnableBinding"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "configFactories", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; - } - getName(suffix) { - return this.bound.getName(suffix); - } - async _mergeConfig(...options) { - const config = mergeConfigs(this.config, ...options); - return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []); - } - bind(kwargs) { - return new this.constructor({ - bound: this.bound, - kwargs: { ...this.kwargs, ...kwargs }, - config: this.config - }); - } - withConfig(config) { - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { ...this.config, ...config } - }); - } - withRetry(fields) { - return new this.constructor({ - bound: this.bound.withRetry(fields), - kwargs: this.kwargs, - config: this.config - }); - } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async *transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - streamEvents(input, options, streamOptions) { - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), - version: options.version - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); - } - static isRunnableBinding(thing) { - return thing.bound && Runnable.isRunnable(thing.bound); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError - }) - ] - }) - ] - }); - } - }; - RunnableEach = class extends Runnable { - static lc_name() { - return "RunnableEach"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - } - /** - * Binds the runnable with the specified arguments. - * @param kwargs The arguments to bind the runnable with. - * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. - */ - bind(kwargs) { - return new RunnableEach({ - bound: this.bound.bind(kwargs) - }); - } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke.bind(this), inputs, config); - } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableEach({ - bound: this.bound.withListeners({ onStart, onEnd, onError }) - }); - } - }; - RunnableRetry = class extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "maxAttemptNumber", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: () => { - } - }); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; - return patchConfig(config, { callbacks: runManager?.getChild(tag) }); - } - async _invoke(input, config, runManager) { - return (0, import_p_retry3.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke.bind(this), input, config); - } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await (0, import_p_retry3.default)(async (attemptNumber) => { - const remainingIndexes = inputs.map((_2, i3) => i3).filter((i3) => resultsMap[i3.toString()] === void 0 || // eslint-disable-next-line no-instanceof/no-instanceof - resultsMap[i3.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i3) => inputs[i3]); - const patchedConfigs = remainingIndexes.map((i3) => this._patchConfigForRetry(attemptNumber, configs?.[i3], runManagers?.[i3])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true - }); - let firstException; - for (let i3 = 0; i3 < results.length; i3 += 1) { - const result = results[i3]; - const resultMapIndex = remainingIndexes[i3]; - if (result instanceof Error) { - if (firstException === void 0) { - firstException = result; - firstException.input = remainingInputs[i3]; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) { - throw firstException; - } - return results; - }, { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } catch (e3) { - if (batchOptions?.returnExceptions !== true) { - throw e3; - } - } - return Object.keys(resultsMap).sort((a3, b3) => parseInt(a3, 10) - parseInt(b3, 10)).map((key) => resultsMap[parseInt(key, 10)]); - } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); - } - }; - RunnableSequence = class extends Runnable { - static lc_name() { - return "RunnableSequence"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "first", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "middle", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "last", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "omitSequenceTags", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; - } - get steps() { - return [this.first, ...this.middle, this.last]; - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i3 = 0; i3 < initialSteps.length; i3 += 1) { - const step = initialSteps[i3]; - const promise = step.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`) - })); - nextStepInput = await raceWithSignal(promise, options?.signal); - } - if (options?.signal?.aborted) { - throw new Error("Aborted"); - } - finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) - })); - } catch (e3) { - await runManager?.handleChainError(e3); - throw e3; - } - await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); - return finalOutput; - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), configList[i3].runId, void 0, void 0, void 0, configList[i3].runName); - delete configList[i3].runId; - return handleStartRes; - })); - let nextStepInputs = inputs; - try { - for (let i3 = 0; i3 < this.steps.length; i3 += 1) { - const step = this.steps[i3]; - const promise = step.batch(nextStepInputs, runManagers.map((runManager, j3) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`); - return patchConfig(configList[j3], { callbacks: childRunManager }); - }), batchOptions); - nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); - } - } catch (e3) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e3))); - throw e3; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(nextStepInputs, "output")))); - return nextStepInputs; - } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId, ...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName); - const steps = [this.first, ...this.middle, this.last]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; - } - try { - let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) - })); - for (let i3 = 1; i3 < steps.length; i3 += 1) { - const step = steps[i3]; - finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i3 + 1}`) - })); - } - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) { - if (finalOutput === void 0) { - finalOutput = chunk; - } else { - try { - finalOutput = concat(finalOutput, chunk); - } catch (e3) { - finalOutput = void 0; - concatSupported = false; - } - } - } - } - } catch (e3) { - await runManager?.handleChainError(e3); - throw e3; - } - await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); - } - getGraph(config) { - const graph = new Graph(); - let currentLastNode = null; - this.steps.forEach((step, index2) => { - const stepGraph = step.getGraph(config); - if (index2 !== 0) { - stepGraph.trimFirstNode(); - } - if (index2 !== this.steps.length - 1) { - stepGraph.trimLastNode(); - } - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) { - throw new Error(`Runnable ${step} has no first node`); - } - if (currentLastNode) { - graph.addEdge(currentLastNode, stepFirstNode); - } - currentLastNode = stepGraph.lastNode(); - }); - return graph; - } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) { - return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle - ]), - last: coerceable.last, - name: this.name ?? coerceable.name - }); - } else { - return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name - }); - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") { - extra.name = nameOrFields; - } else if (nameOrFields !== void 0) { - extra = nameOrFields; - } - return new RunnableSequence({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]) - }); - } - }; - RunnableMap = class extends Runnable { - static lc_name() { - return "RunnableMap"; - } - getStepsKeys() { - return Object.keys(this.steps); - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "steps", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) { - this.steps[key] = _coerceToRunnable(value); - } - } - static from(steps) { - return new RunnableMap({ steps }); - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { - input - }, config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - const output = {}; - try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`map:key:${key}`) - })); - }); - await raceWithSignal(Promise.all(promises), options?.signal); - } catch (e3) { - await runManager?.handleChainError(e3); - throw e3; - } - await runManager?.handleChainEnd(output); - return output; - } - async *_transform(generator, runManager, options) { - const steps = { ...this.steps }; - const inputCopies = atee(generator, Object.keys(steps).length); - const tasks = new Map(Object.entries(steps).map(([key, runnable], i3) => { - const gen = runnable.transform(inputCopies[i3], patchConfig(options, { - callbacks: runManager?.getChild(`map:key:${key}`) - })); - return [key, gen.next().then((result) => ({ key, gen, result }))]; - })); - while (tasks.size) { - const promise = Promise.race(tasks.values()); - const { key, result, gen } = await raceWithSignal(promise, options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result2) => ({ key, gen, result: result2 }))); - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - }; - RunnableTraceable = class extends Runnable { - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (!isTraceableFunction(fields.func)) { - throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); - } - this.func = fields.func; - } - async invoke(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config); - const promise = this.func(patchConfig(config, { callbacks }), input); - return raceWithSignal(promise, config?.signal); - } - async *_streamIterator(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (isAsyncIterable(result)) { - for await (const item of result) { - config?.signal?.throwIfAborted(); - yield item; - } - return; - } - if (isIterator(result)) { - while (true) { - config?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) - break; - yield state.value; - } - return; - } - yield result; - } - static from(func) { - return new RunnableTraceable({ func }); - } - }; - RunnableLambda = class extends Runnable { - static lc_name() { - return "RunnableLambda"; - } - constructor(fields) { - if (isTraceableFunction(fields.func)) { - return RunnableTraceable.from(fields.func); - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new RunnableLambda({ - func - }); - } - async _invoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { - ...childConfig - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); - } - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - } else if (isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) { - finalOutput = chunk; - } else { - try { - finalOutput = concat(finalOutput, chunk); - } catch (e3) { - finalOutput = chunk; - } - } - } - output = finalOutput; - } else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) { - finalOutput = chunk; - } else { - try { - finalOutput = concat(finalOutput, chunk); - } catch (e3) { - finalOutput = chunk; - } - } - } - output = finalOutput; - } - resolve(output); - } catch (e3) { - reject(e3); - } - }); - }); - } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); - } - async *_transform(generator, runManager, config) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === void 0) { - finalChunk = chunk; - } else { - try { - finalChunk = concat(finalChunk, chunk); - } catch (e3) { - finalChunk = chunk; - } - } - } - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - const output = await new Promise((resolve, reject) => { - void AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - const res = await this.func(finalChunk, { - ...childConfig, - config: childConfig - }); - resolve(res); - } catch (e3) { - reject(e3); - } - }); - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); - } - const stream = await output.stream(finalChunk, childConfig); - for await (const chunk of stream) { - yield chunk; - } - } else if (isAsyncIterable(output)) { - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - } else if (isIterableIterator(output)) { - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - } else { - yield output; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - }; - RunnableWithFallbacks = class extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "runnable", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fallbacks", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; - } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) { - yield fallback; - } - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild() - }); - const res = await AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - return output; - } catch (e3) { - if (firstError === void 0) { - firstError = e3; - } - } - } - if (firstError === void 0) { - throw new Error("No error stored at end of fallback."); - } - await runManager?.handleChainError(firstError); - throw firstError; - }); - return res; - } - async *_streamIterator(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - let firstError; - let stream; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild() - }); - try { - const originalStream = await runnable.stream(input, childConfig); - stream = consumeAsyncIterableInContext(childConfig, originalStream); - break; - } catch (e3) { - if (firstError === void 0) { - firstError = e3; - } - } - } - if (stream === void 0) { - const error = firstError ?? new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error); - throw error; - } - let output; - try { - for await (const chunk of stream) { - yield chunk; - try { - output = output === void 0 ? output : concat(output, chunk); - } catch (e3) { - output = void 0; - } - } - } catch (e3) { - await runManager?.handleChainError(e3); - throw e3; - } - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) { - throw new Error("Not implemented."); - } - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i3) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i3], "input"), configList[i3].runId, void 0, void 0, void 0, configList[i3].runName); - delete configList[i3].runId; - return handleStartRes; - })); - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j3) => patchConfig(configList[j3], { - callbacks: runManager?.getChild() - })), batchOptions); - await Promise.all(runManagers.map((runManager, i3) => runManager?.handleChainEnd(_coerceToDict2(outputs[i3], "output")))); - return outputs; - } catch (e3) { - if (firstError === void 0) { - firstError = e3; - } - } - } - if (!firstError) { - throw new Error("No error stored at end of fallbacks."); - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; - } - }; - RunnableAssign = class extends Runnable { - static lc_name() { - return "RunnableAssign"; - } - constructor(fields) { - if (fields instanceof RunnableMap) { - fields = { mapper: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "mapper", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult - }; - } - async *_transform(generator, runManager, options) { - const mapperKeys = this.mapper.getStepsKeys(); - const [forPassthrough, forMapper] = atee(generator); - const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); - const firstMapperChunkPromise = mapperOutput.next(); - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) { - throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); - } - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) { - yield filtered; - } - } - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) { - yield chunk; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - }; - RunnablePick = class extends Runnable { - static lc_name() { - return "RunnablePick"; - } - constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) { - fields = { keys: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "keys", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") { - return input[this.keys]; - } else { - const picked = this.keys.map((key) => [key, input[key]]).filter((v5) => v5[1] !== void 0); - return picked.length === 0 ? void 0 : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async *_transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== void 0) { - yield picked; - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - }; - RunnableToolLike = class extends RunnableBinding { - constructor(fields) { - const sequence = RunnableSequence.from([ - RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) { - try { - toolInput = await this.schema.parseAsync(input.args); - } catch (e3) { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - } else { - toolInput = input; - } - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), - fields.bound - ]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {} - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "description", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "schema", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - static lc_name() { - return "RunnableToolLike"; - } - }; - } -}); - -// node_modules/@langchain/core/dist/runnables/passthrough.js -var RunnablePassthrough; -var init_passthrough = __esm({ - "node_modules/@langchain/core/dist/runnables/passthrough.js"() { - init_stream(); - init_base4(); - init_config(); - RunnablePassthrough = class extends Runnable { - static lc_name() { - return "RunnablePassthrough"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (fields) { - this.func = fields.func; - } - } - async invoke(input, options) { - const config = ensureConfig(options); - if (this.func) { - await this.func(input, config); - } - return this._callWithConfig((input2) => Promise.resolve(input2), input, config); - } - async *transform(generator, options) { - const config = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === void 0) { - finalOutput = chunk; - } else { - try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } - } - if (this.func && finalOutput !== void 0) { - await this.func(finalOutput, config); - } - } - /** - * A runnable that assigns key-value pairs to the input. - * - * The example below shows how you could use it with an inline function. - * - * @example - * ```typescript - * const prompt = - * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} - * Question: {question} - * SQL Query:`); - * - * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` - * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. - * // In this case, we're passing the schema. - * const sqlQueryGeneratorChain = RunnableSequence.from([ - * RunnablePassthrough.assign({ - * schema: async () => db.getTableInfo(), - * }), - * prompt, - * new ChatOpenAI({}).bind({ stop: ["\nSQLResult:"] }), - * new StringOutputParser(), - * ]); - * const result = await sqlQueryGeneratorChain.invoke({ - * question: "How many employees are there?", - * }); - * ``` - */ - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); - } - }; - } -}); - -// node_modules/@langchain/core/dist/runnables/router.js -var init_router = __esm({ - "node_modules/@langchain/core/dist/runnables/router.js"() { - init_base4(); - init_config(); - } -}); - -// node_modules/@langchain/core/dist/runnables/branch.js -var init_branch = __esm({ - "node_modules/@langchain/core/dist/runnables/branch.js"() { - init_base4(); - init_config(); - init_stream(); - } -}); - -// node_modules/@langchain/core/dist/messages/modifier.js -var init_modifier = __esm({ - "node_modules/@langchain/core/dist/messages/modifier.js"() { - init_base3(); - } -}); - -// node_modules/@langchain/core/dist/messages/transformers.js -var init_transformers = __esm({ - "node_modules/@langchain/core/dist/messages/transformers.js"() { - init_base4(); - init_ai(); - init_base3(); - init_chat(); - init_function(); - init_human(); - init_modifier(); - init_system(); - init_tool(); - init_utils2(); - } -}); - -// node_modules/@langchain/core/dist/messages/index.js -var init_messages2 = __esm({ - "node_modules/@langchain/core/dist/messages/index.js"() { - init_ai(); - init_base3(); - init_chat(); - init_function(); - init_human(); - init_system(); - init_utils2(); - init_transformers(); - init_modifier(); - init_tool(); - } -}); - -// node_modules/@langchain/core/dist/runnables/history.js -var init_history = __esm({ - "node_modules/@langchain/core/dist/runnables/history.js"() { - init_messages2(); - init_base4(); - init_passthrough(); - } -}); - -// node_modules/@langchain/core/dist/runnables/index.js -var init_runnables = __esm({ - "node_modules/@langchain/core/dist/runnables/index.js"() { - init_base4(); - init_config(); - init_passthrough(); - init_router(); - init_branch(); - init_history(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/base.js -var BaseLLMOutputParser, BaseOutputParser, OutputParserException; -var init_base5 = __esm({ - "node_modules/@langchain/core/dist/output_parsers/base.js"() { - init_runnables(); - init_errors(); - BaseLLMOutputParser = class extends Runnable { - /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); - } - /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. - */ - async invoke(input, options) { - if (typeof input === "string") { - return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { ...options, runType: "parser" }); - } else { - return this._callWithConfig(async (input2, options2) => this.parseResult([ - { - message: input2, - text: this._baseMessageToString(input2) - } - ], options2?.callbacks), input, { ...options, runType: "parser" }); - } - } - }; - BaseOutputParser = class extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - /** - * Return the string type key uniquely identifying this class of parser - */ - _type() { - throw new Error("_type not implemented"); - } - }; - OutputParserException = class extends Error { - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - Object.defineProperty(this, "llmOutput", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "observation", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "sendToLLM", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === void 0 || llmOutput === void 0) { - throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); - } - }; - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deepCompareStrict(a3, b3) { - const typeofa = typeof a3; - if (typeofa !== typeof b3) { - return false; - } - if (Array.isArray(a3)) { - if (!Array.isArray(b3)) { - return false; - } - const length = a3.length; - if (length !== b3.length) { - return false; - } - for (let i3 = 0; i3 < length; i3++) { - if (!deepCompareStrict(a3[i3], b3[i3])) { - return false; - } - } - return true; - } - if (typeofa === "object") { - if (!a3 || !b3) { - return a3 === b3; - } - const aKeys = Object.keys(a3); - const bKeys = Object.keys(b3); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; - } - for (const k3 of aKeys) { - if (!deepCompareStrict(a3[k3], b3[k3])) { - return false; - } - } - return true; - } - return a3 === b3; -} -var init_deep_compare_strict = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js"() { - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/pointer.js -var init_pointer = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/pointer.js"() { - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/dereference.js -var initialBaseURI; -var init_dereference = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/dereference.js"() { - init_pointer(); - initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/format.js -function bind(r4) { - return r4.test.bind(r4); -} -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function date(str2) { - const matches = str2.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); -} -function time(full, str2) { - const matches = str2.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second2 = +matches[3]; - const timeZone = !!matches[5]; - return (hour <= 23 && minute <= 59 && second2 <= 59 || hour == 23 && minute == 59 && second2 == 60) && (!full || timeZone); -} -function date_time(str2) { - const dateTime = str2.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); -} -function uri(str2) { - return NOT_URI_FRAGMENT.test(str2) && URI_PATTERN.test(str2); -} -function regex(str2) { - if (Z_ANCHOR.test(str2)) - return false; - try { - new RegExp(str2, "u"); - return true; - } catch (e3) { - return false; - } -} -var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, FASTDATE, FASTTIME, FASTDATETIME, FASTURIREFERENCE, EMAIL, IPV4, IPV6, DURATION, fullFormat, fastFormat, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR; -var init_format = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/format.js"() { - DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; - HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; - URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; - URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; - UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; - JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; - JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; - RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; - FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; - FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; - FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; - FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; - EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split("@"); - if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) - return false; - if (name[0] === "." || name.endsWith(".") || name.includes("..")) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); - }; - IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; - IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; - DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)); - fullFormat = { - date, - time: time.bind(void 0, false), - "date-time": date_time, - duration: DURATION, - uri, - "uri-reference": bind(URIREF), - "uri-template": bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex, - uuid: bind(UUID), - "json-pointer": bind(JSON_POINTER), - "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), - "relative-json-pointer": bind(RELATIVE_JSON_POINTER) - }; - fastFormat = { - ...fullFormat, - date: bind(FASTDATE), - time: bind(FASTTIME), - "date-time": bind(FASTDATETIME), - "uri-reference": bind(FASTURIREFERENCE) - }; - DATE_TIME_SEPARATOR = /t|\s/i; - NOT_URI_FRAGMENT = /\/|:/; - URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - Z_ANCHOR = /[^\\]\\Z/; - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -var init_types = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/types.js"() { - (function(OutputFormat2) { - OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag"; - OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic"; - OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed"; - })(OutputFormat || (OutputFormat = {})); - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js -var init_ucs2_length = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js"() { - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/validate.js -var init_validate3 = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/validate.js"() { - init_deep_compare_strict(); - init_dereference(); - init_format(); - init_pointer(); - init_ucs2_length(); - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/validator.js -var init_validator = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/validator.js"() { - init_dereference(); - init_validate3(); - } -}); - -// node_modules/@cfworker/json-schema/dist/esm/index.js -var init_esm2 = __esm({ - "node_modules/@cfworker/json-schema/dist/esm/index.js"() { - init_deep_compare_strict(); - init_dereference(); - init_format(); - init_pointer(); - init_types(); - init_ucs2_length(); - init_validate3(); - init_validator(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/transform.js -var BaseTransformOutputParser, BaseCumulativeTransformOutputParser; -var init_transform = __esm({ - "node_modules/@langchain/core/dist/output_parsers/transform.js"() { - init_esm2(); - init_base5(); - init_base3(); - init_utils2(); - init_outputs(); - BaseTransformOutputParser = class extends BaseOutputParser { - async *_transform(inputGenerator) { - for await (const chunk of inputGenerator) { - if (typeof chunk === "string") { - yield this.parseResult([{ text: chunk }]); - } else { - yield this.parseResult([ - { - message: chunk, - text: this._baseMessageToString(chunk) - } - ]); - } - } - } - /** - * Transforms an asynchronous generator of input into an asynchronous - * generator of parsed output. - * @param inputGenerator An asynchronous generator of input. - * @param options A configuration object. - * @returns An asynchronous generator of parsed output. - */ - async *transform(inputGenerator, options) { - yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { - ...options, - runType: "parser" - }); - } - }; - BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { - constructor(fields) { - super(fields); - Object.defineProperty(this, "diff", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - this.diff = fields?.diff ?? this.diff; - } - async *_transform(inputGenerator) { - let prevParsed; - let accGen; - for await (const chunk of inputGenerator) { - if (typeof chunk !== "string" && typeof chunk.content !== "string") { - throw new Error("Cannot handle non-string output."); - } - let chunkGen; - if (isBaseMessageChunk(chunk)) { - if (typeof chunk.content !== "string") { - throw new Error("Cannot handle non-string message output."); - } - chunkGen = new ChatGenerationChunk({ - message: chunk, - text: chunk.content - }); - } else if (isBaseMessage(chunk)) { - if (typeof chunk.content !== "string") { - throw new Error("Cannot handle non-string message output."); - } - chunkGen = new ChatGenerationChunk({ - message: convertToChunk(chunk), - text: chunk.content - }); - } else { - chunkGen = new GenerationChunk({ text: chunk }); - } - if (accGen === void 0) { - accGen = chunkGen; - } else { - accGen = accGen.concat(chunkGen); - } - const parsed = await this.parsePartialResult([accGen]); - if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { - if (this.diff) { - yield this._diff(prevParsed, parsed); - } else { - yield parsed; - } - prevParsed = parsed; - } - } - } - getFormatInstructions() { - return ""; - } - }; - } -}); - -// node_modules/@langchain/core/dist/output_parsers/bytes.js -var init_bytes = __esm({ - "node_modules/@langchain/core/dist/output_parsers/bytes.js"() { - init_transform(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/list.js -var init_list = __esm({ - "node_modules/@langchain/core/dist/output_parsers/list.js"() { - init_base5(); - init_transform(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/string.js -var StringOutputParser; -var init_string2 = __esm({ - "node_modules/@langchain/core/dist/output_parsers/string.js"() { - init_transform(); - StringOutputParser = class extends BaseTransformOutputParser { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "output_parsers", "string"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - static lc_name() { - return "StrOutputParser"; - } - /** - * Parses a string output from an LLM call. This method is meant to be - * implemented by subclasses to define how a string output from an LLM - * should be parsed. - * @param text The string output from an LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parse(text) { - return Promise.resolve(text); - } - getFormatInstructions() { - return ""; - } - _textContentToString(content) { - return content.text; - } - _imageUrlContentToString(_content) { - throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); - } - _messageContentComplexToString(content) { - switch (content.type) { - case "text": - case "text_delta": - if ("text" in content) { - return this._textContentToString(content); - } - break; - case "image_url": - if ("image_url" in content) { - return this._imageUrlContentToString(content); - } - break; - default: - throw new Error(`Cannot coerce "${content.type}" message part into a string.`); - } - throw new Error(`Invalid content type: ${content.type}`); - } - _baseMessageContentToString(content) { - return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), ""); - } - }; - } -}); - -// node_modules/@langchain/core/dist/output_parsers/structured.js -var StructuredOutputParser; -var init_structured = __esm({ - "node_modules/@langchain/core/dist/output_parsers/structured.js"() { - init_lib(); - init_esm(); - init_base5(); - StructuredOutputParser = class extends BaseOutputParser { - static lc_name() { - return "StructuredOutputParser"; - } - toJSON() { - return this.toJSONNotImplemented(); - } - constructor(schema) { - super(schema); - Object.defineProperty(this, "schema", { - enumerable: true, - configurable: true, - writable: true, - value: schema - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "output_parsers", "structured"] - }); - } - /** - * Creates a new StructuredOutputParser from a Zod schema. - * @param schema The Zod schema which the output should match - * @returns A new instance of StructuredOutputParser. - */ - static fromZodSchema(schema) { - return new this(schema); - } - /** - * Creates a new StructuredOutputParser from a set of names and - * descriptions. - * @param schemas An object where each key is a name and each value is a description - * @returns A new instance of StructuredOutputParser. - */ - static fromNamesAndDescriptions(schemas) { - const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)]))); - return new this(zodSchema); - } - /** - * Returns a markdown code snippet with a JSON object formatted according - * to the schema. - * @param options Optional. The options for formatting the instructions - * @returns A markdown code snippet with a JSON object formatted according to the schema. - */ - getFormatInstructions() { - return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. +`)),n.close()}});return Nc.fromReadableStream(r)}var xFe=C(()=>{iy()});function Sue(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}function DV(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*xue(e,t){for(;;){let{value:r,done:n}=jc.runWithConfig(Xf(e),t.next.bind(t),!0);if(n)break;yield r}}async function*jV(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jc.runWithConfig(Xf(e),r.next.bind(t),!0);if(o)break;yield n}}var CFe,OFe=C(()=>{LD();ny();CFe=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function"});function ku(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function tWt(e){if(nV(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function CS(e){if(typeof e=="function")return new ES({func:e});if(nn.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=CS(n);return new vO({steps:t})}else throw new Error(`Expected a Runnable, function or object. +Instead got an unsupported type.`)}function rWt(e,t){let r=t.name??e.getName(),n=t.description??t.schema?.description;return t.schema.constructor===Er.ZodString?new Q$({name:r,description:n,schema:Er.object({input:Er.string()}).transform(o=>o.input),bound:e}):new Q$({name:r,description:n,schema:t.schema,bound:e})}var Cue,nn,OS,NV,LV,Ha,vO,Oue,ES,FV,BD,kV,Q$,sf=C(()=>{bd();Cue=B(C6(),1);O$();hse();DLe();NLe();NM();iy();$se();ny();kD();FLe();Use();LD();wFe();xFe();OFe();fV();nn=class extends tf{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(t){let r=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${r}${t}`:r}bind(t){return new OS({bound:this,kwargs:t,config:{}})}map(){return new NV({bound:this})}withRetry(t){return new LV({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new OS({bound:this,config:t,kwargs:{}})}withFallbacks(t){let r=Array.isArray(t)?t:t.fallbacks;return new FV({runnable:this,fallbacks:r})}_getOptionsList(t,r=0){if(Array.isArray(t)&&t.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${r} inputs`);if(Array.isArray(t))return t.map(Rr);if(r>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(t).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>Rr(i===0?t:n))}return Array.from({length:r},()=>Rr(t))}async batch(t,r,n){let o=this._getOptionsList(r??{},t.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new Qf({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=t.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(t,r){yield this.invoke(t,r)}async stream(t,r){let n=Rr(r),o=new xS({generator:this._streamIterator(t,n),config:n});return await o.setup,Nc.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(t){let r;t===void 0?r=Rr(t):r=Rr({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});let n={...t};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(t,r,n){let o=Rr(n),a=await(await af(o))?.handleChainStart(this.toJSON(),ku(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=t.call(this,r,o,a);s=await oy(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ku(s,"output")),s}async _batchWithConfig(t,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(af)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),ku(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=t.call(this,r,i,s,o);u=await oy(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(ku(u,"output")))),u}async*_transformStreamWithConfig(t,r,n){let o,i=!0,a,s=!0,u=Rr(n),l=await af(u);async function*c(){for await(let f of t){if(i)if(o===void 0)o=f;else try{o=al(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await MLe(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(jLe),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let m=d?.handlers.find(RLe);m!==void 0&&d!==void 0&&(h=m.tapOutputIterable(d.runId,h));for await(let _ of h)if(yield _,s)if(a===void 0)a=_;else try{a=al(a,_)}catch{a=void 0,s=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:ku(o,"input")}),f}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:ku(o,"input")})}getGraph(t){let r=new X$,n=r.addNode({name:`${this.getName()}Input`,schema:Er.any()}),o=r.addNode(this),i=r.addNode({name:`${this.getName()}Output`,schema:Er.any()});return r.addEdge(n,o),r.addEdge(o,i),r}pipe(t){return new Ha({first:this,last:CS(t)})}pick(t){return this.pipe(new kV(t))}assign(t){return this.pipe(new BD(new vO({steps:t})))}async*transform(t,r){let n;for await(let o of t)n===void 0?n=o:n=al(n,o);yield*this._streamIterator(n,Rr(r))}async*streamLog(t,r,n){let o=new J$({...n,autoClose:!1,_schemaFormat:"original"}),i=Rr(r);yield*this._streamLog(t,o,i)}async*_streamLog(t,r,n){let{callbacks:o}=n;if(o===void 0)n.callbacks=[r];else if(Array.isArray(o))n.callbacks=o.concat([r]);else{let u=o.copy();u.addHandler(r,!0),n.callbacks=u}let i=this.stream(t,n);async function a(){try{let u=await i;for await(let l of u){let c=new Lm({ops:[{op:"add",path:"/streamed_output/-",value:l}]});await r.writer.write(c)}}finally{await r.writer.close()}}let s=a();try{for await(let u of r)yield u}finally{await s}}streamEvents(t,r,n){let o;if(r.version==="v1")o=this._streamEventsV1(t,r,n);else if(r.version==="v2")o=this._streamEventsV2(t,r,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return r.encoding==="text/event-stream"?SFe(o):Nc.fromAsyncGenerator(o)}async*_streamEventsV2(t,r,n){let o=new SV({...n,autoClose:!1}),i=Rr(r),a=i.runId??Xd();i.runId=a;let s=i.callbacks;if(s===void 0)i.callbacks=[o];else if(Array.isArray(s))i.callbacks=s.concat(o);else{let h=s.copy();h.addHandler(o,!0),i.callbacks=h}let u=new AbortController,l=this;async function c(){try{let h;r?.signal?"any"in AbortSignal?h=AbortSignal.any([u.signal,r.signal]):(h=r.signal,r.signal.addEventListener("abort",()=>{u.abort()},{once:!0})):h=u.signal;let m=await l.stream(t,{...i,signal:h}),_=o.tapOutputIterable(a,m);for await(let g of _)if(u.signal.aborted)break}finally{await o.finish()}}let d=c(),f=!1,p;try{for await(let h of o){if(!f){h.data.input=t,f=!0,p=h.run_id,yield h;continue}h.run_id===p&&h.event.endsWith("_end")&&h.data?.input&&delete h.data.input,yield h}}finally{u.abort(),await d}}async*_streamEventsV1(t,r,n){let o,i=!1,a=Rr(r),s=a.tags??[],u=a.metadata??{},l=a.runName??this.getName(),c=new J$({...n,autoClose:!1,_schemaFormat:"streaming_events"}),d=new CV({...n}),f=this._streamLog(t,c,a);for await(let h of f){if(o?o=o.concat(h):o=W$.fromRunLogPatch(h),o.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let v={...o.state},S={run_id:v.id,event:`on_${v.type}_start`,name:l,tags:s,metadata:u,data:{input:t}};d.includeEvent(S,v.type)&&(yield S)}let m=h.ops.filter(v=>v.path.startsWith("/logs/")).map(v=>v.path.split("/")[2]),_=[...new Set(m)];for(let v of _){let S,x={},O=o.state.logs[v];if(O.end_time===void 0?O.streamed_output.length>0?S="stream":S="start":S="end",S==="start")O.inputs!==void 0&&(x.input=O.inputs);else if(S==="end")O.inputs!==void 0&&(x.input=O.inputs),x.output=O.final_output;else if(S==="stream"){let T=O.streamed_output.length;if(T!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${T} instead. Encountered in: "${O.name}"`);x={chunk:O.streamed_output[0]},O.streamed_output=[]}yield{event:`on_${O.type}_${S}`,name:O.name,run_id:O.id,tags:O.tags,metadata:O.metadata,data:x}}let{state:g}=o;if(g.streamed_output.length>0){let v=g.streamed_output.length;if(v!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${v} instead. Encountered in: "${g.name}"`);let S={chunk:g.streamed_output[0]};g.streamed_output=[];let x={event:`on_${g.type}_stream`,run_id:g.id,tags:s,metadata:u,name:l,data:S};d.includeEvent(x,g.type)&&(yield x)}}let p=o?.state;if(p!==void 0){let h={event:`on_${p.type}_end`,name:l,run_id:p.id,tags:s,metadata:u,data:{output:p.final_output}};d.includeEvent(h,p.type)&&(yield h)}}static isRunnable(t){return Y$(t)}withListeners({onStart:t,onEnd:r,onError:n}){return new OS({bound:this,config:{},configFactories:[o=>({callbacks:[new K$({config:o,onStart:t,onEnd:r,onError:n})]})]})}asTool(t){return rWt(this,t)}},OS=class e extends nn{static lc_name(){return"RunnableBinding"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){let r=vV(this.config,...t);return vV(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}bind(t){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...t},config:this.config})}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new this.constructor({bound:this.bound.withRetry(t),kwargs:this.kwargs,config:this.config})}async invoke(t,r){return this.bound.invoke(t,await this._mergeConfig(Rr(r),this.kwargs))}async batch(t,r,n){let o=Array.isArray(r)?await Promise.all(r.map(async i=>this._mergeConfig(Rr(i),this.kwargs))):await this._mergeConfig(Rr(r),this.kwargs);return this.bound.batch(t,o,n)}async*_streamIterator(t,r){yield*this.bound._streamIterator(t,await this._mergeConfig(Rr(r),this.kwargs))}async stream(t,r){return this.bound.stream(t,await this._mergeConfig(Rr(r),this.kwargs))}async*transform(t,r){yield*this.bound.transform(t,await this._mergeConfig(Rr(r),this.kwargs))}streamEvents(t,r,n){let o=this,i=async function*(){yield*o.bound.streamEvents(t,{...await o._mergeConfig(Rr(r),o.kwargs),version:r.version},n)};return Nc.fromAsyncGenerator(i())}static isRunnableBinding(t){return t.bound&&nn.isRunnable(t.bound)}withListeners({onStart:t,onEnd:r,onError:n}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[o=>({callbacks:[new K$({config:o,onStart:t,onEnd:r,onError:n})]})]})}},NV=class e extends nn{static lc_name(){return"RunnableEach"}constructor(t){super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=t.bound}bind(t){return new e({bound:this.bound.bind(t)})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _invoke(t,r,n){return this.bound.batch(t,Ta(r,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:r,onError:n}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:r,onError:n})})}},LV=class extends OS{static lc_name(){return"RunnableRetry"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,r,n){let o=t>1?`retry:attempt:${t}`:void 0;return Ta(r,{callbacks:n?.getChild(o)})}async _invoke(t,r,n){return(0,Cue.default)(o=>super.invoke(t,this._patchConfigForRetry(o,r,n)),{onFailedAttempt:o=>this.onFailedAttempt(o,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async _batch(t,r,n,o){let i={};try{await(0,Cue.default)(async a=>{let s=t.map((f,p)=>p).filter(f=>i[f.toString()]===void 0||i[f.toString()]instanceof Error),u=s.map(f=>t[f]),l=s.map(f=>this._patchConfigForRetry(a,r?.[f],n?.[f])),c=await super.batch(u,l,{...o,returnExceptions:!0}),d;for(let f=0;fthis.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if(o?.returnExceptions!==!0)throw a}return Object.keys(i).sort((a,s)=>parseInt(a,10)-parseInt(s,10)).map(a=>i[parseInt(a,10)])}async batch(t,r,n){return this._batchWithConfig(this._batch.bind(this),t,r,n)}},Ha=class e extends nn{static lc_name(){return"RunnableSequence"}constructor(t){super(t),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,r){let n=Rr(r),i=await(await af(n))?.handleChainStart(this.toJSON(),ku(t,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a=t,s;try{let u=[this.first,...this.middle];for(let l=0;l{let c=await u?.handleChainStart(this.toJSON(),ku(t[l],"input"),o[l].runId,void 0,void 0,void 0,o[l].runName);return delete o[l].runId,c})),s=t;try{for(let u=0;u{let p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return Ta(o[f],{callbacks:p})}),n);s=await oy(c,o[0]?.signal)}}catch(u){throw await Promise.all(a.map(l=>l?.handleChainError(u))),u}return await Promise.all(a.map(u=>u?.handleChainEnd(ku(s,"output")))),s}async*_streamIterator(t,r){let n=await af(r),{runId:o,...i}=r??{},a=await n?.handleChainStart(this.toJSON(),ku(t,"input"),o,void 0,void 0,void 0,i?.runName),s=[this.first,...this.middle,this.last],u=!0,l;async function*c(){yield t}try{let d=s[0].transform(c(),Ta(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f{let a=o.getGraph(t);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),r.extend(a);let s=a.firstNode();if(!s)throw new Error(`Runnable ${o} has no first node`);n&&r.addEdge(n,s),n=a.lastNode()}),r}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:CS(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&nn.isRunnable(t)}static from([t,...r],n){let o={};return typeof n=="string"?o.name=n:n!==void 0&&(o=n),new e({...o,first:CS(t),middle:r.slice(0,-1).map(CS),last:CS(r[r.length-1])})}},vO=class e extends nn{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(let[r,n]of Object.entries(t.steps))this.steps[r]=CS(n)}static from(t){return new e({steps:t})}async invoke(t,r){let n=Rr(r),i=await(await af(n))?.handleChainStart(this.toJSON(),{input:t},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let a={};try{let s=Object.entries(this.steps).map(async([u,l])=>{a[u]=await l.invoke(t,Ta(n,{callbacks:i?.getChild(`map:key:${u}`)}))});await oy(Promise.all(s),r?.signal)}catch(s){throw await i?.handleChainError(s),s}return await i?.handleChainEnd(a),a}async*_transform(t,r,n){let o={...this.steps},i=qse(t,Object.keys(o).length),a=new Map(Object.entries(o).map(([s,u],l)=>{let c=u.transform(i[l],Ta(n,{callbacks:r?.getChild(`map:key:${s}`)}));return[s,c.next().then(d=>({key:s,gen:c,result:d}))]}));for(;a.size;){let s=Promise.race(a.values()),{key:u,result:l,gen:c}=await oy(s,n?.signal);a.delete(u),l.done||(yield{[u]:l.value},a.set(u,c.next().then(d=>({key:u,gen:c,result:d}))))}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let o=Rr(r),i=new xS({generator:this.transform(n(),o),config:o});return await i.setup,Nc.fromAsyncGenerator(i)}},Oue=class e extends nn{constructor(t){if(super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!nV(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,r){let[n]=this._getOptionsList(r??{},1),o=await af(n),i=this.func(Ta(n,{callbacks:o}),t);return oy(i,n?.signal)}async*_streamIterator(t,r){let[n]=this._getOptionsList(r??{},1),o=await this.invoke(t,r);if(DV(o)){for await(let i of o)n?.signal?.throwIfAborted(),yield i;return}if(CFe(o)){for(;;){n?.signal?.throwIfAborted();let i=o.next();if(i.done)break;yield i.value}return}yield o}static from(t){return new e({func:t})}};ES=class e extends nn{static lc_name(){return"RunnableLambda"}constructor(t){if(nV(t.func))return Oue.from(t.func);super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),tWt(t.func),this.func=t.func}static from(t){return new e({func:t})}async _invoke(t,r,n){return new Promise((o,i)=>{let a=Ta(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??_V)-1});jc.runWithConfig(Xf(a),async()=>{try{let s=await this.func(t,{...a});if(s&&nn.isRunnable(s)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");s=await s.invoke(t,{...a,recursionLimit:(a.recursionLimit??_V)-1})}else if(DV(s)){let u;for await(let l of jV(a,s))if(r?.signal?.throwIfAborted(),u===void 0)u=l;else try{u=al(u,l)}catch{u=l}s=u}else if(Sue(s)){let u;for(let l of xue(a,s))if(r?.signal?.throwIfAborted(),u===void 0)u=l;else try{u=al(u,l)}catch{u=l}s=u}o(s)}catch(s){i(s)}})})}async invoke(t,r){return this._callWithConfig(this._invoke.bind(this),t,r)}async*_transform(t,r,n){let o;for await(let s of t)if(o===void 0)o=s;else try{o=al(o,s)}catch{o=s}let i=Ta(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??_V)-1}),a=await new Promise((s,u)=>{jc.runWithConfig(Xf(i),async()=>{try{let l=await this.func(o,{...i,config:i});s(l)}catch(l){u(l)}})});if(a&&nn.isRunnable(a)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");let s=await a.stream(o,i);for await(let u of s)yield u}else if(DV(a))for await(let s of jV(i,a))n?.signal?.throwIfAborted(),yield s;else if(Sue(a))for(let s of xue(i,a))n?.signal?.throwIfAborted(),yield s;else yield a}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let o=Rr(r),i=new xS({generator:this.transform(n(),o),config:o});return await i.setup,Nc.fromAsyncGenerator(i)}},FV=class extends nn{static lc_name(){return"RunnableWithFallbacks"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(let t of this.fallbacks)yield t}async invoke(t,r){let n=Rr(r),o=await af(n),{runId:i,...a}=n,s=await o?.handleChainStart(this.toJSON(),ku(t,"input"),i,void 0,void 0,void 0,a?.runName),u=Ta(a,{callbacks:s?.getChild()});return await jc.runWithConfig(u,async()=>{let c;for(let d of this.runnables()){n?.signal?.throwIfAborted();try{let f=await d.invoke(t,u);return await s?.handleChainEnd(ku(f,"output")),f}catch(f){c===void 0&&(c=f)}}throw c===void 0?new Error("No error stored at end of fallback."):(await s?.handleChainError(c),c)})}async*_streamIterator(t,r){let n=Rr(r),o=await af(n),{runId:i,...a}=n,s=await o?.handleChainStart(this.toJSON(),ku(t,"input"),i,void 0,void 0,void 0,a?.runName),u,l;for(let d of this.runnables()){n?.signal?.throwIfAborted();let f=Ta(a,{callbacks:s?.getChild()});try{let p=await d.stream(t,f);l=jV(f,p);break}catch(p){u===void 0&&(u=p)}}if(l===void 0){let d=u??new Error("No error stored at end of fallback.");throw await s?.handleChainError(d),d}let c;try{for await(let d of l){yield d;try{c=c===void 0?c:al(c,d)}catch{c=void 0}}}catch(d){throw await s?.handleChainError(d),d}await s?.handleChainEnd(ku(c,"output"))}async batch(t,r,n){if(n?.returnExceptions)throw new Error("Not implemented.");let o=this._getOptionsList(r??{},t.length),i=await Promise.all(o.map(u=>af(u))),a=await Promise.all(i.map(async(u,l)=>{let c=await u?.handleChainStart(this.toJSON(),ku(t[l],"input"),o[l].runId,void 0,void 0,void 0,o[l].runName);return delete o[l].runId,c})),s;for(let u of this.runnables()){o[0].signal?.throwIfAborted();try{let l=await u.batch(t,a.map((c,d)=>Ta(o[d],{callbacks:c?.getChild()})),n);return await Promise.all(a.map((c,d)=>c?.handleChainEnd(ku(l[d],"output")))),l}catch(l){s===void 0&&(s=l)}}throw s?(await Promise.all(a.map(u=>u?.handleChainError(s))),s):new Error("No error stored at end of fallbacks.")}};BD=class extends nn{static lc_name(){return"RunnableAssign"}constructor(t){t instanceof vO&&(t={mapper:t}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=t.mapper}async invoke(t,r){let n=await this.mapper.invoke(t,r);return{...t,...n}}async*_transform(t,r,n){let o=this.mapper.getStepsKeys(),[i,a]=qse(t),s=this.mapper.transform(a,Ta(n,{callbacks:r?.getChild()})),u=s.next();for await(let l of i){if(typeof l!="object"||Array.isArray(l))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof l}`);let c=Object.fromEntries(Object.entries(l).filter(([d])=>!o.includes(d)));Object.keys(c).length>0&&(yield c)}yield(await u).value;for await(let l of s)yield l}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let o=Rr(r),i=new xS({generator:this.transform(n(),o),config:o});return await i.setup,Nc.fromAsyncGenerator(i)}},kV=class extends nn{static lc_name(){return"RunnablePick"}constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{let r=this.keys.map(n=>[n,t[n]]).filter(n=>n[1]!==void 0);return r.length===0?void 0:Object.fromEntries(r)}}async invoke(t,r){return this._callWithConfig(this._pick.bind(this),t,r)}async*_transform(t){for await(let r of t){let n=await this._pick(r);n!==void 0&&(yield n)}}transform(t,r){return this._transformStreamWithConfig(t,this._transform.bind(this),r)}async stream(t,r){async function*n(){yield t}let o=Rr(r),i=new xS({generator:this.transform(n(),o),config:o});return await i.setup,Nc.fromAsyncGenerator(i)}},Q$=class extends OS{constructor(t){let r=Ha.from([ES.from(async n=>{let o;if(AD(n))try{o=await this.schema.parseAsync(n.args)}catch{throw new ID("Received tool input did not match expected schema",JSON.stringify(n.args))}else o=n;return o}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:r,config:t.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}}});var Fi,BV=C(()=>{iy();sf();ny();Fi=class extends nn{static lc_name(){return"RunnablePassthrough"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t&&(this.func=t.func)}async invoke(t,r){let n=Rr(r);return this.func&&await this.func(t,n),this._callWithConfig(o=>Promise.resolve(o),t,n)}async*transform(t,r){let n=Rr(r),o,i=!0;for await(let a of this._transformStreamWithConfig(t,s=>s,n))if(yield a,i)if(o===void 0)o=a;else try{o=al(o,a)}catch{o=void 0,i=!1}this.func&&o!==void 0&&await this.func(o,n)}static assign(t){return new BD(new vO({steps:t}))}}});var EFe=C(()=>{sf();ny()});var PFe=C(()=>{sf();ny();iy()});var Eue=C(()=>{rh()});var TFe=C(()=>{sf();BM();rh();pV();hV();U$();Eue();mV();DD();gO()});var UM=C(()=>{BM();rh();pV();hV();U$();mV();gO();TFe();Eue();DD()});var MFe=C(()=>{UM();sf();BV()});var Pue=C(()=>{sf();ny();BV();EFe();PFe();MFe()});var zM,HM,ep,$D=C(()=>{Pue();$$();zM=class extends nn{parseResultWithPrompt(t,r,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,r){return typeof t=="string"?this._callWithConfig(async(n,o)=>this.parseResult([{text:n}],o?.callbacks),t,{...r,runType:"parser"}):this._callWithConfig(async(n,o)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],o?.callbacks),t,{...r,runType:"parser"})}},HM=class extends zM{parseResult(t,r){return this.parse(t[0].text,r)}async parseWithPrompt(t,r,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},ep=class extends Error{constructor(t,r,n,o=!1){if(super(t),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=r,this.observation=n,this.sendToLLM=o,o&&(n===void 0||r===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");hO(this,"OUTPUT_PARSING_FAILURE")}}});function eq(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let o=0;o{});var $V=C(()=>{});var xxn,qV=C(()=>{$V();xxn=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function uf(e){return e.test.bind(e)}function OWt(e){return e%4===0&&(e%100!==0||e%400===0)}function IFe(e){let t=e.match(oWt);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&OWt(r)?29:iWt[n])}function AFe(e,t){let r=t.match(aWt);if(!r)return!1;let n=+r[1],o=+r[2],i=+r[3],a=!!r[5];return(n<=23&&o<=59&&i<=59||n==23&&o==59&&i==60)&&(!e||a)}function PWt(e){let t=e.split(EWt);return t.length==2&&IFe(t[0])&&AFe(!0,t[1])}function IWt(e){return TWt.test(e)&&MWt.test(e)}function RWt(e){if(AWt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var oWt,iWt,aWt,sWt,uWt,lWt,cWt,dWt,fWt,pWt,hWt,mWt,gWt,yWt,bWt,_Wt,vWt,wWt,SWt,xWt,CWt,EWt,TWt,MWt,AWt,Mue=C(()=>{oWt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,iWt=[0,31,28,31,30,31,30,31,31,30,31,30,31],aWt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sWt=/^(?=.{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,uWt=/^(?:[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,lWt=/^(?:(?:[^\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,cWt=/^(?:(?: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,dWt=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,fWt=/^(?:\/(?:[^~/]|~0|~1)*)*$/,pWt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,hWt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,mWt=/^\d\d\d\d-[0-1]\d-[0-3]\d$/,gWt=/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,yWt=/^\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,bWt=/^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,_Wt=e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},vWt=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,wWt=/^((([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,SWt=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));xWt={date:IFe,time:AFe.bind(void 0,!1),"date-time":PWt,duration:SWt,uri:IWt,"uri-reference":uf(uWt),"uri-template":uf(lWt),url:uf(cWt),email:_Wt,hostname:uf(sWt),ipv4:uf(vWt),ipv6:uf(wWt),regex:RWt,uuid:uf(dWt),"json-pointer":uf(fWt),"json-pointer-uri-fragment":uf(pWt),"relative-json-pointer":uf(hWt)},CWt={...xWt,date:uf(mWt),time:uf(gWt),"date-time":uf(yWt),"uri-reference":uf(bWt)};EWt=/t|\s/i;TWt=/\/|:/,MWt=/^(?:[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;AWt=/[^\\]\\Z/});var RFe,DFe=C(()=>{(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(RFe||(RFe={}))});var Iue=C(()=>{});var Aue=C(()=>{Tue();qV();Mue();$V();Iue()});var jFe=C(()=>{qV();Aue()});var NFe=C(()=>{Tue();qV();Mue();$V();DFe();Iue();Aue();jFe()});var VM,WM,wO=C(()=>{NFe();$D();rh();gO();FD();VM=class extends HM{async*_transform(t){for await(let r of t)typeof r=="string"?yield this.parseResult([{text:r}]):yield this.parseResult([{message:r,text:this._baseMessageToString(r)}])}async*transform(t,r){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...r,runType:"parser"})}},WM=class extends VM{constructor(t){super(t),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=t?.diff??this.diff}async*_transform(t){let r,n;for await(let o of t){if(typeof o!="string"&&typeof o.content!="string")throw new Error("Cannot handle non-string output.");let i;if(Pse(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new oi({message:o,text:o.content})}else if(th(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new oi({message:Ise(o),text:o.content})}else i=new nh({text:o});n===void 0?n=i:n=n.concat(i);let a=await this.parsePartialResult([n]);a!=null&&!eq(a,r)&&(this.diff?yield this._diff(r,a):yield a,r=a)}}getFormatInstructions(){return""}}});var LFe=C(()=>{wO()});var FFe=C(()=>{$D();wO()});var UV,kFe=C(()=>{wO();UV=class extends VM{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers","string"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"StrOutputParser"}parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}_textContentToString(t){return t.text}_imageUrlContentToString(t){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentComplexToString(t){switch(t.type){case"text":case"text_delta":if("text"in t)return this._textContentToString(t);break;case"image_url":if("image_url"in t)return this._imageUrlContentToString(t);break;default:throw new Error(`Cannot coerce "${t.type}" message part into a string.`)}throw new Error(`Invalid content type: ${t.type}`)}_baseMessageContentToString(t){return t.reduce((r,n)=>r+this._messageContentComplexToString(n),"")}}});var PS,BFe=C(()=>{bd();oh();$D();PS=class extends HM{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(t){super(t),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){let r=Er.object(Object.fromEntries(Object.entries(t).map(([n,o])=>[n,Er.string().describe(o)])));return new this(r)}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. @@ -21124,95804 +74,107 @@ Your output will be parsed and type-checked according to the provided schema ins Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json -${JSON.stringify(zodToJsonSchema(this.schema))} +${JSON.stringify(Li(this.schema))} \`\`\` -`; - } - /** - * Parses the given text according to the schema. - * @param text The text to parse - * @returns The parsed output. - */ - async parse(text) { - try { - const json = text.includes("```") ? text.trim().split(/```(?:json)?/)[1] : text.trim(); - const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { - const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n"); - return `"${escapedInsideQuotes}"`; - }).replace(/\n/g, ""); - return await this.schema.parseAsync(JSON.parse(escapedJson)); - } catch (e3) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e3}`, text); - } - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/json_patch.js -var init_json_patch = __esm({ - "node_modules/@langchain/core/dist/utils/json_patch.js"() { - init_fast_json_patch(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/json.js -var JsonOutputParser; -var init_json2 = __esm({ - "node_modules/@langchain/core/dist/output_parsers/json.js"() { - init_transform(); - init_json_patch(); - init_json(); - JsonOutputParser = class extends BaseCumulativeTransformOutputParser { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "output_parsers"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - static lc_name() { - return "JsonOutputParser"; - } - _diff(prev, next) { - if (!next) { - return void 0; - } - if (!prev) { - return [{ op: "replace", path: "", value: next }]; - } - return compare(prev, next); - } - // This should actually return Partial, but there's no way - // to specify emitted chunks as instances separate from the main output type. - async parsePartialResult(generations) { - return parseJsonMarkdown(generations[0].text); - } - async parse(text) { - return parseJsonMarkdown(text, JSON.parse); - } - getFormatInstructions() { - return ""; - } - }; - } -}); - -// node_modules/@langchain/core/dist/utils/sax-js/sax.js -var init_sax = __esm({ - "node_modules/@langchain/core/dist/utils/sax-js/sax.js"() { - } -}); - -// node_modules/@langchain/core/dist/output_parsers/xml.js -var init_xml = __esm({ - "node_modules/@langchain/core/dist/output_parsers/xml.js"() { - init_transform(); - init_json_patch(); - init_sax(); - } -}); - -// node_modules/@langchain/core/dist/output_parsers/index.js -var init_output_parsers = __esm({ - "node_modules/@langchain/core/dist/output_parsers/index.js"() { - init_base5(); - init_bytes(); - init_list(); - init_string2(); - init_structured(); - init_transform(); - init_json2(); - init_xml(); - } -}); - -// node_modules/@langchain/core/output_parsers.js -var init_output_parsers2 = __esm({ - "node_modules/@langchain/core/output_parsers.js"() { - init_output_parsers(); - } -}); - -// node_modules/@langchain/core/dist/prompt_values.js -var BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue; -var init_prompt_values = __esm({ - "node_modules/@langchain/core/dist/prompt_values.js"() { - init_serializable(); - init_human(); - init_utils2(); - BasePromptValue = class extends Serializable { - }; - StringPromptValue = class extends BasePromptValue { - static lc_name() { - return "StringPromptValue"; - } - constructor(value) { - super({ value }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompt_values"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "value", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.value = value; - } - toString() { - return this.value; - } - toChatMessages() { - return [new HumanMessage(this.value)]; - } - }; - ChatPromptValue = class extends BasePromptValue { - static lc_name() { - return "ChatPromptValue"; - } - constructor(fields) { - if (Array.isArray(fields)) { - fields = { messages: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompt_values"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "messages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.messages = fields.messages; - } - toString() { - return getBufferString(this.messages); - } - toChatMessages() { - return this.messages; - } - }; - ImagePromptValue = class extends BasePromptValue { - static lc_name() { - return "ImagePromptValue"; - } - constructor(fields) { - if (!("imageUrl" in fields)) { - fields = { imageUrl: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompt_values"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "imageUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "value", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [ - new HumanMessage({ - content: [ - { - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url - } - } - ] - }) - ]; - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/string.js -var BaseStringPromptTemplate; -var init_string3 = __esm({ - "node_modules/@langchain/core/dist/prompts/string.js"() { - init_prompt_values(); - init_base6(); - BaseStringPromptTemplate = class extends BasePromptTemplate { - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new StringPromptValue(formattedPrompt); - } - }; - } -}); - -// node_modules/mustache/mustache.mjs -function isFunction(object) { - return typeof object === "function"; -} -function typeStr(obj) { - return isArray(obj) ? "array" : typeof obj; -} -function escapeRegExp(string) { - return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -} -function hasProperty(obj, propName) { - return obj != null && typeof obj === "object" && propName in obj; -} -function primitiveHasOwnProperty(primitive, propName) { - return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); -} -function testRegExp(re, string) { - return regExpTest.call(re, string); -} -function isWhitespace(string) { - return !testRegExp(nonSpaceRe, string); -} -function escapeHtml(string) { - return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s4) { - return entityMap[s4]; - }); -} -function parseTemplate(template, tags) { - if (!template) - return []; - var lineHasNonSpace = false; - var sections = []; - var tokens = []; - var spaces = []; - var hasTag = false; - var nonSpace = false; - var indentation = ""; - var tagIndex = 0; - function stripSpace() { - if (hasTag && !nonSpace) { - while (spaces.length) - delete tokens[spaces.pop()]; - } else { - spaces = []; - } - hasTag = false; - nonSpace = false; - } - var openingTagRe, closingTagRe, closingCurlyRe; - function compileTags(tagsToCompile) { - if (typeof tagsToCompile === "string") - tagsToCompile = tagsToCompile.split(spaceRe, 2); - if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) - throw new Error("Invalid tags: " + tagsToCompile); - openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); - closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); - closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); - } - compileTags(tags || mustache.tags); - var scanner = new Scanner(template); - var start, type, value, chr, token, openSection; - while (!scanner.eos()) { - start = scanner.pos; - value = scanner.scanUntil(openingTagRe); - if (value) { - for (var i3 = 0, valueLength = value.length; i3 < valueLength; ++i3) { - chr = value.charAt(i3); - if (isWhitespace(chr)) { - spaces.push(tokens.length); - indentation += chr; - } else { - nonSpace = true; - lineHasNonSpace = true; - indentation += " "; - } - tokens.push(["text", chr, start, start + 1]); - start += 1; - if (chr === "\n") { - stripSpace(); - indentation = ""; - tagIndex = 0; - lineHasNonSpace = false; - } - } - } - if (!scanner.scan(openingTagRe)) - break; - hasTag = true; - type = scanner.scan(tagRe) || "name"; - scanner.scan(whiteRe); - if (type === "=") { - value = scanner.scanUntil(equalsRe); - scanner.scan(equalsRe); - scanner.scanUntil(closingTagRe); - } else if (type === "{") { - value = scanner.scanUntil(closingCurlyRe); - scanner.scan(curlyRe); - scanner.scanUntil(closingTagRe); - type = "&"; - } else { - value = scanner.scanUntil(closingTagRe); - } - if (!scanner.scan(closingTagRe)) - throw new Error("Unclosed tag at " + scanner.pos); - if (type == ">") { - token = [type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace]; - } else { - token = [type, value, start, scanner.pos]; - } - tagIndex++; - tokens.push(token); - if (type === "#" || type === "^") { - sections.push(token); - } else if (type === "/") { - openSection = sections.pop(); - if (!openSection) - throw new Error('Unopened section "' + value + '" at ' + start); - if (openSection[1] !== value) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); - } else if (type === "name" || type === "{" || type === "&") { - nonSpace = true; - } else if (type === "=") { - compileTags(value); - } - } - stripSpace(); - openSection = sections.pop(); - if (openSection) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); - return nestTokens(squashTokens(tokens)); -} -function squashTokens(tokens) { - var squashedTokens = []; - var token, lastToken; - for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) { - token = tokens[i3]; - if (token) { - if (token[0] === "text" && lastToken && lastToken[0] === "text") { - lastToken[1] += token[1]; - lastToken[3] = token[3]; - } else { - squashedTokens.push(token); - lastToken = token; - } - } - } - return squashedTokens; -} -function nestTokens(tokens) { - var nestedTokens = []; - var collector = nestedTokens; - var sections = []; - var token, section; - for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) { - token = tokens[i3]; - switch (token[0]) { - case "#": - case "^": - collector.push(token); - sections.push(token); - collector = token[4] = []; - break; - case "/": - section = sections.pop(); - section[5] = token[2]; - collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; - break; - default: - collector.push(token); - } - } - return nestedTokens; -} -function Scanner(string) { - this.string = string; - this.tail = string; - this.pos = 0; -} -function Context(view, parentContext) { - this.view = view; - this.cache = { ".": this.view }; - this.parent = parentContext; -} -function Writer() { - this.templateCache = { - _cache: {}, - set: function set(key, value) { - this._cache[key] = value; - }, - get: function get4(key) { - return this._cache[key]; - }, - clear: function clear() { - this._cache = {}; - } - }; -} -var objectToString, isArray, regExpTest, nonSpaceRe, entityMap, whiteRe, spaceRe, equalsRe, curlyRe, tagRe, mustache, defaultWriter, mustache_default; -var init_mustache = __esm({ - "node_modules/mustache/mustache.mjs"() { - objectToString = Object.prototype.toString; - isArray = Array.isArray || function isArrayPolyfill(object) { - return objectToString.call(object) === "[object Array]"; - }; - regExpTest = RegExp.prototype.test; - nonSpaceRe = /\S/; - entityMap = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "/": "/", - "`": "`", - "=": "=" - }; - whiteRe = /\s*/; - spaceRe = /\s+/; - equalsRe = /\s*=/; - curlyRe = /\s*\}/; - tagRe = /#|\^|\/|>|\{|&|=|!/; - Scanner.prototype.eos = function eos() { - return this.tail === ""; - }; - Scanner.prototype.scan = function scan(re) { - var match2 = this.tail.match(re); - if (!match2 || match2.index !== 0) - return ""; - var string = match2[0]; - this.tail = this.tail.substring(string.length); - this.pos += string.length; - return string; - }; - Scanner.prototype.scanUntil = function scanUntil(re) { - var index2 = this.tail.search(re), match2; - switch (index2) { - case -1: - match2 = this.tail; - this.tail = ""; - break; - case 0: - match2 = ""; - break; - default: - match2 = this.tail.substring(0, index2); - this.tail = this.tail.substring(index2); - } - this.pos += match2.length; - return match2; - }; - Context.prototype.push = function push(view) { - return new Context(view, this); - }; - Context.prototype.lookup = function lookup(name) { - var cache2 = this.cache; - var value; - if (cache2.hasOwnProperty(name)) { - value = cache2[name]; - } else { - var context = this, intermediateValue, names, index2, lookupHit = false; - while (context) { - if (name.indexOf(".") > 0) { - intermediateValue = context.view; - names = name.split("."); - index2 = 0; - while (intermediateValue != null && index2 < names.length) { - if (index2 === names.length - 1) - lookupHit = hasProperty(intermediateValue, names[index2]) || primitiveHasOwnProperty(intermediateValue, names[index2]); - intermediateValue = intermediateValue[names[index2++]]; - } - } else { - intermediateValue = context.view[name]; - lookupHit = hasProperty(context.view, name); - } - if (lookupHit) { - value = intermediateValue; - break; - } - context = context.parent; - } - cache2[name] = value; - } - if (isFunction(value)) - value = value.call(this.view); - return value; - }; - Writer.prototype.clearCache = function clearCache() { - if (typeof this.templateCache !== "undefined") { - this.templateCache.clear(); - } - }; - Writer.prototype.parse = function parse(template, tags) { - var cache2 = this.templateCache; - var cacheKey = template + ":" + (tags || mustache.tags).join(":"); - var isCacheEnabled = typeof cache2 !== "undefined"; - var tokens = isCacheEnabled ? cache2.get(cacheKey) : void 0; - if (tokens == void 0) { - tokens = parseTemplate(template, tags); - isCacheEnabled && cache2.set(cacheKey, tokens); - } - return tokens; - }; - Writer.prototype.render = function render(template, view, partials, config) { - var tags = this.getConfigTags(config); - var tokens = this.parse(template, tags); - var context = view instanceof Context ? view : new Context(view, void 0); - return this.renderTokens(tokens, context, partials, template, config); - }; - Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config) { - var buffer = ""; - var token, symbol, value; - for (var i3 = 0, numTokens = tokens.length; i3 < numTokens; ++i3) { - value = void 0; - token = tokens[i3]; - symbol = token[0]; - if (symbol === "#") - value = this.renderSection(token, context, partials, originalTemplate, config); - else if (symbol === "^") - value = this.renderInverted(token, context, partials, originalTemplate, config); - else if (symbol === ">") - value = this.renderPartial(token, context, partials, config); - else if (symbol === "&") - value = this.unescapedValue(token, context); - else if (symbol === "name") - value = this.escapedValue(token, context, config); - else if (symbol === "text") - value = this.rawValue(token); - if (value !== void 0) - buffer += value; - } - return buffer; - }; - Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config) { - var self2 = this; - var buffer = ""; - var value = context.lookup(token[1]); - function subRender(template) { - return self2.render(template, context, partials, config); - } - if (!value) - return; - if (isArray(value)) { - for (var j3 = 0, valueLength = value.length; j3 < valueLength; ++j3) { - buffer += this.renderTokens(token[4], context.push(value[j3]), partials, originalTemplate, config); - } - } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") { - buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); - } else if (isFunction(value)) { - if (typeof originalTemplate !== "string") - throw new Error("Cannot use higher-order sections without the original template"); - value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); - if (value != null) - buffer += value; - } else { - buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); - } - return buffer; - }; - Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config) { - var value = context.lookup(token[1]); - if (!value || isArray(value) && value.length === 0) - return this.renderTokens(token[4], context, partials, originalTemplate, config); - }; - Writer.prototype.indentPartial = function indentPartial(partial, indentation, lineHasNonSpace) { - var filteredIndentation = indentation.replace(/[^ \t]/g, ""); - var partialByNl = partial.split("\n"); - for (var i3 = 0; i3 < partialByNl.length; i3++) { - if (partialByNl[i3].length && (i3 > 0 || !lineHasNonSpace)) { - partialByNl[i3] = filteredIndentation + partialByNl[i3]; - } - } - return partialByNl.join("\n"); - }; - Writer.prototype.renderPartial = function renderPartial(token, context, partials, config) { - if (!partials) - return; - var tags = this.getConfigTags(config); - var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; - if (value != null) { - var lineHasNonSpace = token[6]; - var tagIndex = token[5]; - var indentation = token[4]; - var indentedValue = value; - if (tagIndex == 0 && indentation) { - indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); - } - var tokens = this.parse(indentedValue, tags); - return this.renderTokens(tokens, context, partials, indentedValue, config); - } - }; - Writer.prototype.unescapedValue = function unescapedValue(token, context) { - var value = context.lookup(token[1]); - if (value != null) - return value; - }; - Writer.prototype.escapedValue = function escapedValue(token, context, config) { - var escape2 = this.getConfigEscape(config) || mustache.escape; - var value = context.lookup(token[1]); - if (value != null) - return typeof value === "number" && escape2 === mustache.escape ? String(value) : escape2(value); - }; - Writer.prototype.rawValue = function rawValue(token) { - return token[1]; - }; - Writer.prototype.getConfigTags = function getConfigTags(config) { - if (isArray(config)) { - return config; - } else if (config && typeof config === "object") { - return config.tags; - } else { - return void 0; - } - }; - Writer.prototype.getConfigEscape = function getConfigEscape(config) { - if (config && typeof config === "object" && !isArray(config)) { - return config.escape; - } else { - return void 0; - } - }; - mustache = { - name: "mustache.js", - version: "4.2.0", - tags: ["{{", "}}"], - clearCache: void 0, - escape: void 0, - parse: void 0, - render: void 0, - Scanner: void 0, - Context: void 0, - Writer: void 0, - /** - * Allows a user to override the default caching strategy, by providing an - * object with set, get and clear methods. This can also be used to disable - * the cache by setting it to the literal `undefined`. - */ - set templateCache(cache2) { - defaultWriter.templateCache = cache2; - }, - /** - * Gets the default or overridden caching object from the default writer. - */ - get templateCache() { - return defaultWriter.templateCache; - } - }; - defaultWriter = new Writer(); - mustache.clearCache = function clearCache2() { - return defaultWriter.clearCache(); - }; - mustache.parse = function parse2(template, tags) { - return defaultWriter.parse(template, tags); - }; - mustache.render = function render2(template, view, partials, config) { - if (typeof template !== "string") { - throw new TypeError('Invalid template! Template should be a "string" but "' + typeStr(template) + '" was given as the first argument for mustache#render(template, view, partials)'); - } - return defaultWriter.render(template, view, partials, config); - }; - mustache.escape = escapeHtml; - mustache.Scanner = Scanner; - mustache.Context = Context; - mustache.Writer = Writer; - mustache_default = mustache; - } -}); - -// node_modules/@langchain/core/dist/prompts/template.js -function configureMustache() { - mustache_default.escape = (text) => text; -} -var parseFString, mustacheTemplateToNodes, parseMustache, interpolateFString, interpolateMustache, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate, parseTemplate2, checkValidTemplate; -var init_template = __esm({ - "node_modules/@langchain/core/dist/prompts/template.js"() { - init_mustache(); - init_errors(); - parseFString = (template) => { - const chars = template.split(""); - const nodes = []; - const nextBracket = (bracket, start) => { - for (let i4 = start; i4 < chars.length; i4 += 1) { - if (bracket.includes(chars[i4])) { - return i4; - } - } - return -1; - }; - let i3 = 0; - while (i3 < chars.length) { - if (chars[i3] === "{" && i3 + 1 < chars.length && chars[i3 + 1] === "{") { - nodes.push({ type: "literal", text: "{" }); - i3 += 2; - } else if (chars[i3] === "}" && i3 + 1 < chars.length && chars[i3 + 1] === "}") { - nodes.push({ type: "literal", text: "}" }); - i3 += 2; - } else if (chars[i3] === "{") { - const j3 = nextBracket("}", i3); - if (j3 < 0) { - throw new Error("Unclosed '{' in template."); - } - nodes.push({ - type: "variable", - name: chars.slice(i3 + 1, j3).join("") - }); - i3 = j3 + 1; - } else if (chars[i3] === "}") { - throw new Error("Single '}' in template."); - } else { - const next = nextBracket("{}", i3); - const text = (next < 0 ? chars.slice(i3) : chars.slice(i3, next)).join(""); - nodes.push({ type: "literal", text }); - i3 = next < 0 ? chars.length : next; - } - } - return nodes; - }; - mustacheTemplateToNodes = (template) => template.map((temp) => { - if (temp[0] === "name") { - const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; - return { type: "variable", name }; - } else if (["#", "&", "^", ">"].includes(temp[0])) { - return { type: "variable", name: temp[1] }; - } else { - return { type: "literal", text: temp[1] }; - } - }); - parseMustache = (template) => { - configureMustache(); - const parsed = mustache_default.parse(template); - return mustacheTemplateToNodes(parsed); - }; - interpolateFString = (template, values) => { - return parseFString(template).reduce((res, node) => { - if (node.type === "variable") { - if (node.name in values) { - const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]); - return res + stringValue; - } - throw new Error(`(f-string) Missing value for input ${node.name}`); - } - return res + node.text; - }, ""); - }; - interpolateMustache = (template, values) => { - configureMustache(); - return mustache_default.render(template, values); - }; - DEFAULT_FORMATTER_MAPPING = { - "f-string": interpolateFString, - mustache: interpolateMustache - }; - DEFAULT_PARSER_MAPPING = { - "f-string": parseFString, - mustache: parseMustache - }; - renderTemplate = (template, templateFormat, inputValues) => { - try { - return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); - } catch (e3) { - const error = addLangChainErrorFields(e3, "INVALID_PROMPT_INPUT"); - throw error; - } - }; - parseTemplate2 = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); - checkValidTemplate = (template, templateFormat, inputVariables) => { - if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { - const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); - throw new Error(`Invalid template format. Got \`${templateFormat}\`; - should be one of ${validFormats}`); - } - try { - const dummyInputs = inputVariables.reduce((acc, v5) => { - acc[v5] = "foo"; - return acc; - }, {}); - if (Array.isArray(template)) { - template.forEach((message) => { - if (message.type === "text") { - renderTemplate(message.text, templateFormat, dummyInputs); - } else if (message.type === "image_url") { - if (typeof message.image_url === "string") { - renderTemplate(message.image_url, templateFormat, dummyInputs); - } else { - const imageUrl = message.image_url.url; - renderTemplate(imageUrl, templateFormat, dummyInputs); - } - } else { - throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); - } - }); - } else { - renderTemplate(template, templateFormat, dummyInputs); - } - } catch (e3) { - throw new Error(`Invalid prompt schema: ${e3.message}`); - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/prompt.js -var prompt_exports = {}; -__export(prompt_exports, { - PromptTemplate: () => PromptTemplate -}); -var PromptTemplate; -var init_prompt = __esm({ - "node_modules/@langchain/core/dist/prompts/prompt.js"() { - init_string3(); - init_template(); - PromptTemplate = class extends BaseStringPromptTemplate { - static lc_name() { - return "PromptTemplate"; - } - constructor(input) { - super(input); - Object.defineProperty(this, "template", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "additionalContentFields", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) { - this.validateTemplate = false; - } - Object.assign(this, input); - if (this.validateTemplate) { - if (this.templateFormat === "mustache") { - throw new Error("Mustache templates cannot be validated."); - } - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - checkValidTemplate(this.template, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - return renderTemplate(this.template, this.templateFormat, allValues); - } - /** - * Take examples in list format with prefix and suffix to create a prompt. - * - * Intended to be used a a way to dynamically create a prompt from examples. - * - * @param examples - List of examples to use in the prompt. - * @param suffix - String to go after the list of examples. Should generally set up the user's input. - * @param inputVariables - A list of variable names the final prompt template will expect - * @param exampleSeparator - The separator to use in between examples - * @param prefix - String that should go before any examples. Generally includes examples. - * - * @returns The final prompt template generated. - */ - static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { - const template = [prefix, ...examples, suffix].join(exampleSeparator); - return new PromptTemplate({ - inputVariables, - template - }); - } - static fromTemplate(template, options) { - const { templateFormat = "f-string", ...rest } = options ?? {}; - const names = /* @__PURE__ */ new Set(); - parseTemplate2(template, templateFormat).forEach((node) => { - if (node.type === "variable") { - names.add(node.name); - } - }); - return new PromptTemplate({ - // Rely on extracted types - // eslint-disable-next-line @typescript-eslint/no-explicit-any - inputVariables: [...names], - templateFormat, - template, - ...rest - }); - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of PromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new PromptTemplate(promptDict); - } - serialize() { - if (this.outputParser !== void 0) { - throw new Error("Cannot serialize a prompt template with an output parser"); - } - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - template: this.template, - template_format: this.templateFormat - }; - } - static async deserialize(data) { - if (!data.template) { - throw new Error("Prompt template must have a template"); - } - const res = new PromptTemplate({ - inputVariables: data.input_variables, - template: data.template, - templateFormat: data.template_format - }); - return res; - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/image.js -var ImagePromptTemplate; -var init_image = __esm({ - "node_modules/@langchain/core/dist/prompts/image.js"() { - init_prompt_values(); - init_base6(); - init_template(); - ImagePromptTemplate = class extends BasePromptTemplate { - static lc_name() { - return "ImagePromptTemplate"; - } - constructor(input) { - super(input); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompts", "image"] - }); - Object.defineProperty(this, "template", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "additionalContentFields", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.template = input.template; - this.templateFormat = input.templateFormat ?? this.templateFormat; - this.validateTemplate = input.validateTemplate ?? this.validateTemplate; - this.additionalContentFields = input.additionalContentFields; - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - checkValidTemplate([ - { type: "image_url", image_url: this.template } - ], this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of ImagePromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ImagePromptTemplate(promptDict); - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const formatted = {}; - for (const [key, value] of Object.entries(this.template)) { - if (typeof value === "string") { - formatted[key] = renderTemplate(value, this.templateFormat, values); - } else { - formatted[key] = value; - } - } - const url = values.url || formatted.url; - const detail = values.detail || formatted.detail; - if (!url) { - throw new Error("Must provide either an image URL."); - } - if (typeof url !== "string") { - throw new Error("url must be a string."); - } - const output = { url }; - if (detail) { - output.detail = detail; - } - return output; - } - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new ImagePromptValue(formattedPrompt); - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/chat.js -function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { - return typeof baseMessagePromptTemplateLike.formatMessages === "function"; -} -function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { - if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) { - return messagePromptTemplateLike; - } - if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { - const messageContent = messagePromptTemplateLike[1]; - if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") { - const variableName = messageContent.slice(2, -2); - return new MessagesPlaceholder({ variableName, optional: true }); - } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") { - const variableName = messageContent.slice(1, -1); - return new MessagesPlaceholder({ variableName, optional: true }); - } - throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); - } - const message = coerceMessageLikeToMessage(messagePromptTemplateLike); - let templateData; - if (typeof message.content === "string") { - templateData = message.content; - } else { - templateData = message.content.map((item) => { - if ("text" in item) { - return { ...item, text: item.text }; - } else if ("image_url" in item) { - return { ...item, image_url: item.image_url }; - } else { - return item; - } - }); - } - if (message._getType() === "human") { - return HumanMessagePromptTemplate.fromTemplate(templateData, extra); - } else if (message._getType() === "ai") { - return AIMessagePromptTemplate.fromTemplate(templateData, extra); - } else if (message._getType() === "system") { - return SystemMessagePromptTemplate.fromTemplate(templateData, extra); - } else if (ChatMessage.isInstance(message)) { - return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); - } else { - throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); - } -} -function isMessagesPlaceholder(x2) { - return x2.constructor.lc_name() === "MessagesPlaceholder"; -} -var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; -var init_chat2 = __esm({ - "node_modules/@langchain/core/dist/prompts/chat.js"() { - init_messages2(); - init_prompt_values(); - init_base4(); - init_string3(); - init_base6(); - init_prompt(); - init_image(); - init_template(); - init_errors(); - BaseMessagePromptTemplate = class extends Runnable { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompts", "chat"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - /** - * Calls the formatMessages method with the provided input and options. - * @param input Input for the formatMessages method - * @param options Optional BaseCallbackConfig - * @returns Formatted output messages - */ - async invoke(input, options) { - return this._callWithConfig((input2) => this.formatMessages(input2), input, { ...options, runType: "prompt" }); - } - }; - MessagesPlaceholder = class extends BaseMessagePromptTemplate { - static lc_name() { - return "MessagesPlaceholder"; - } - constructor(fields) { - if (typeof fields === "string") { - fields = { variableName: fields }; - } - super(fields); - Object.defineProperty(this, "variableName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "optional", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.variableName = fields.variableName; - this.optional = fields.optional ?? false; - } - get inputVariables() { - return [this.variableName]; - } - async formatMessages(values) { - const input = values[this.variableName]; - if (this.optional && !input) { - return []; - } else if (!input) { - const error = new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); - error.name = "InputFormatError"; - throw error; - } - let formattedMessages; - try { - if (Array.isArray(input)) { - formattedMessages = input.map(coerceMessageLikeToMessage); - } else { - formattedMessages = [coerceMessageLikeToMessage(input)]; - } - } catch (e3) { - const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); - const error = new Error([ - `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, - `Received value: ${readableInput}`, - `Additional message: ${e3.message}` - ].join("\n\n")); - error.name = "InputFormatError"; - error.lc_error_code = e3.lc_error_code; - throw error; - } - return formattedMessages; - } - }; - BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { - constructor(fields) { - if (!("prompt" in fields)) { - fields = { prompt: fields }; - } - super(fields); - Object.defineProperty(this, "prompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.prompt = fields.prompt; - } - get inputVariables() { - return this.prompt.inputVariables; - } - async formatMessages(values) { - return [await this.format(values)]; - } - }; - BaseChatPromptTemplate = class extends BasePromptTemplate { - constructor(input) { - super(input); - } - async format(values) { - return (await this.formatPromptValue(values)).toString(); - } - async formatPromptValue(values) { - const resultMessages = await this.formatMessages(values); - return new ChatPromptValue(resultMessages); - } - }; - ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { - static lc_name() { - return "ChatMessagePromptTemplate"; - } - constructor(fields, role) { - if (!("prompt" in fields)) { - fields = { prompt: fields, role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; - } - async format(values) { - return new ChatMessage(await this.prompt.format(values), this.role); - } - static fromTemplate(template, role, options) { - return new this(PromptTemplate.fromTemplate(template, { - templateFormat: options?.templateFormat - }), role); - } - }; - _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { - static _messageClass() { - throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); - } - constructor(fields, additionalOptions) { - if (!("prompt" in fields)) { - fields = { prompt: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompts", "chat"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "inputVariables", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "additionalOptions", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "prompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "messageClass", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "chatMessageClass", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.prompt = fields.prompt; - if (Array.isArray(this.prompt)) { - let inputVariables = []; - this.prompt.forEach((prompt) => { - if ("inputVariables" in prompt) { - inputVariables = inputVariables.concat(prompt.inputVariables); - } - }); - this.inputVariables = inputVariables; - } else { - this.inputVariables = this.prompt.inputVariables; - } - this.additionalOptions = additionalOptions ?? this.additionalOptions; - } - createMessage(content) { - const constructor = this.constructor; - if (constructor._messageClass()) { - const MsgClass = constructor._messageClass(); - return new MsgClass({ content }); - } else if (constructor.chatMessageClass) { - const MsgClass = constructor.chatMessageClass(); - return new MsgClass({ - content, - role: this.getRoleFromMessageClass(MsgClass.lc_name()) - }); - } else { - throw new Error("No message class defined"); - } - } - getRoleFromMessageClass(name) { - switch (name) { - case "HumanMessage": - return "human"; - case "AIMessage": - return "ai"; - case "SystemMessage": - return "system"; - case "ChatMessage": - return "chat"; - default: - throw new Error("Invalid message class name"); - } - } - static fromTemplate(template, additionalOptions) { - if (typeof template === "string") { - return new this(PromptTemplate.fromTemplate(template, additionalOptions)); - } - const prompt = []; - for (const item of template) { - if (typeof item === "string" || typeof item === "object" && "text" in item) { - let text = ""; - if (typeof item === "string") { - text = item; - } else if (typeof item.text === "string") { - text = item.text ?? ""; - } - const options = { - ...additionalOptions, - ...typeof item !== "string" ? { additionalContentFields: item } : {} - }; - prompt.push(PromptTemplate.fromTemplate(text, options)); - } else if (typeof item === "object" && "image_url" in item) { - let imgTemplate = item.image_url ?? ""; - let imgTemplateObject; - let inputVariables = []; - if (typeof imgTemplate === "string") { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") { - parsedTemplate = parseMustache(imgTemplate); - } else { - parsedTemplate = parseFString(imgTemplate); - } - const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); - if ((variables?.length ?? 0) > 0) { - if (variables.length > 1) { - throw new Error(`Only one format variable allowed per image template. -Got: ${variables} -From: ${imgTemplate}`); - } - inputVariables = [variables[0]]; - } else { - inputVariables = []; - } - imgTemplate = { url: imgTemplate }; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else if (typeof imgTemplate === "object") { - if ("url" in imgTemplate) { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") { - parsedTemplate = parseMustache(imgTemplate.url); - } else { - parsedTemplate = parseFString(imgTemplate.url); - } - inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); - } else { - inputVariables = []; - } - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else { - throw new Error("Invalid image template"); - } - prompt.push(imgTemplateObject); - } - } - return new this({ prompt, additionalOptions }); - } - async format(input) { - if (this.prompt instanceof BaseStringPromptTemplate) { - const text = await this.prompt.format(input); - return this.createMessage(text); - } else { - const content = []; - for (const prompt of this.prompt) { - let inputs = {}; - if (!("inputVariables" in prompt)) { - throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); - } - for (const item of prompt.inputVariables) { - if (!inputs) { - inputs = { [item]: input[item] }; - } - inputs = { ...inputs, [item]: input[item] }; - } - if (prompt instanceof BaseStringPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) { - additionalContentFields = prompt.additionalContentFields; - } - content.push({ - ...additionalContentFields, - type: "text", - text: formatted - }); - } else if (prompt instanceof ImagePromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) { - additionalContentFields = prompt.additionalContentFields; - } - content.push({ - ...additionalContentFields, - type: "image_url", - image_url: formatted - }); - } - } - return this.createMessage(content); - } - } - async formatMessages(values) { - return [await this.format(values)]; - } - }; - HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return HumanMessage; - } - static lc_name() { - return "HumanMessagePromptTemplate"; - } - }; - AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return AIMessage; - } - static lc_name() { - return "AIMessagePromptTemplate"; - } - }; - SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return SystemMessage; - } - static lc_name() { - return "SystemMessagePromptTemplate"; - } - }; - ChatPromptTemplate = class extends BaseChatPromptTemplate { - static lc_name() { - return "ChatPromptTemplate"; - } - get lc_aliases() { - return { - promptMessages: "messages" - }; - } - constructor(input) { - super(input); - Object.defineProperty(this, "promptMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) { - this.validateTemplate = false; - } - Object.assign(this, input); - if (this.validateTemplate) { - const inputVariablesMessages = /* @__PURE__ */ new Set(); - for (const promptMessage of this.promptMessages) { - if (promptMessage instanceof BaseMessage) - continue; - for (const inputVariable of promptMessage.inputVariables) { - inputVariablesMessages.add(inputVariable); - } - } - const totalInputVariables = this.inputVariables; - const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); - const difference = new Set([...inputVariablesInstance].filter((x2) => !inputVariablesMessages.has(x2))); - if (difference.size > 0) { - throw new Error(`Input variables \`${[ - ...difference - ]}\` are not used in any of the prompt messages.`); - } - const otherDifference = new Set([...inputVariablesMessages].filter((x2) => !inputVariablesInstance.has(x2))); - if (otherDifference.size > 0) { - throw new Error(`Input variables \`${[ - ...otherDifference - ]}\` are used in prompt messages but not in the prompt template.`); - } - } - } - _getPromptType() { - return "chat"; - } - async _parseImagePrompts(message, inputValues) { - if (typeof message.content === "string") { - return message; - } - const formattedMessageContent = await Promise.all(message.content.map(async (item) => { - if (item.type !== "image_url") { - return item; - } - let imageUrl = ""; - if (typeof item.image_url === "string") { - imageUrl = item.image_url; - } else { - imageUrl = item.image_url.url; - } - const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { - templateFormat: this.templateFormat - }); - const formattedUrl = await promptTemplatePlaceholder.format(inputValues); - if (typeof item.image_url !== "string" && "url" in item.image_url) { - item.image_url.url = formattedUrl; - } else { - item.image_url = formattedUrl; - } - return item; - })); - message.content = formattedMessageContent; - return message; - } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let resultMessages = []; - for (const promptMessage of this.promptMessages) { - if (promptMessage instanceof BaseMessage) { - resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); - } else { - const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { - if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { - const error = addLangChainErrorFields(new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); - throw error; - } - acc[inputVariable] = allValues[inputVariable]; - return acc; - }, {}); - const message = await promptMessage.formatMessages(inputValues); - resultMessages = resultMessages.concat(message); - } - } - return resultMessages; - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ChatPromptTemplate(promptDict); - } - static fromTemplate(template, options) { - const prompt = PromptTemplate.fromTemplate(template, options); - const humanTemplate = new HumanMessagePromptTemplate({ prompt }); - return this.fromMessages([humanTemplate]); - } - /** - * Create a chat model-specific prompt from individual chat messages - * or message-like tuples. - * @param promptMessages Messages to be passed to the chat model - * @returns A new ChatPromptTemplate - */ - static fromMessages(promptMessages, extra) { - const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat( - // eslint-disable-next-line no-instanceof/no-instanceof - promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [ - _coerceMessagePromptTemplateLike(promptMessage, extra) - ] - ), []); - const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => ( - // eslint-disable-next-line no-instanceof/no-instanceof - promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc - ), /* @__PURE__ */ Object.create(null)); - const inputVariables = /* @__PURE__ */ new Set(); - for (const promptMessage of flattenedMessages) { - if (promptMessage instanceof BaseMessage) - continue; - for (const inputVariable of promptMessage.inputVariables) { - if (inputVariable in flattenedPartialVariables) { - continue; - } - inputVariables.add(inputVariable); - } - } - return new this({ - ...extra, - inputVariables: [...inputVariables], - promptMessages: flattenedMessages, - partialVariables: flattenedPartialVariables, - templateFormat: extra?.templateFormat - }); - } - /** @deprecated Renamed to .fromMessages */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static fromPromptMessages(promptMessages) { - return this.fromMessages(promptMessages); - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/few_shot.js -var few_shot_exports = {}; -__export(few_shot_exports, { - FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, - FewShotPromptTemplate: () => FewShotPromptTemplate -}); -var FewShotPromptTemplate, FewShotChatMessagePromptTemplate; -var init_few_shot = __esm({ - "node_modules/@langchain/core/dist/prompts/few_shot.js"() { - init_string3(); - init_template(); - init_prompt(); - init_chat2(); - FewShotPromptTemplate = class extends BaseStringPromptTemplate { - constructor(input) { - super(input); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "examples", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "exampleSelector", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "examplePrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "suffix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "exampleSeparator", { - enumerable: true, - configurable: true, - writable: true, - value: "\n\n" - }); - Object.defineProperty(this, "prefix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.assign(this, input); - if (this.examples !== void 0 && this.exampleSelector !== void 0) { - throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - } - if (this.examples === void 0 && this.exampleSelector === void 0) { - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "few_shot"; - } - static lc_name() { - return "FewShotPromptTemplate"; - } - async getExamples(inputVariables) { - if (this.examples !== void 0) { - return this.examples; - } - if (this.exampleSelector !== void 0) { - return this.exampleSelector.selectExamples(inputVariables); - } - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotPromptTemplate(promptDict); - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); - const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - serialize() { - if (this.exampleSelector || !this.examples) { - throw new Error("Serializing an example selector is not currently supported"); - } - if (this.outputParser !== void 0) { - throw new Error("Serializing an output parser is not currently supported"); - } - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - example_prompt: this.examplePrompt.serialize(), - example_separator: this.exampleSeparator, - suffix: this.suffix, - prefix: this.prefix, - template_format: this.templateFormat, - examples: this.examples - }; - } - static async deserialize(data) { - const { example_prompt } = data; - if (!example_prompt) { - throw new Error("Missing example prompt"); - } - const examplePrompt = await PromptTemplate.deserialize(example_prompt); - let examples; - if (Array.isArray(data.examples)) { - examples = data.examples; - } else { - throw new Error("Invalid examples format. Only list or string are supported."); - } - return new FewShotPromptTemplate({ - inputVariables: data.input_variables, - examplePrompt, - examples, - exampleSeparator: data.example_separator, - prefix: data.prefix, - suffix: data.suffix, - templateFormat: data.template_format - }); - } - }; - FewShotChatMessagePromptTemplate = class extends BaseChatPromptTemplate { - _getPromptType() { - return "few_shot_chat"; - } - static lc_name() { - return "FewShotChatMessagePromptTemplate"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "examples", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "exampleSelector", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "examplePrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "suffix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "exampleSeparator", { - enumerable: true, - configurable: true, - writable: true, - value: "\n\n" - }); - Object.defineProperty(this, "prefix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - this.examples = fields.examples; - this.examplePrompt = fields.examplePrompt; - this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; - this.exampleSelector = fields.exampleSelector; - this.prefix = fields.prefix ?? ""; - this.suffix = fields.suffix ?? ""; - this.templateFormat = fields.templateFormat ?? "f-string"; - this.validateTemplate = fields.validateTemplate ?? true; - if (this.examples !== void 0 && this.exampleSelector !== void 0) { - throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - } - if (this.examples === void 0 && this.exampleSelector === void 0) { - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - async getExamples(inputVariables) { - if (this.examples !== void 0) { - return this.examples; - } - if (this.exampleSelector !== void 0) { - return this.exampleSelector.selectExamples(inputVariables); - } - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - /** - * Formats the list of values and returns a list of formatted messages. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let examples = await this.getExamples(allValues); - examples = examples.map((example) => { - const result = {}; - this.examplePrompt.inputVariables.forEach((inputVariable) => { - result[inputVariable] = example[inputVariable]; - }); - return result; - }); - const messages = []; - for (const example of examples) { - const exampleMessages = await this.examplePrompt.formatMessages(example); - messages.push(...exampleMessages); - } - return messages; - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example))); - const exampleStrings = exampleMessages.flat().map((message) => message.content); - const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - /** - * Partially formats the prompt with the given values. - * @param values The values to partially format the prompt with. - * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotChatMessagePromptTemplate(promptDict); - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/base.js -var BasePromptTemplate; -var init_base6 = __esm({ - "node_modules/@langchain/core/dist/prompts/base.js"() { - init_base4(); - BasePromptTemplate = class extends Runnable { - get lc_attributes() { - return { - partialVariables: void 0 - // python doesn't support this yet - }; - } - constructor(input) { - super(input); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "prompts", this._getPromptType()] - }); - Object.defineProperty(this, "inputVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputParser", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "partialVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const { inputVariables } = input; - if (inputVariables.includes("stop")) { - throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); - } - Object.assign(this, input); - } - /** - * Merges partial variables and user variables. - * @param userVariables The user variables to merge with the partial variables. - * @returns A Promise that resolves to an object containing the merged variables. - */ - async mergePartialAndUserVariables(userVariables) { - const partialVariables = this.partialVariables ?? {}; - const partialValues = {}; - for (const [key, value] of Object.entries(partialVariables)) { - if (typeof value === "string") { - partialValues[key] = value; - } else { - partialValues[key] = await value(); - } - } - const allKwargs = { - ...partialValues, - ...userVariables - }; - return allKwargs; - } - /** - * Invokes the prompt template with the given input and options. - * @param input The input to invoke the prompt template with. - * @param options Optional configuration for the callback. - * @returns A Promise that resolves to the output of the prompt template. - */ - async invoke(input, options) { - const metadata = { - ...this.metadata, - ...options?.metadata - }; - const tags = [...this.tags ?? [], ...options?.tags ?? []]; - return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { ...options, tags, metadata, runType: "prompt" }); - } - /** - * Return a json-like object representing this prompt template. - * @deprecated - */ - serialize() { - throw new Error("Use .toJSON() instead"); - } - /** - * @deprecated - * Load a prompt template from a json-like object describing it. - * - * @remarks - * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can - * reference remote resources that we read asynchronously with a web - * request. - */ - static async deserialize(data) { - switch (data._type) { - case "prompt": { - const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); - return PromptTemplate2.deserialize(data); - } - case void 0: { - const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); - return PromptTemplate2.deserialize({ ...data, _type: "prompt" }); - } - case "few_shot": { - const { FewShotPromptTemplate: FewShotPromptTemplate2 } = await Promise.resolve().then(() => (init_few_shot(), few_shot_exports)); - return FewShotPromptTemplate2.deserialize(data); - } - default: - throw new Error(`Invalid prompt type in config: ${data._type}`); - } - } - }; - } -}); - -// node_modules/@langchain/core/dist/prompts/pipeline.js -var init_pipeline2 = __esm({ - "node_modules/@langchain/core/dist/prompts/pipeline.js"() { - init_base6(); - init_chat2(); - } -}); - -// node_modules/@langchain/core/dist/prompts/serde.js -var init_serde = __esm({ - "node_modules/@langchain/core/dist/prompts/serde.js"() { - } -}); - -// node_modules/@langchain/core/dist/prompts/structured.js -var init_structured2 = __esm({ - "node_modules/@langchain/core/dist/prompts/structured.js"() { - init_chat2(); - } -}); - -// node_modules/@langchain/core/dist/prompts/index.js -var init_prompts2 = __esm({ - "node_modules/@langchain/core/dist/prompts/index.js"() { - init_base6(); - init_chat2(); - init_few_shot(); - init_pipeline2(); - init_prompt(); - init_serde(); - init_string3(); - init_template(); - init_image(); - init_structured2(); - } -}); - -// node_modules/@langchain/core/prompts.js -var init_prompts3 = __esm({ - "node_modules/@langchain/core/prompts.js"() { - init_prompts2(); - } -}); - -// node_modules/@langchain/core/runnables.js -var init_runnables2 = __esm({ - "node_modules/@langchain/core/runnables.js"() { - init_runnables(); - } -}); - -// node_modules/react/cjs/react.development.js -var require_react_development = __commonJS({ - "node_modules/react/cjs/react.development.js"(exports, module2) { - "use strict"; - if (true) { - (function() { - "use strict"; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var ReactVersion = "18.2.0"; - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var ReactCurrentDispatcher = { - /** - * @internal - * @type {ReactComponent} - */ - current: null - }; - var ReactCurrentBatchConfig = { - transition: null - }; - var ReactCurrentActQueue = { - current: null, - // Used to reproduce behavior of `batchedUpdates` in legacy mode. - isBatchingLegacy: false, - didScheduleLegacyUpdate: false - }; - var ReactCurrentOwner = { - /** - * @internal - * @type {ReactComponent} - */ - current: null - }; - var ReactDebugCurrentFrame = {}; - var currentExtraStackFrame = null; - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack; - } - } - { - ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { - { - currentExtraStackFrame = stack; - } - }; - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFrame.getStackAddendum = function() { - var stack = ""; - if (currentExtraStackFrame) { - stack += currentExtraStackFrame; - } - var impl = ReactDebugCurrentFrame.getCurrentStack; - if (impl) { - stack += impl() || ""; - } - return stack; - }; - } - var enableScopeAPI = false; - var enableCacheElement = false; - var enableTransitionTracing = false; - var enableLegacyHidden = false; - var enableDebugTracing = false; - var ReactSharedInternals = { - ReactCurrentDispatcher, - ReactCurrentBatchConfig, - ReactCurrentOwner - }; - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; - ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; - } - function warn2(format) { - { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var didWarnStateUpdateForUnmountedComponent = {}; - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; - var warningKey = componentName + "." + callerName; - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return; - } - error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); - didWarnStateUpdateForUnmountedComponent[warningKey] = true; - } - } - var ReactNoopUpdateQueue = { - /** - * Checks whether or not this composite component is mounted. - * @param {ReactClass} publicInstance The instance we want to test. - * @return {boolean} True if mounted, false otherwise. - * @protected - * @final - */ - isMounted: function(publicInstance) { - return false; - }, - /** - * Forces an update. This should only be invoked when it is known with - * certainty that we are **not** in a DOM transaction. - * - * You may want to call this when you know that some deeper aspect of the - * component's state has changed but `setState` was not called. - * - * This will not invoke `shouldComponentUpdate`, but it will invoke - * `componentWillUpdate` and `componentDidUpdate`. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueForceUpdate: function(publicInstance, callback, callerName) { - warnNoop(publicInstance, "forceUpdate"); - }, - /** - * Replaces all of the state. Always use this or `setState` to mutate state. - * You should treat `this.state` as immutable. - * - * There is no guarantee that `this.state` will be immediately updated, so - * accessing `this.state` after calling this method may return the old value. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} completeState Next state. - * @param {?function} callback Called after component is updated. - * @param {?string} callerName name of the calling function in the public API. - * @internal - */ - enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { - warnNoop(publicInstance, "replaceState"); - }, - /** - * Sets a subset of the state. This only exists because _pendingState is - * internal. This provides a merging strategy that is not available to deep - * properties which is confusing. TODO: Expose pendingState or don't use it - * during the merge. - * - * @param {ReactClass} publicInstance The instance that should rerender. - * @param {object} partialState Next partial state to be merged with state. - * @param {?function} callback Called after component is updated. - * @param {?string} Name of the calling function in the public API. - * @internal - */ - enqueueSetState: function(publicInstance, partialState, callback, callerName) { - warnNoop(publicInstance, "setState"); - } - }; - var assign = Object.assign; - var emptyObject = {}; - { - Object.freeze(emptyObject); - } - function Component2(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - Component2.prototype.isReactComponent = {}; - Component2.prototype.setState = function(partialState, callback) { - if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { - throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); - } - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component2.prototype.forceUpdate = function(callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - { - var deprecatedAPIs = { - isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], - replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] - }; - var defineDeprecationWarning = function(methodName, info) { - Object.defineProperty(Component2.prototype, methodName, { - get: function() { - warn2("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); - return void 0; - } - }); - }; - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - } - } - } - function ComponentDummy() { - } - ComponentDummy.prototype = Component2.prototype; - function PureComponent(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); - pureComponentPrototype.constructor = PureComponent; - assign(pureComponentPrototype, Component2.prototype); - pureComponentPrototype.isPureReactComponent = true; - function createRef() { - var refObject = { - current: null - }; - { - Object.seal(refObject); - } - return refObject; - } - var isArrayImpl = Array.isArray; - function isArray2(a3) { - return isArrayImpl(a3); - } - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e3) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x2) { - return null; - } - } - } - } - return null; - } - var hasOwnProperty3 = Object.prototype.hasOwnProperty; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty3.call(config, "ref")) { - var getter = Object.getOwnPropertyDescriptor(config, "ref").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== void 0; - } - function hasValidKey(config) { - { - if (hasOwnProperty3.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== void 0; - } - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function() { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function() { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, "ref", { - get: warnAboutAccessingRef, - configurable: true - }); - } - function warnIfStringRefCannotBeAutoConverted(config) { - { - if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { - var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - var ReactElement = function(type, key, ref, self2, source, owner, props) { - var element = { - // This tag allows us to uniquely identify this as a React Element - $$typeof: REACT_ELEMENT_TYPE, - // Built-in properties that belong on the element - type, - key, - ref, - props, - // Record the component responsible for creating this element. - _owner: owner - }; - { - element._store = {}; - Object.defineProperty(element._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: false - }); - Object.defineProperty(element, "_self", { - configurable: false, - enumerable: false, - writable: false, - value: self2 - }); - Object.defineProperty(element, "_source", { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - function createElement31(type, config, children) { - var propName; - var props = {}; - var key = null; - var ref = null; - var self2 = null; - var source = null; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - { - warnIfStringRefCannotBeAutoConverted(config); - } - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - self2 = config.__self === void 0 ? null : config.__self; - source = config.__source === void 0 ? null : config.__source; - for (propName in config) { - if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i3 = 0; i3 < childrenLength; i3++) { - childArray[i3] = arguments[i3 + 2]; - } - { - if (Object.freeze) { - Object.freeze(childArray); - } - } - props.children = childArray; - } - if (type && type.defaultProps) { - var defaultProps2 = type.defaultProps; - for (propName in defaultProps2) { - if (props[propName] === void 0) { - props[propName] = defaultProps2[propName]; - } - } - } - { - if (key || ref) { - var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - } - return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); - return newElement; - } - function cloneElement15(element, config, children) { - if (element === null || element === void 0) { - throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); - } - var propName; - var props = assign({}, element.props); - var key = element.key; - var ref = element.ref; - var self2 = element._self; - var source = element._source; - var owner = element._owner; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - owner = ReactCurrentOwner.current; - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - var defaultProps2; - if (element.type && element.type.defaultProps) { - defaultProps2 = element.type.defaultProps; - } - for (propName in config) { - if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - if (config[propName] === void 0 && defaultProps2 !== void 0) { - props[propName] = defaultProps2[propName]; - } else { - props[propName] = config[propName]; - } - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i3 = 0; i3 < childrenLength; i3++) { - childArray[i3] = arguments[i3 + 2]; - } - props.children = childArray; - } - return ReactElement(element.type, key, ref, self2, source, owner, props); - } - function isValidElement11(object) { - return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - var SEPARATOR = "."; - var SUBSEPARATOR = ":"; - function escape2(key) { - var escapeRegex2 = /[=:]/g; - var escaperLookup = { - "=": "=0", - ":": "=2" - }; - var escapedString = key.replace(escapeRegex2, function(match2) { - return escaperLookup[match2]; - }); - return "$" + escapedString; - } - var didWarnAboutMaps = false; - var userProvidedKeyEscapeRegex = /\/+/g; - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, "$&/"); - } - function getElementKey(element, index2) { - if (typeof element === "object" && element !== null && element.key != null) { - { - checkKeyStringCoercion(element.key); - } - return escape2("" + element.key); - } - return index2.toString(36); - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if (type === "undefined" || type === "boolean") { - children = null; - } - var invokeCallback = false; - if (children === null) { - invokeCallback = true; - } else { - switch (type) { - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - } - } - } - if (invokeCallback) { - var _child = children; - var mappedChild = callback(_child); - var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; - if (isArray2(mappedChild)) { - var escapedChildKey = ""; - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + "/"; - } - mapIntoArray(mappedChild, array, escapedChildKey, "", function(c4) { - return c4; - }); - } else if (mappedChild != null) { - if (isValidElement11(mappedChild)) { - { - if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { - checkKeyStringCoercion(mappedChild.key); - } - } - mappedChild = cloneAndReplaceKey( - mappedChild, - // Keep both the (mapped) and old keys if they differ, just as - // traverseAllChildren used to do for objects as children - escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key - (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( - // $FlowFixMe Flow incorrectly thinks existing element's key can be a number - // eslint-disable-next-line react-internal/safe-string-coercion - escapeUserProvidedKey("" + mappedChild.key) + "/" - ) : "") + childKey - ); - } - array.push(mappedChild); - } - return 1; - } - var child; - var nextName; - var subtreeCount = 0; - var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; - if (isArray2(children)) { - for (var i3 = 0; i3 < children.length; i3++) { - child = children[i3]; - nextName = nextNamePrefix + getElementKey(child, i3); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var iterableChildren = children; - { - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn2("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - } - var iterator = iteratorFn.call(iterableChildren); - var step; - var ii = 0; - while (!(step = iterator.next()).done) { - child = step.value; - nextName = nextNamePrefix + getElementKey(child, ii++); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else if (type === "object") { - var childrenString = String(children); - throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); - } - } - return subtreeCount; - } - function mapChildren(children, func, context) { - if (children == null) { - return children; - } - var result = []; - var count5 = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count5++); - }); - return result; - } - function countChildren(children) { - var n4 = 0; - mapChildren(children, function() { - n4++; - }); - return n4; - } - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren(children, function() { - forEachFunc.apply(this, arguments); - }, forEachContext); - } - function toArray2(children) { - return mapChildren(children, function(child) { - return child; - }) || []; - } - function onlyChild(children) { - if (!isValidElement11(children)) { - throw new Error("React.Children.only expected to receive a single React element child."); - } - return children; - } - function createContext13(defaultValue) { - var context = { - $$typeof: REACT_CONTEXT_TYPE, - // As a workaround to support multiple concurrent renderers, we categorize - // some renderers as primary and others as secondary. We only expect - // there to be two concurrent renderers at most: React Native (primary) and - // Fabric (secondary); React DOM (primary) and React ART (secondary). - // Secondary renderers store their context values on separate fields. - _currentValue: defaultValue, - _currentValue2: defaultValue, - // Used to track how many concurrent renderers this context currently - // supports within in a single renderer. Such as parallel server rendering. - _threadCount: 0, - // These are circular - Provider: null, - Consumer: null, - // Add these to use same hidden class in VM as ServerContext - _defaultValue: null, - _globalName: null - }; - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context - }; - var hasWarnedAboutUsingNestedContextConsumers = false; - var hasWarnedAboutUsingConsumerProvider = false; - var hasWarnedAboutDisplayNameOnConsumer = false; - { - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context - }; - Object.defineProperties(Consumer, { - Provider: { - get: function() { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render 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 is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Consumer; - } - }, - displayName: { - get: function() { - return context.displayName; - }, - set: function(displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn2("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); - hasWarnedAboutDisplayNameOnConsumer = true; - } - } - } - }); - context.Consumer = Consumer; - } - { - context._currentRenderer = null; - context._currentRenderer2 = null; - } - return context; - } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result; - var thenable = ctor(); - thenable.then(function(moduleObject2) { - if (payload._status === Pending || payload._status === Uninitialized) { - var resolved = payload; - resolved._status = Resolved; - resolved._result = moduleObject2; - } - }, function(error2) { - if (payload._status === Pending || payload._status === Uninitialized) { - var rejected = payload; - rejected._status = Rejected; - rejected._result = error2; - } - }); - if (payload._status === Uninitialized) { - var pending = payload; - pending._status = Pending; - pending._result = thenable; - } - } - if (payload._status === Resolved) { - var moduleObject = payload._result; - { - if (moduleObject === void 0) { - error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); - } - } - { - if (!("default" in moduleObject)) { - error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); - } - } - return moduleObject.default; - } else { - throw payload._result; - } - } - function lazy(ctor) { - var payload = { - // We use these fields to store the result. - _status: Uninitialized, - _result: ctor - }; - var lazyType2 = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer - }; - { - var defaultProps2; - var propTypes; - Object.defineProperties(lazyType2, { - defaultProps: { - configurable: true, - get: function() { - return defaultProps2; - }, - set: function(newDefaultProps) { - error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - defaultProps2 = newDefaultProps; - Object.defineProperty(lazyType2, "defaultProps", { - enumerable: true - }); - } - }, - propTypes: { - configurable: true, - get: function() { - return propTypes; - }, - set: function(newPropTypes) { - error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - propTypes = newPropTypes; - Object.defineProperty(lazyType2, "propTypes", { - enumerable: true - }); - } - } - }); - } - return lazyType2; - } - function forwardRef82(render3) { - { - if (render3 != null && render3.$$typeof === REACT_MEMO_TYPE) { - error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); - } else if (typeof render3 !== "function") { - error("forwardRef requires a render function but was given %s.", render3 === null ? "null" : typeof render3); - } else { - if (render3.length !== 0 && render3.length !== 2) { - error("forwardRef render functions accept exactly two parameters: props and ref. %s", render3.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); - } - } - if (render3 != null) { - if (render3.defaultProps != null || render3.propTypes != null) { - error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); - } - } - } - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: render3 - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (!render3.name && !render3.displayName) { - render3.displayName = name; - } - } - }); - } - return elementType; - } - var REACT_MODULE_REFERENCE; - { - REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); - } - function isValidElementType(type) { - if (typeof type === "string" || typeof type === "function") { - return true; - } - if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { - return true; - } - if (typeof type === "object" && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object - // types supported by any Flight configuration anywhere since - // we don't know which Flight build this will end up being used - // with. - type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { - return true; - } - } - return false; - } - function memo3(type, compare2) { - { - if (!isValidElementType(type)) { - error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); - } - } - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type, - compare: compare2 === void 0 ? null : compare2 - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (!type.name && !type.displayName) { - type.displayName = name; - } - } - }); - } - return elementType; - } - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current; - { - if (dispatcher === null) { - error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - } - return dispatcher; - } - function useContext14(Context2) { - var dispatcher = resolveDispatcher(); - { - if (Context2._context !== void 0) { - var realContext = Context2._context; - if (realContext.Consumer === Context2) { - error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); - } else if (realContext.Provider === Context2) { - error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); - } - } - } - return dispatcher.useContext(Context2); - } - function useState57(initialState2) { - var dispatcher = resolveDispatcher(); - return dispatcher.useState(initialState2); - } - function useReducer4(reducer2, initialArg, init) { - var dispatcher = resolveDispatcher(); - return dispatcher.useReducer(reducer2, initialArg, init); - } - function useRef43(initialValue) { - var dispatcher = resolveDispatcher(); - return dispatcher.useRef(initialValue); - } - function useEffect51(create9, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useEffect(create9, deps); - } - function useInsertionEffect(create9, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useInsertionEffect(create9, deps); - } - function useLayoutEffect5(create9, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useLayoutEffect(create9, deps); - } - function useCallback38(callback, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useCallback(callback, deps); - } - function useMemo15(create9, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useMemo(create9, deps); - } - function useImperativeHandle3(ref, create9, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useImperativeHandle(ref, create9, deps); - } - function useDebugValue2(value, formatterFn) { - { - var dispatcher = resolveDispatcher(); - return dispatcher.useDebugValue(value, formatterFn); - } - } - function useTransition() { - var dispatcher = resolveDispatcher(); - return dispatcher.useTransition(); - } - function useDeferredValue(value) { - var dispatcher = resolveDispatcher(); - return dispatcher.useDeferredValue(value); - } - function useId2() { - var dispatcher = resolveDispatcher(); - return dispatcher.useId(); - } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var dispatcher = resolveDispatcher(); - return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x2) { - var match2 = x2.stack.trim().match(/\n( *(at )?)/); - prefix = match2 && match2[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x2) { - control = x2; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x2) { - control = x2; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x2) { - control = x2; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s4 = sampleLines.length - 1; - var c4 = controlLines.length - 1; - while (s4 >= 1 && c4 >= 0 && sampleLines[s4] !== controlLines[c4]) { - c4--; - } - for (; s4 >= 1 && c4 >= 0; s4--, c4--) { - if (sampleLines[s4] !== controlLines[c4]) { - if (s4 !== 1 || c4 !== 1) { - do { - s4--; - c4--; - if (c4 < 0 || sampleLines[s4] !== controlLines[c4]) { - var _frame = "\n" + sampleLines[s4].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s4 >= 1 && c4 >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component3) { - var prototype = Component3.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x2) { - } - } - } - } - return ""; - } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location2, componentName, element) { - { - var has2 = Function.call.bind(hasOwnProperty3); - for (var typeSpecName in typeSpecs) { - if (has2(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location2, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location2, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - setExtraStackFrame(stack); - } else { - setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentNameFromType(ReactCurrentOwner.current.type); - if (name) { - return "\n\nCheck the render method of `" + name + "`."; - } - } - return ""; - } - function getSourceInfoErrorAddendum(source) { - if (source !== void 0) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ""); - var lineNumber = source.lineNumber; - return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; - } - return ""; - } - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== void 0) { - return getSourceInfoErrorAddendum(elementProps.__source); - } - return ""; - } - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - function validateExplicitKey(element, parentType) { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - var childOwner = ""; - if (element && element._owner && element._owner !== ReactCurrentOwner.current) { - childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; - } - { - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - function validateChildKeys(node, parentType) { - if (typeof node !== "object") { - return; - } - if (isArray2(node)) { - for (var i3 = 0; i3 < node.length; i3++) { - var child = node[i3]; - if (isValidElement11(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement11(node)) { - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === "function") { - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement11(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === void 0 || typeof type === "string") { - return; - } - var propTypes; - if (typeof type === "function") { - propTypes = type.propTypes; - } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. - // Inner props are checked in the reconciler. - type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - var name = getComponentNameFromType(type); - checkPropTypes(propTypes, element.props, "prop", name, element); - } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; - var _name = getComponentNameFromType(type); - error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); - } - if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { - error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); - } - } - } - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i3 = 0; i3 < keys.length; i3++) { - var key = keys[i3]; - if (key !== "children" && key !== "key") { - setCurrentlyValidatingElement$1(fragment); - error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error("Invalid attribute `ref` supplied to `React.Fragment`."); - setCurrentlyValidatingElement$1(null); - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type); - if (!validType) { - var info = ""; - if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendumForProps(props); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = "null"; - } else if (isArray2(type)) { - typeString = "array"; - } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; - info = " Did you accidentally export a JSX literal instead of a component?"; - } else { - typeString = typeof type; - } - { - error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); - } - } - var element = createElement31.apply(this, arguments); - if (element == null) { - return element; - } - if (validType) { - for (var i3 = 2; i3 < arguments.length; i3++) { - validateChildKeys(arguments[i3], type); - } - } - if (type === REACT_FRAGMENT_TYPE) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - var didWarnAboutDeprecatedCreateFactory = false; - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type); - validatedFactory.type = type; - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true; - warn2("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); - } - Object.defineProperty(validatedFactory, "type", { - enumerable: false, - get: function() { - warn2("Factory.type is deprecated. Access the class directly before passing it to createFactory."); - Object.defineProperty(this, "type", { - value: type - }); - return type; - } - }); - } - return validatedFactory; - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement15.apply(this, arguments); - for (var i3 = 2; i3 < arguments.length; i3++) { - validateChildKeys(arguments[i3], newElement.type); - } - validatePropTypes(newElement); - return newElement; - } - function startTransition(scope, options) { - var prevTransition = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = {}; - var currentTransition = ReactCurrentBatchConfig.transition; - { - ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); - } - try { - scope(); - } finally { - ReactCurrentBatchConfig.transition = prevTransition; - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - if (updatedFibersCount > 10) { - warn2("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); - } - currentTransition._updatedFibers.clear(); - } - } - } - } - var didWarnAboutMessageChannel = false; - var enqueueTaskImpl = null; - function enqueueTask(task) { - if (enqueueTaskImpl === null) { - try { - var requireString = ("require" + Math.random()).slice(0, 7); - var nodeRequire = module2 && module2[requireString]; - enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate; - } catch (_err) { - enqueueTaskImpl = function(callback) { - { - if (didWarnAboutMessageChannel === false) { - didWarnAboutMessageChannel = true; - if (typeof MessageChannel === "undefined") { - error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); - } - } - } - var channel = new MessageChannel(); - channel.port1.onmessage = callback; - channel.port2.postMessage(void 0); - }; - } - } - return enqueueTaskImpl(task); - } - var actScopeDepth = 0; - var didWarnNoAwaitAct = false; - function act(callback) { - { - var prevActScopeDepth = actScopeDepth; - actScopeDepth++; - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - } - var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; - var result; - try { - ReactCurrentActQueue.isBatchingLegacy = true; - result = callback(); - if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { - var queue2 = ReactCurrentActQueue.current; - if (queue2 !== null) { - ReactCurrentActQueue.didScheduleLegacyUpdate = false; - flushActQueue(queue2); - } - } - } catch (error2) { - popActScope(prevActScopeDepth); - throw error2; - } finally { - ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; - } - if (result !== null && typeof result === "object" && typeof result.then === "function") { - var thenableResult = result; - var wasAwaited = false; - var thenable = { - then: function(resolve, reject) { - wasAwaited = true; - thenableResult.then(function(returnValue2) { - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - recursivelyFlushAsyncActWork(returnValue2, resolve, reject); - } else { - resolve(returnValue2); - } - }, function(error2) { - popActScope(prevActScopeDepth); - reject(error2); - }); - } - }; - { - if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { - Promise.resolve().then(function() { - }).then(function() { - if (!wasAwaited) { - didWarnNoAwaitAct = true; - error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); - } - }); - } - } - return thenable; - } else { - var returnValue = result; - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - var _queue = ReactCurrentActQueue.current; - if (_queue !== null) { - flushActQueue(_queue); - ReactCurrentActQueue.current = null; - } - var _thenable = { - then: function(resolve, reject) { - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } else { - resolve(returnValue); - } - } - }; - return _thenable; - } else { - var _thenable2 = { - then: function(resolve, reject) { - resolve(returnValue); - } - }; - return _thenable2; - } - } - } - } - function popActScope(prevActScopeDepth) { - { - if (prevActScopeDepth !== actScopeDepth - 1) { - error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); - } - actScopeDepth = prevActScopeDepth; - } - } - function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { - { - var queue2 = ReactCurrentActQueue.current; - if (queue2 !== null) { - try { - flushActQueue(queue2); - enqueueTask(function() { - if (queue2.length === 0) { - ReactCurrentActQueue.current = null; - resolve(returnValue); - } else { - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } - }); - } catch (error2) { - reject(error2); - } - } else { - resolve(returnValue); - } - } - } - var isFlushing = false; - function flushActQueue(queue2) { - { - if (!isFlushing) { - isFlushing = true; - var i3 = 0; - try { - for (; i3 < queue2.length; i3++) { - var callback = queue2[i3]; - do { - callback = callback(true); - } while (callback !== null); - } - queue2.length = 0; - } catch (error2) { - queue2 = queue2.slice(i3 + 1); - throw error2; - } finally { - isFlushing = false; - } - } - } - } - var createElement$1 = createElementWithValidation; - var cloneElement$1 = cloneElementWithValidation; - var createFactory = createFactoryWithValidation; - var Children16 = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray: toArray2, - only: onlyChild - }; - exports.Children = Children16; - exports.Component = Component2; - exports.Fragment = REACT_FRAGMENT_TYPE; - exports.Profiler = REACT_PROFILER_TYPE; - exports.PureComponent = PureComponent; - exports.StrictMode = REACT_STRICT_MODE_TYPE; - exports.Suspense = REACT_SUSPENSE_TYPE; - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; - exports.cloneElement = cloneElement$1; - exports.createContext = createContext13; - exports.createElement = createElement$1; - exports.createFactory = createFactory; - exports.createRef = createRef; - exports.forwardRef = forwardRef82; - exports.isValidElement = isValidElement11; - exports.lazy = lazy; - exports.memo = memo3; - exports.startTransition = startTransition; - exports.unstable_act = act; - exports.useCallback = useCallback38; - exports.useContext = useContext14; - exports.useDebugValue = useDebugValue2; - exports.useDeferredValue = useDeferredValue; - exports.useEffect = useEffect51; - exports.useId = useId2; - exports.useImperativeHandle = useImperativeHandle3; - exports.useInsertionEffect = useInsertionEffect; - exports.useLayoutEffect = useLayoutEffect5; - exports.useMemo = useMemo15; - exports.useReducer = useReducer4; - exports.useRef = useRef43; - exports.useState = useState57; - exports.useSyncExternalStore = useSyncExternalStore; - exports.useTransition = useTransition; - exports.version = ReactVersion; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - })(); - } - } -}); - -// node_modules/react/index.js -var require_react = __commonJS({ - "node_modules/react/index.js"(exports, module2) { - "use strict"; - if (false) { - module2.exports = null; - } else { - module2.exports = require_react_development(); - } - } -}); - -// node_modules/scheduler/cjs/scheduler.development.js -var require_scheduler_development = __commonJS({ - "node_modules/scheduler/cjs/scheduler.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var enableSchedulerDebugging = false; - var enableProfiling = false; - var frameYieldMs = 5; - function push3(heap, node) { - var index2 = heap.length; - heap.push(node); - siftUp(heap, node, index2); - } - function peek(heap) { - return heap.length === 0 ? null : heap[0]; - } - function pop(heap) { - if (heap.length === 0) { - return null; - } - var first = heap[0]; - var last = heap.pop(); - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - return first; - } - function siftUp(heap, node, i3) { - var index2 = i3; - while (index2 > 0) { - var parentIndex = index2 - 1 >>> 1; - var parent = heap[parentIndex]; - if (compare2(parent, node) > 0) { - heap[parentIndex] = node; - heap[index2] = parent; - index2 = parentIndex; - } else { - return; - } - } - } - function siftDown(heap, node, i3) { - var index2 = i3; - var length = heap.length; - var halfLength = length >>> 1; - while (index2 < halfLength) { - var leftIndex = (index2 + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; - if (compare2(left, node) < 0) { - if (rightIndex < length && compare2(right, left) < 0) { - heap[index2] = right; - heap[rightIndex] = node; - index2 = rightIndex; - } else { - heap[index2] = left; - heap[leftIndex] = node; - index2 = leftIndex; - } - } else if (rightIndex < length && compare2(right, node) < 0) { - heap[index2] = right; - heap[rightIndex] = node; - index2 = rightIndex; - } else { - return; - } - } - } - function compare2(a3, b3) { - var diff = a3.sortIndex - b3.sortIndex; - return diff !== 0 ? diff : a3.id - b3.id; - } - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - function markTaskErrored(task, ms) { - } - var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; - if (hasPerformanceNow) { - var localPerformance = performance; - exports.unstable_now = function() { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - exports.unstable_now = function() { - return localDate.now() - initialTime; - }; - } - var maxSigned31BitInt = 1073741823; - var IMMEDIATE_PRIORITY_TIMEOUT = -1; - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5e3; - var LOW_PRIORITY_TIMEOUT = 1e4; - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; - var taskQueue = []; - var timerQueue = []; - var taskIdCounter = 1; - var currentTask = null; - var currentPriorityLevel = NormalPriority; - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; - var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; - var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; - var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; - var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - function advanceTimers(currentTime) { - var timer = peek(timerQueue); - while (timer !== null) { - if (timer.callback === null) { - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push3(taskQueue, timer); - } else { - return; - } - timer = peek(timerQueue); - } - } - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - function flushWork(hasTimeRemaining, initialTime2) { - isHostCallbackScheduled = false; - if (isHostTimeoutScheduled) { - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - try { - if (enableProfiling) { - try { - return workLoop(hasTimeRemaining, initialTime2); - } catch (error) { - if (currentTask !== null) { - var currentTime = exports.unstable_now(); - markTaskErrored(currentTask, currentTime); - currentTask.isQueued = false; - } - throw error; - } - } else { - return workLoop(hasTimeRemaining, initialTime2); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - function workLoop(hasTimeRemaining, initialTime2) { - var currentTime = initialTime2; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - while (currentTask !== null && !enableSchedulerDebugging) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { - break; - } - var callback = currentTask.callback; - if (typeof callback === "function") { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - if (typeof continuationCallback === "function") { - currentTask.callback = continuationCallback; - } else { - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - currentTask = peek(taskQueue); - } - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - return false; - } - } - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - default: - priorityLevel = NormalPriority; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_next(eventHandler) { - var priorityLevel; - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - priorityLevel = NormalPriority; - break; - default: - priorityLevel = currentPriorityLevel; - break; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function() { - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime2; - if (typeof options === "object" && options !== null) { - var delay = options.delay; - if (typeof delay === "number" && delay > 0) { - startTime2 = currentTime + delay; - } else { - startTime2 = currentTime; - } - } else { - startTime2 = currentTime; - } - var timeout; - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - var expirationTime = startTime2 + timeout; - var newTask = { - id: taskIdCounter++, - callback, - priorityLevel, - startTime: startTime2, - expirationTime, - sortIndex: -1 - }; - if (startTime2 > currentTime) { - newTask.sortIndex = startTime2; - push3(timerQueue, newTask); - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - if (isHostTimeoutScheduled) { - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } - requestHostTimeout(handleTimeout, startTime2 - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push3(taskQueue, newTask); - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - return newTask; - } - function unstable_pauseExecution() { - } - function unstable_continueExecution() { - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - function unstable_cancelCallback(task) { - task.callback = null; - } - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; - var frameInterval = frameYieldMs; - var startTime = -1; - function shouldYieldToHost() { - var timeElapsed = exports.unstable_now() - startTime; - if (timeElapsed < frameInterval) { - return false; - } - return true; - } - function requestPaint() { - } - function forceFrameRate(fps) { - if (fps < 0 || fps > 125) { - console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); - return; - } - if (fps > 0) { - frameInterval = Math.floor(1e3 / fps); - } else { - frameInterval = frameYieldMs; - } - } - var performWorkUntilDeadline = function() { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); - startTime = currentTime; - var hasTimeRemaining = true; - var hasMoreWork = true; - try { - hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - } finally { - if (hasMoreWork) { - schedulePerformWorkUntilDeadline(); - } else { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } - } - } else { - isMessageLoopRunning = false; - } - }; - var schedulePerformWorkUntilDeadline; - if (typeof localSetImmediate === "function") { - schedulePerformWorkUntilDeadline = function() { - localSetImmediate(performWorkUntilDeadline); - }; - } else if (typeof MessageChannel !== "undefined") { - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - schedulePerformWorkUntilDeadline = function() { - port.postMessage(null); - }; - } else { - schedulePerformWorkUntilDeadline = function() { - localSetTimeout(performWorkUntilDeadline, 0); - }; - } - function requestHostCallback(callback) { - scheduledHostCallback = callback; - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - schedulePerformWorkUntilDeadline(); - } - } - function requestHostTimeout(callback, ms) { - taskTimeoutID = localSetTimeout(function() { - callback(exports.unstable_now()); - }, ms); - } - function cancelHostTimeout() { - localClearTimeout(taskTimeoutID); - taskTimeoutID = -1; - } - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_forceFrameRate = forceFrameRate; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_shouldYield = shouldYieldToHost; - exports.unstable_wrapCallback = unstable_wrapCallback; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - })(); - } - } -}); - -// node_modules/scheduler/index.js -var require_scheduler = __commonJS({ - "node_modules/scheduler/index.js"(exports, module2) { - "use strict"; - if (false) { - module2.exports = null; - } else { - module2.exports = require_scheduler_development(); - } - } -}); - -// node_modules/react-dom/cjs/react-dom.development.js -var require_react_dom_development = __commonJS({ - "node_modules/react-dom/cjs/react-dom.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var React145 = require_react(); - var Scheduler = require_scheduler(); - var ReactSharedInternals = React145.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var suppressWarning = false; - function setSuppressWarning(newSuppressWarning) { - { - suppressWarning = newSuppressWarning; - } - } - function warn2(format) { - { - if (!suppressWarning) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - if (!suppressWarning) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; - var HostRoot = 3; - var HostPortal = 4; - var HostComponent = 5; - var HostText = 6; - var Fragment21 = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var ScopeComponent = 21; - var OffscreenComponent = 22; - var LegacyHiddenComponent = 23; - var CacheComponent = 24; - var TracingMarkerComponent = 25; - var enableClientRenderFallbackOnTextMismatch = true; - var enableNewReconciler = false; - var enableLazyContextPropagation = false; - var enableLegacyHidden = false; - var enableSuspenseAvoidThisFallback = false; - var disableCommentsAsDOMContainers = true; - var enableCustomElementPropertySupport = false; - var warnAboutStringRefs = false; - var enableSchedulingProfiler = true; - var enableProfilerTimer = true; - var enableProfilerCommitHooks = true; - var allNativeEvents = /* @__PURE__ */ new Set(); - var registrationNameDependencies = {}; - var possibleRegistrationNames = {}; - function registerTwoPhaseEvent(registrationName, dependencies) { - registerDirectEvent(registrationName, dependencies); - registerDirectEvent(registrationName + "Capture", dependencies); - } - function registerDirectEvent(registrationName, dependencies) { - { - if (registrationNameDependencies[registrationName]) { - error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); - } - } - registrationNameDependencies[registrationName] = dependencies; - { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - if (registrationName === "onDoubleClick") { - possibleRegistrationNames.ondblclick = registrationName; - } - } - for (var i3 = 0; i3 < dependencies.length; i3++) { - allNativeEvents.add(dependencies[i3]); - } - } - var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); - var hasOwnProperty3 = Object.prototype.hasOwnProperty; - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e3) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkAttributeStringCoercion(value, attributeName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function checkPropStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkCSSPropertyStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkHtmlStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function checkFormFieldValueStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - var RESERVED = 0; - var STRING = 1; - var BOOLEANISH_STRING = 2; - var BOOLEAN = 3; - var OVERLOADED_BOOLEAN = 4; - var NUMERIC = 5; - var POSITIVE_NUMERIC = 6; - var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); - var illegalAttributeNameCache = {}; - var validatedAttributeNameCache = {}; - function isAttributeNameSafe(attributeName) { - if (hasOwnProperty3.call(validatedAttributeNameCache, attributeName)) { - return true; - } - if (hasOwnProperty3.call(illegalAttributeNameCache, attributeName)) { - return false; - } - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - illegalAttributeNameCache[attributeName] = true; - { - error("Invalid attribute name: `%s`", attributeName); - } - return false; - } - function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED; - } - if (isCustomComponentTag) { - return false; - } - if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { - return true; - } - return false; - } - function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - switch (typeof value) { - case "function": - case "symbol": - return true; - case "boolean": { - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix2 = name.toLowerCase().slice(0, 5); - return prefix2 !== "data-" && prefix2 !== "aria-"; - } - } - default: - return false; - } - } - function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { - if (value === null || typeof value === "undefined") { - return true; - } - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { - return true; - } - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value; - case OVERLOADED_BOOLEAN: - return value === false; - case NUMERIC: - return isNaN(value); - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1; - } - } - return false; - } - function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; - } - function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; - this.sanitizeURL = sanitizeURL2; - this.removeEmptyString = removeEmptyString; - } - var properties = {}; - var reservedProps = [ - "children", - "dangerouslySetInnerHTML", - // TODO: This prevents the assignment of defaultValue to regular - // elements (not just inputs). Now that ReactDOMInput assigns to the - // defaultValue property -- do we need this? - "defaultValue", - "defaultChecked", - "innerHTML", - "suppressContentEditableWarning", - "suppressHydrationWarning", - "style" - ]; - reservedProps.forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - RESERVED, - false, - // mustUseProperty - name, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { - var name = _ref[0], attributeName = _ref[1]; - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - // mustUseProperty - attributeName, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, - // mustUseProperty - name.toLowerCase(), - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEANISH_STRING, - false, - // mustUseProperty - name, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [ - "allowFullScreen", - "async", - // Note: there is a special case that prevents it from being written to the DOM - // on the client side because the browsers are inconsistent. Instead we call focus(). - "autoFocus", - "autoPlay", - "controls", - "default", - "defer", - "disabled", - "disablePictureInPicture", - "disableRemotePlayback", - "formNoValidate", - "hidden", - "loop", - "noModule", - "noValidate", - "open", - "playsInline", - "readOnly", - "required", - "reversed", - "scoped", - "seamless", - // Microdata - "itemScope" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - false, - // mustUseProperty - name.toLowerCase(), - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [ - "checked", - // Note: `option.selected` is not updated if `select.multiple` is - // disabled with `removeAttribute`. We have special logic for handling this. - "multiple", - "muted", - "selected" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - BOOLEAN, - true, - // mustUseProperty - name, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [ - "capture", - "download" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - OVERLOADED_BOOLEAN, - false, - // mustUseProperty - name, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [ - "cols", - "rows", - "size", - "span" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - POSITIVE_NUMERIC, - false, - // mustUseProperty - name, - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - ["rowSpan", "start"].forEach(function(name) { - properties[name] = new PropertyInfoRecord( - name, - NUMERIC, - false, - // mustUseProperty - name.toLowerCase(), - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - var CAMELIZE = /[\-\:]([a-z])/g; - var capitalize = function(token) { - return token[1].toUpperCase(); - }; - [ - "accent-height", - "alignment-baseline", - "arabic-form", - "baseline-shift", - "cap-height", - "clip-path", - "clip-rule", - "color-interpolation", - "color-interpolation-filters", - "color-profile", - "color-rendering", - "dominant-baseline", - "enable-background", - "fill-opacity", - "fill-rule", - "flood-color", - "flood-opacity", - "font-family", - "font-size", - "font-size-adjust", - "font-stretch", - "font-style", - "font-variant", - "font-weight", - "glyph-name", - "glyph-orientation-horizontal", - "glyph-orientation-vertical", - "horiz-adv-x", - "horiz-origin-x", - "image-rendering", - "letter-spacing", - "lighting-color", - "marker-end", - "marker-mid", - "marker-start", - "overline-position", - "overline-thickness", - "paint-order", - "panose-1", - "pointer-events", - "rendering-intent", - "shape-rendering", - "stop-color", - "stop-opacity", - "strikethrough-position", - "strikethrough-thickness", - "stroke-dasharray", - "stroke-dashoffset", - "stroke-linecap", - "stroke-linejoin", - "stroke-miterlimit", - "stroke-opacity", - "stroke-width", - "text-anchor", - "text-decoration", - "text-rendering", - "underline-position", - "underline-thickness", - "unicode-bidi", - "unicode-range", - "units-per-em", - "v-alphabetic", - "v-hanging", - "v-ideographic", - "v-mathematical", - "vector-effect", - "vert-adv-y", - "vert-origin-x", - "vert-origin-y", - "word-spacing", - "writing-mode", - "xmlns:xlink", - "x-height" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - // mustUseProperty - attributeName, - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - [ - "xlink:actuate", - "xlink:arcrole", - "xlink:role", - "xlink:show", - "xlink:title", - "xlink:type" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - // mustUseProperty - attributeName, - "http://www.w3.org/1999/xlink", - false, - // sanitizeURL - false - ); - }); - [ - "xml:base", - "xml:lang", - "xml:space" - // NOTE: if you add a camelCased prop to this list, - // you'll need to set attributeName to name.toLowerCase() - // instead in the assignment below. - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord( - name, - STRING, - false, - // mustUseProperty - attributeName, - "http://www.w3.org/XML/1998/namespace", - false, - // sanitizeURL - false - ); - }); - ["tabIndex", "crossOrigin"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, - // mustUseProperty - attributeName.toLowerCase(), - // attributeName - null, - // attributeNamespace - false, - // sanitizeURL - false - ); - }); - var xlinkHref = "xlinkHref"; - properties[xlinkHref] = new PropertyInfoRecord( - "xlinkHref", - STRING, - false, - // mustUseProperty - "xlink:href", - "http://www.w3.org/1999/xlink", - true, - // sanitizeURL - false - ); - ["src", "href", "action", "formAction"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord( - attributeName, - STRING, - false, - // mustUseProperty - attributeName.toLowerCase(), - // attributeName - null, - // attributeNamespace - true, - // sanitizeURL - true - ); - }); - var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; - var didWarn = false; - function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true; - error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); - } - } - } - function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName; - return node[propertyName]; - } else { - { - checkAttributeStringCoercion(expected, name); - } - if (propertyInfo.sanitizeURL) { - sanitizeURL("" + expected); - } - var attributeName = propertyInfo.attributeName; - var stringValue = null; - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName); - if (value === "") { - return true; - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return value; - } - if (value === "" + expected) { - return expected; - } - return value; - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return node.getAttribute(attributeName); - } - if (propertyInfo.type === BOOLEAN) { - return expected; - } - stringValue = node.getAttribute(attributeName); - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue; - } else if (stringValue === "" + expected) { - return expected; - } else { - return stringValue; - } - } - } - } - function getValueForAttribute(node, name, expected, isCustomComponentTag) { - { - if (!isAttributeNameSafe(name)) { - return; - } - if (!node.hasAttribute(name)) { - return expected === void 0 ? void 0 : null; - } - var value = node.getAttribute(name); - { - checkAttributeStringCoercion(expected, name); - } - if (value === "" + expected) { - return expected; - } - return value; - } - } - function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name); - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return; - } - if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { - value = null; - } - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name; - if (value === null) { - node.removeAttribute(_attributeName); - } else { - { - checkAttributeStringCoercion(value, name); - } - node.setAttribute(_attributeName, "" + value); - } - } - return; - } - var mustUseProperty = propertyInfo.mustUseProperty; - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName; - if (value === null) { - var type = propertyInfo.type; - node[propertyName] = type === BOOLEAN ? false : ""; - } else { - node[propertyName] = value; - } - return; - } - var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; - if (value === null) { - node.removeAttribute(attributeName); - } else { - var _type = propertyInfo.type; - var attributeValue; - if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { - attributeValue = ""; - } else { - { - { - checkAttributeStringCoercion(value, attributeName); - } - attributeValue = "" + value; - } - if (propertyInfo.sanitizeURL) { - sanitizeURL(attributeValue.toString()); - } - } - if (attributeNamespace) { - node.setAttributeNS(attributeNamespace, attributeName, attributeValue); - } else { - node.setAttribute(attributeName, attributeValue); - } - } - } - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_SCOPE_TYPE = Symbol.for("react.scope"); - var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); - var REACT_CACHE_TYPE = Symbol.for("react.cache"); - var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var assign = Object.assign; - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x2) { - var match2 = x2.stack.trim().match(/\n( *(at )?)/); - prefix = match2 && match2[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x2) { - control = x2; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x2) { - control = x2; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x2) { - control = x2; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s4 = sampleLines.length - 1; - var c4 = controlLines.length - 1; - while (s4 >= 1 && c4 >= 0 && sampleLines[s4] !== controlLines[c4]) { - c4--; - } - for (; s4 >= 1 && c4 >= 0; s4--, c4--) { - if (sampleLines[s4] !== controlLines[c4]) { - if (s4 !== 1 || c4 !== 1) { - do { - s4--; - c4--; - if (c4 < 0 || sampleLines[s4] !== controlLines[c4]) { - var _frame = "\n" + sampleLines[s4].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s4 >= 1 && c4 >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component2) { - var prototype = Component2.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x2) { - } - } - } - } - return ""; - } - function describeFiber(fiber) { - var owner = fiber._debugOwner ? fiber._debugOwner.type : null; - var source = fiber._debugSource; - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - case LazyComponent: - return describeBuiltInComponentFrame("Lazy"); - case SuspenseComponent: - return describeBuiltInComponentFrame("Suspense"); - case SuspenseListComponent: - return describeBuiltInComponentFrame("SuspenseList"); - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - case ClassComponent: - return describeClassComponentFrame(fiber.type); - default: - return ""; - } - } - function getStackByFiberInDevAndProd(workInProgress2) { - try { - var info = ""; - var node = workInProgress2; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; - } catch (x2) { - return "\nError generating stack: " + x2.message + "\n" + x2.stack; - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x2) { - return null; - } - } - } - } - return null; - } - function getWrappedName$1(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName$1(type) { - return type.displayName || "Context"; - } - function getComponentNameFromFiber(fiber) { - var tag = fiber.tag, type = fiber.type; - switch (tag) { - case CacheComponent: - return "Cache"; - case ContextConsumer: - var context = type; - return getContextName$1(context) + ".Consumer"; - case ContextProvider: - var provider = type; - return getContextName$1(provider._context) + ".Provider"; - case DehydratedFragment: - return "DehydratedFragment"; - case ForwardRef: - return getWrappedName$1(type, type.render, "ForwardRef"); - case Fragment21: - return "Fragment"; - case HostComponent: - return type; - case HostPortal: - return "Portal"; - case HostRoot: - return "Root"; - case HostText: - return "Text"; - case LazyComponent: - return getComponentNameFromType(type); - case Mode: - if (type === REACT_STRICT_MODE_TYPE) { - return "StrictMode"; - } - return "Mode"; - case OffscreenComponent: - return "Offscreen"; - case Profiler: - return "Profiler"; - case ScopeComponent: - return "Scope"; - case SuspenseComponent: - return "Suspense"; - case SuspenseListComponent: - return "SuspenseList"; - case TracingMarkerComponent: - return "TracingMarker"; - case ClassComponent: - case FunctionComponent: - case IncompleteClassComponent: - case IndeterminateComponent: - case MemoComponent: - case SimpleMemoComponent: - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - break; - } - return null; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== "undefined") { - return getComponentNameFromFiber(owner); - } - } - return null; - } - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ""; - } - return getStackByFiberInDevAndProd(current); - } - } - function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function getCurrentFiber() { - { - return current; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - function toString(value) { - return "" + value; - } - function getToStringValue(value) { - switch (typeof value) { - case "boolean": - case "number": - case "string": - case "undefined": - return value; - case "object": - { - checkFormFieldValueStringCoercion(value); - } - return value; - default: - return ""; - } - } - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - function checkControlledValueProps(tagName, props) { - { - if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { - error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); - } - if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { - error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); - } - } - } - function isCheckable(elem) { - var type = elem.type; - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); - } - function getTracker(node) { - return node._valueTracker; - } - function detachTracker(node) { - node._valueTracker = null; - } - function getValueFromNode(node) { - var value = ""; - if (!node) { - return value; - } - if (isCheckable(node)) { - value = node.checked ? "true" : "false"; - } else { - value = node.value; - } - return value; - } - function trackValueOnNode(node) { - var valueField = isCheckable(node) ? "checked" : "value"; - var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - { - checkFormFieldValueStringCoercion(node[valueField]); - } - var currentValue = "" + node[valueField]; - if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { - return; - } - var get5 = descriptor.get, set2 = descriptor.set; - Object.defineProperty(node, valueField, { - configurable: true, - get: function() { - return get5.call(this); - }, - set: function(value) { - { - checkFormFieldValueStringCoercion(value); - } - currentValue = "" + value; - set2.call(this, value); - } - }); - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable - }); - var tracker = { - getValue: function() { - return currentValue; - }, - setValue: function(value) { - { - checkFormFieldValueStringCoercion(value); - } - currentValue = "" + value; - }, - stopTracking: function() { - detachTracker(node); - delete node[valueField]; - } - }; - return tracker; - } - function track(node) { - if (getTracker(node)) { - return; - } - node._valueTracker = trackValueOnNode(node); - } - function updateValueIfChanged(node) { - if (!node) { - return false; - } - var tracker = getTracker(node); - if (!tracker) { - return true; - } - var lastValue = tracker.getValue(); - var nextValue = getValueFromNode(node); - if (nextValue !== lastValue) { - tracker.setValue(nextValue); - return true; - } - return false; - } - function getActiveElement(doc) { - doc = doc || (typeof document !== "undefined" ? document : void 0); - if (typeof doc === "undefined") { - return null; - } - try { - return doc.activeElement || doc.body; - } catch (e3) { - return doc.body; - } - } - var didWarnValueDefaultValue = false; - var didWarnCheckedDefaultChecked = false; - var didWarnControlledToUncontrolled = false; - var didWarnUncontrolledToControlled = false; - function isControlled(props) { - var usesChecked = props.type === "checkbox" || props.type === "radio"; - return usesChecked ? props.checked != null : props.value != null; - } - function getHostProps(element, props) { - var node = element; - var checked = props.checked; - var hostProps = assign({}, props, { - defaultChecked: void 0, - defaultValue: void 0, - value: void 0, - checked: checked != null ? checked : node._wrapperState.initialChecked - }); - return hostProps; - } - function initWrapperState(element, props) { - { - checkControlledValueProps("input", props); - if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { - error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnCheckedDefaultChecked = true; - } - if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { - error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnValueDefaultValue = true; - } - } - var node = element; - var defaultValue = props.defaultValue == null ? "" : props.defaultValue; - node._wrapperState = { - initialChecked: props.checked != null ? props.checked : props.defaultChecked, - initialValue: getToStringValue(props.value != null ? props.value : defaultValue), - controlled: isControlled(props) - }; - } - function updateChecked(element, props) { - var node = element; - var checked = props.checked; - if (checked != null) { - setValueForProperty(node, "checked", checked, false); - } - } - function updateWrapper(element, props) { - var node = element; - { - var controlled = isControlled(props); - if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { - error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnUncontrolledToControlled = true; - } - if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { - error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnControlledToUncontrolled = true; - } - } - updateChecked(element, props); - var value = getToStringValue(props.value); - var type = props.type; - if (value != null) { - if (type === "number") { - if (value === 0 && node.value === "" || // We explicitly want to coerce to number here if possible. - // eslint-disable-next-line - node.value != value) { - node.value = toString(value); - } - } else if (node.value !== toString(value)) { - node.value = toString(value); - } - } else if (type === "submit" || type === "reset") { - node.removeAttribute("value"); - return; - } - { - if (props.hasOwnProperty("value")) { - setDefaultValue(node, props.type, value); - } else if (props.hasOwnProperty("defaultValue")) { - setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); - } - } - { - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked; - } - } - } - function postMountWrapper(element, props, isHydrating2) { - var node = element; - if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { - var type = props.type; - var isButton = type === "submit" || type === "reset"; - if (isButton && (props.value === void 0 || props.value === null)) { - return; - } - var initialValue = toString(node._wrapperState.initialValue); - if (!isHydrating2) { - { - if (initialValue !== node.value) { - node.value = initialValue; - } - } - } - { - node.defaultValue = initialValue; - } - } - var name = node.name; - if (name !== "") { - node.name = ""; - } - { - node.defaultChecked = !node.defaultChecked; - node.defaultChecked = !!node._wrapperState.initialChecked; - } - if (name !== "") { - node.name = name; - } - } - function restoreControlledState(element, props) { - var node = element; - updateWrapper(node, props); - updateNamedCousins(node, props); - } - function updateNamedCousins(rootNode, props) { - var name = props.name; - if (props.type === "radio" && name != null) { - var queryRoot = rootNode; - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode; - } - { - checkAttributeStringCoercion(name, "name"); - } - var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); - for (var i3 = 0; i3 < group.length; i3++) { - var otherNode = group[i3]; - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue; - } - var otherProps = getFiberCurrentPropsFromNode(otherNode); - if (!otherProps) { - throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); - } - updateValueIfChanged(otherNode); - updateWrapper(otherNode, otherProps); - } - } - } - function setDefaultValue(node, type, value) { - if ( - // Focused number inputs synchronize on blur. See ChangeEventPlugin.js - type !== "number" || getActiveElement(node.ownerDocument) !== node - ) { - if (value == null) { - node.defaultValue = toString(node._wrapperState.initialValue); - } else if (node.defaultValue !== toString(value)) { - node.defaultValue = toString(value); - } - } - } - var didWarnSelectedSetOnOption = false; - var didWarnInvalidChild = false; - var didWarnInvalidInnerHTML = false; - function validateProps(element, props) { - { - if (props.value == null) { - if (typeof props.children === "object" && props.children !== null) { - React145.Children.forEach(props.children, function(child) { - if (child == null) { - return; - } - if (typeof child === "string" || typeof child === "number") { - return; - } - if (!didWarnInvalidChild) { - didWarnInvalidChild = true; - error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to